Battle-plan for CTFE

H. S. Teoh via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Thu Sep 1 14:54:16 PDT 2016


On Thu, Sep 01, 2016 at 08:43:16PM +0000, David Nadlinger via Digitalmars-d-announce wrote:
> On Thursday, 1 September 2016 at 19:38:13 UTC, Stefan Koch wrote:
> > I have something that will help with that a little bit.
> > https://github.com/UplinkCoder/dmd/tree/__ctfeWriteln when you apply
> > this patch __ctfeWriteln() will output every compiletime avilable
> > string to the console.
> 
> More crucially, it also allows you to print runtime values during
> CTFE.  pragma(msg, …) suffices to print compile-time constants. Very
> few people seem to have the correct mental model for the the
> interaction between compile-time features and CTFE, hence I think
> using precise terminology is an important first step.
[...]

Part of the problem is that the term "compile-time" is ambiguous. In the
compilation of a D program, there are (at least) 2 distinct phases that
may be termed "compile-time": (1) expansion of templates and evaluation
of static-if, and (2) CTFE.

Phase (1) conceptually happens before the AST is finalized, and hence at
this stage it makes no sense to refer to variables and such: variables
don't even exist yet because the syntax tree of the program is still
being manipulated.

Phase (2) happens just as the compiler is ready to emit object code: the
AST has been finalized, symbols have been resolved, statements have been
analysed / lowered, etc.. At this stage, static-if no longer makes any
sense because the AST can no longer be manipulated at this point.

Of course, the above is a simplified picture of what actually happens.
In a complex D program, you *can* have phase (2) precede phase (1),
e.g., using static-if on the result of a CTFE function. The important
thing to note here, though, is that the CTFE function's body must
already be in phase (2), because otherwise CTFE is impossible. So
another part of the code can depend on the result of the CTFE function,
but the function itself is already past phase (1) and you can't change
its AST anymore.  So you can have different parts of the program be in
different phases, and they can have interdependencies, but the same
piece of code can only progress from phase (1) to phase (2), and never
the other way around.

Referring to both phases as "compile-time" is ambiguous and causes
confusion to people who are not familiar with how the compilation
process actually works.


T

-- 
Windows: the ultimate triumph of marketing over technology. -- Adrian von Bidder


More information about the Digitalmars-d-announce mailing list