Libraries that are both nogc and gc?

Ola Fosheim Grøstad ola.fosheim.grostad at
Sat Nov 21 12:14:58 UTC 2020

Let's assume that all the useful D constructs like class objects, 
dynamic arrays, associative arrays, delegates, exceptions are 
allocated with a reference count at a negative offset (which can 
be optimized away during static analysis).

Then it should be possible to write library code that supports 
both gc and nogc. It seems to me that this would be possible if:

- all functions are templated behind the scenes with a hidden 
template parameter "allocator_strategy". This parameter is 
inherited from the calling context unless it is explicitly set.

- library aggregates (classes structs) have to use a specific 
notation for owning pointers and nonowning pointers. This will 
also speed up GC collection if the collector is precise (it does 
not have to follow nonowning pointers).

If the context is "allocator_gc" then it will just use raw 
pointers, and mark the ones that are owning for tracing and also 
be careful about using gc_root IR intrinsics when calling 
C-functions to makes sure that the pointer is live during the 
function call.

If the context is "allocator_arc" then it will use an ARC pointer 
and emit acquire/release (retain/release) intrinsics at the IR 
level (or AST).

If the context is "allocator_bump" then it will just emit C-like 

Please note that this is static, not dynamic, so it should yield 
efficient code.

More information about the Digitalmars-d mailing list