Migrating an existing more modern GC to D's gc.d

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Apr 10 08:56:02 UTC 2018


On Tuesday, April 10, 2018 08:37:47 David Bennett via Digitalmars-d wrote:
> On Tuesday, 10 April 2018 at 08:10:32 UTC, Jonathan M Davis wrote:
> > Yes. They expect it to work, and as the language is currently
> > designed, it works perfectly well. In fact, it's even built
> > into the language. e.g.
> >
> >     int[] foo() pure
> >     {
> >         return [1, 2, 3, 4];
> >     }
> >
> >     void main()
> >     {
> >         immutable arr = foo();
> >     }
> >
> > compiles thanks to the fact that the compiler can guarantee
> > from the signature of foo that its return value is unique.
>
> Oh is that run at runtime? I thought D was just smart and did it
> using CTFE.

CTFE only ever happens when it must happen. The compiler never does it as an
optimization. So, if you did

enum arr = foo();

or

static arr = foo();

then it would use CTFE, because an enum's value must be known at compile
time, and if a static variable is directly initialized instead of
initialized via a static constructor, its value must be known at compile
time. But if you're initializing a variable whose value does not need to be
known at compile time, then no CTFE occurs.

It would be a serious rabbit hole for the compiler to attempt CTFE when it
wasn't told to, particularly since it can't look at a function and know
whether it's going to work with CTFE or not. It has to actually call it with
a specific set of arguments to find out (and depending on what the function
does, it might even work with CTFE with some arguments and not with others -
e.g. if a particular branch of an if statement works with CTFE while another
does an operation that doesn't work with CTFE).

- Jonathan M Davis



More information about the Digitalmars-d mailing list