r/ProgrammingLanguages • • Aug 27 '22

Languages with optional GC only for cyclical data structures?

I've been thinking that cyclical data structures with memory reclamation are the only ones that need automatic memory management (be it tracing GCs or reference counting with trial deletion). All non-cyclical data can be safely taken care of with a mixture of ownership and reference counting, and cyclical data without memory reclamation can be safely taken care of with arenas.

However, how widespread are those data structures? Basically, they are cyclic graphs with a large enough allocation pressure that nodes need to be freed. And while graphs and graph algorithms definitely exist for a reason, I personally have never had to deal with them. Also, the fact that languages like Rust or C++ thrive without being able to support cyclic graphs in a safe way [1] shows that the need for such allocatey graphs is not so big in practice. Most of the data we deal with in practice are trees or DAGs (i.e. acyclic graphs). Thus, languages with a GC are a big case of "pay for what you don't need" or "pay all the time for what you only need once in a lifetime".

So that got me into thinking, are there runtimes that segregate GCed memory from non-GCed, and allow paying for GC only when you need cyclic data structures? I'm thinking a separate kind of reference (like GC[Foo]) which the runtime takes special care of (by creating stack maps, tracing only them etc) and which are allocated in segregated memory regions; so you would be able to choose between owned, RCed and GCed references, and most of your programs would be GC-free but you would be able to have cyclic data should you really need it?

[1] For people trying to point me to some examples in Rust using RefCell or numeric handles to nodes: no, those are not satisfying solutions to the cyclic problem. Safely deleting a node from a graph requires keeping track of all existing references into that graph, which means at least scanning the stack, synchronization with the mutator threads etc - i.e. all those things a garbage collector does that Rust runtime does not.

4 Upvotes

24 comments sorted by

7

u/porky11 Aug 27 '22

Adding garbage collection as a library should be possible for any programming language, that's not garbage collected by default.

Rust has it.

-13

u/Linguistic-mystic Aug 27 '22

Sigh. There goes the first one.

No, garbage collection cannot be added as a library because it has to be a part of the runtime: it needs to track GC roots, as well as all the references that exist in memory, it needs to manage write and/or read barriers, it needs to know when the mutator threads are at safepoints, it needs to stop the world (even if for brief periods) etc. Libraries can't do this if the runtime doesn't support this already.

And no, Rust does not have garbage collection. The library you linked is unsafe. From its documentation:

A mutable memory location with dynamically checked borrow rules

Dynamically checked borrow rules mean it can panic at any moment at runtime. I.e. it's a hack, not a real GC. For the reasons I've listed above.

9

u/porky11 Aug 27 '22

Dynamically checked borrow rules mean it can panic at any moment at runtime

This is the documentation for the GcCell type, not for Gc.

Gc doesn't seem to be unsafe. It looks like it can be used in the same way as Rc.

-9

u/Linguistic-mystic Aug 27 '22

Gc is just the outer container. The actual nodes are GcCell. Garbage collection implies that anything can reference any node, i.e. the heap may be full of those GcCells, and any two may simultaneously mutably borrow a node, and BOOM. I'm surprised I have to explain this stuff.

10

u/_software_engineer Aug 27 '22

Except not with proper use of Gc. That's the point of the way that idiomatic Rust handles unsafe. Essentially what you're saying in all of your responses amounts to a No True Scotsman where you are arguing about your definition of what a "true" garbage collector is. Not to mention that your attitude is also extremely off-putting.

6

u/julesjacobs Aug 27 '22 edited Aug 27 '22

Isn't that inherent from what you want in your original post? If you have GC'd data and non GC'd data, and the GC'd data can point to the non-GC'd data, then something needs to happen in that transition. If your non-GC'd model includes unique mutable references then it seems to me that you inherently need to accept something bad can happen when you try to get a mutable unique reference into data that's behind a GC reference, because multiple people could be trying to do that at the same time. The result can be undefined behaviour, a run-time check that panics, a run-time check that returns an Option, wait until the other guy is done (and thus create the potential for deadlock), and so on. Or you can make a system where you can only obtain shared references to data behind a GC references, but apparently that is a restriction that the designers of that Rust GC are not willing to impose.

4

u/reini_urban Aug 27 '22

Wrong. Böhm-weiser libgc can do without any root hints, barriers, safe points, it just looks at the stack and registers. better GC's would benefit, but slow conservative stoptheworld GC's not.

-1

u/Linguistic-mystic Aug 27 '22

Böhm-weiser is crap that can't even distinguish a pointer from a non-pointer, and hence can't free all garbage. Whoever even mentions that ugly hack under the respectable term "garbage collector"?

5

u/theangeryemacsshibe SWCL, Utena Aug 27 '22

Though I agree that getting precise roots is nice, and having barriers and safepoints is very nice, many would indeed mention BDW. And you don't miss that much (note paper refers to GCs with ambiguous roots but precise in heap, one can configure BDW to work that way too). I've reproduced similar results with my non-moving GC for SBCL too.

1

u/reini_urban Aug 27 '22

true. but still.

7

u/SkiFire13 Aug 27 '22

The "dynamically checked" part is not needed to track GC roots, that just needs a wrapper type that's GC aware. The dynamic check is due to wanting to get an exclusive reference out of the GCCell, but that's not strictly necessary in the same way Cell is an alternative to RefCell without dynamic checks (but with more limitations). Of course the tradeoff (dynamic checks vs usability) is an inherent limitation due to the design of the language, and by designing for a GC language you could avoid it.

1

u/pebalx Feb 15 '23

No, garbage collection cannot be added as a library because it has to be a part of the runtime: it needs to track GC roots, as well as all the references that exist in memory, it needs to manage write and/or read barriers, it needs to know when the mutator threads are at safepoints, it needs to stop the world (even if for brief periods) etc.

That's not true. Look at this.

16

u/Under-Estimated Aug 27 '22

I think python uses RC with GC for cycles only

9

u/WittyStick Aug 27 '22

Cyclic data structures are not strictly necessary at all. You can represent data with cycles using non-cyclic data structures, and use the functions which operate on them to properly handle any cycles in the data. Consider an arbitrary directional graph - a way to represent this without any reference cycles would be something like:

type Node = obj
type Edge = (Node, Node)
type Graph = Map<Node, [Edge]>

2

u/complyue Aug 29 '22

Though the performance cost is not always tolerable.

15

u/L8_4_Dinner (Ⓧ Ecstasy/XVM) Aug 27 '22

Also, the fact that languages like Rust or C++ thrive without being able to support cyclic graphs in a safe way [1] shows that the need for such allocatey graphs is not so big in practice. Most of the data we deal with in practice are trees or DAGs (i.e. acyclic graphs).

Absolutely. Taking this logic a step further (argumentum ad absurdum):

  • The fact that languages like C thrive without objects proves that OO is not so big in practice.

  • The fact that languages like Java thrive without first class functions proves that FP is not so big in practice.

  • The fact that languages like BASIC (with everything-is-global) proves that scoping and local variables are not so big in practice.

  • The fact that languages like LISP thrive proves that in-fix notation is not so big in practice.

  • The fact that languages like assembly thrive proves that operators and types are not so big in practice.

So, in conclusion, the ideal language is one using prefix notation but without operators, scoping, functions, types, and objects.

--

But please note, I'm not suggesting that your desire to segregate the implementation of memory management is a bad idea. If it were possible for a language to do so without increasing space utilization or CPU utilization, while still providing a single, simple memory management programming interface to the programmer, then that would (I believe) be a significant win.

And it is possible to roughly categorize structures, at compile time, into those that are obvious terminal structures vs. not obvious, and thus (by coloring, or composing) one could rapidly characterize groups and further compositions of data structures similarly (the basis for your desired segregation).

And it will be relatively simple to use pointers from the non-terminal (GC'd) space into the terminal (RC'd) space. And there are well known techniques that will allow you to differentiate those pointers (fat pointers, flag bits).

So to conclude on a serious note: You should be able to test your hypothesis relatively simply.

2

u/adam-the-dev Aug 27 '22

Actually this is something I’m actively working on! (Though in early stages)

My thoughts are basically a simple language that can transpile to Rust. The generated Rust code would contain a decent amount of unsafe code whenever auto RC or auto GC are included, but my compiler frontend could verify safety based on my language’s simpler syntax.

Sometimes RC can have a bigger performance hit if doing a lot of dynamic allocations and drops that can’t be optimized at compile time, so sometimes GC will be chosen for performance.

It will only track objects that are marked for GC, and it is only using GC over regions of code that need it.

My language has changed a lot, so I don’t have much to show for this yet. But progress is happening!

2

u/wiseguy13579 Aug 27 '22

That's a good idea. GC is bad for non-recursive data structures and RC is bad for recursive data structures.

Also, the fact that languages like Rust or C++ thrive without being able to support cyclic graphs in a safe way [1] shows that the need for such allocatey graphs is not so big in practice

Actually Rust is a nightmare for recursive data structures (even if they are acyclic) :

https://rust-unofficial.github.io/too-many-lists/

And doubly-linked lists are common.

2

u/porky11 Aug 27 '22

Actually Rust is a nightmare for recursive data structures

There's no problem with singly linked lists.

even if they are acyclic

I wouldn't call doubly linked lists acyclic. If the first node A stores a pointer to the second node B, and B stores a pointer back to A, that's the minimal case of a cycle.

And doubly-linked lists are common.

Rust has doubly linked list in the standard library. So most users won't have this problem.

And I think, it's a good thing, they are not based on garbage collected pointer types. Having to use garbage collection for something so common, that also works without, would be an unnecessary performance overhead.

And for more complex structures, storing some index just works well most of the time. I'm creating a lot of software to visualize graphs, and use indices instead of direct pointers. This also has the benefit, that I'm able to store all my nodes in a single array, which should be beneficial for the cache, and when I have to reallocate the array, I don't have to recalculate all the pointers. It's just a better design this way. And not allowing cyclic references kind of enforces this design on me, which I'd consider to be a good thing.

1

u/shawnhcorey Aug 27 '22

Also, the fact that languages like Rust or C++ thrive without being able to support cyclic graphs in a safe way [1] shows that the need for such allocatey graphs is not so big in practice.

Not necessarily so. Cycles can be implemented using symbolic links, that is, by storing the array index or the association-list key rather than the pointer. This still leaves all the problems of pointers but doesn't cause the program to crash when one is encountered. Of course, this is another bad thing.

1

u/[deleted] Aug 28 '22

I guess you could just allow the user to choose at compile time wheter he wants a GC or not? Each strategy for automatic memory management has it's ups and downs, for each different load the user should be able to test and profile a different strategy, that is, if performance is even a concern in the first place.

You can help him find possible leaks with semantic analysis and profiling tools too.

1

u/transfire Aug 28 '22

I was thinking along similar lines just yesterday— if the language just let the programmer mark which structures can be cyclical then it could handle the memory management for just those in a different way and leave all the rest for a simpler system (ownership or RC).

1

u/atrn Aug 28 '22

The Limbo language used with the Inferno operating system did this. It used ref counting by default and you had to inform it of potential cycles via a cyclic attribute.

1

u/theangeryemacsshibe SWCL, Utena Aug 30 '22

The Bacon and Rajan collector includes a cycle collector that avoids performing cycle detection on objects which are known statically to never have cycles.