vala: implement a garbage collector.
authorSimon Tatham <anakin@pobox.com>
Sun, 12 May 2019 09:05:34 +0000 (10:05 +0100)
committerSimon Tatham <anakin@pobox.com>
Mon, 13 May 2019 14:40:47 +0000 (15:40 +0100)
commit5ff3e2e8081a42858125bf3fafa78bad048dbfa0
tree81ae4204c9336f76b1cc0f767ebd5cf17847dd92
parent54c4ae6192e6ea11643cec3d48017a142a8fa69c
vala: implement a garbage collector.

This fixes a lot of memory leakage due to me having relied on the Vala
reference-counting system to do my memory management.

The most obvious bad result of that design decision was the memory
leak from Mal.Nil pointing to itself as metadata. But fixing that
didn't solve the whole problem, because other kinds of reference cycle
are common.

In particular, the idiom `(def! FUNC (fn* (ARGS) BODY))`, for defining
a function in the most obvious way, would create a cycle of two
objects: from the outer environment in which FUNC is defined, to the
function object for FUNC itself, back to that same environment because
it was captured by FUNC.

And _either_ of those objects could end up being the only element of
the cycle referred to from the rest of the system: it could be the
environment, if nothing ever uses that function definition, or it
could be the function, if that function object is looked up and
returned from an outer function that was the last user of the
environment. So you can't break the cycle in the way that reference
counting systems would like you to, by making a well-chosen one of the
links weak: there's no universally right choice for which one it needs
to be.

So I've fixed it properly by writing a simple garbage collector. In
Vala's ref-counted environment, that works by being the only thing
allowed to hold an _owning_ reference to any derivative of GC.Object.
All the normal kinds of link between objects are now weak references;
each object provides a gc_traverse method which lists all the things
it links to; and when the garbage collector runs, it unlinks any
unwanted objects from its big linked list of all of them, causing the
one owned reference to each one to disappear.

Now the perf3 test can run without its memory usage gradually
increasing.
16 files changed:
vala/Makefile
vala/README.md
vala/core.vala
vala/env.vala
vala/gc.vala [new file with mode: 0644]
vala/step1_read_print.vala
vala/step2_eval.vala
vala/step3_env.vala
vala/step4_if_fn_do.vala
vala/step5_tco.vala
vala/step6_file.vala
vala/step7_quote.vala
vala/step8_macros.vala
vala/step9_try.vala
vala/stepA_mal.vala
vala/types.vala