pragma(explicit_gc)
Timon Gehr
timon.gehr at gmx.ch
Sat May 4 14:35:07 UTC 2024
On 5/2/24 03:45, Timon Gehr wrote:
> Often, GC is nice but collections should be avoided in an inner loop.
> `@nogc` is too restrictive because may be fine to e.g., allocate an
> `Exception` before throwing it, and programmers are aware that such
> allocations are happening.
>
> A somewhat more insidious case is implicit allocation, because even when
> programs look like they do need to allocate, they may in fact allocate
> due to the compiler's escape analysis being too weak.
>
> For example, there is no reason for the following program to allocate
> with the GC, but it does implicitly allocate a closure:
>
> ```d
> void main(){ // errors with @nogc
> auto y=2;
> assert(iota(10).filter!((x)=>x%y!=0).sum==25);
> }
> ```
>
> In case the GC is disabled, such imprecise escape analysis in an inner
> loop may result in a memory leak.
>
> Proposal: Add `pragma(explicit_gc)`. Functions marked with this pragma
> will non-transitively error out on implicit GC allocations. This is a
> useful tool to check expectations about escape analysis precision.
Merged into OpenD: https://github.com/opendlang/opend/pull/69
Can be cherry-picked from there.
More information about the dip.ideas
mailing list