explore gc finalizers
Description
As grain is garbage collected it would be nice if we added support for finalizers basically a function that get's called right before the data is collected.
Some example use cases are:
- Wit-bindgen, we need to alert the host that we are done with resources
- The only way we can really support this right now is by overriding
decRefin the runtime forwit-bindgen - wasm-gc will probably have some way to support this with wasm-gc so finalizers seem more relevant for linear memory
- The only way we can really support this right now is by overriding
- File Streams, We need to close the stream after the user is done with it
- Even after wasm-gc we kind of need to figure this out, by file streams I am not refering to async streams here I mean something more like
File.open,File.readLine,File.close
- Even after wasm-gc we kind of need to figure this out, by file streams I am not refering to async streams here I mean something more like
Semantics:
- This would need some discussion but I think for an
MVPit would be fine if we just supported finalizers
Implementation:
Wasm-GC
Currently finalizers are not supported by wasm-gc so we would need to figure this out ourselves, without having support for wasm-gc in grain yet though I think it would be best to postpone thinking too far into this but it is something we need to consider before implementing.
Linear Memory
We have to be pretty careful playing with our low level data structures so we don't break the runtime but I think there are two options here, we could either add an extra pointer to a function index for the destructor before the type which would change the layout and possibly break things or currently we store 32-bits of padding between the reference count and the pointer where we could put the function index without breaking things.
Either way a finalizer would be a grain function (without closure support) which we would call before deallocating.
After some discussion on discord we have come to the conclusion that as wasm-gc does not currently support finalization we are not going to add it for now.
Here is a branch with some changes made supporting finalizers in linear memory if it is of any use later here. It takes advantage of an extra 32 bits of padding after our reference count so the changes are rather minimal.
Blocked waiting to see what wasm-gc does in respect to finalizers.