How does CTFE work?

How does the compile time estimation function (CTFE) work? I am trying to understand how the compiler, while it works, creates something that does not exist (for example, a function) and executes it. I got used to the idea that the source code becomes a binary through compilation, and then the binary is executed. So, how does the source code become something executable while the compiler is running and is able to run it? Is a function really created and run, or is it just an emulation of a function call?

+8
compiler-construction d
source share
2 answers

CTFE uses an interpreter that is embedded in the compiler - just as you would expect from an interpreted language such as Python. When you compile something like this:

bool not(bool arg) { return !arg; } void main() { enum compileTime = not(true); // not() called at compile time bool runTime = not(true); // not() called at runtime } 

The compiler goes through the usual stages of tokenization / lexing / parsing, etc. When the computeTime enum (or any other construct that requires a compilation time value) is encountered, it will try to evaluate what is on the right side of the expression. In the case of a constant, it does what you expect and saves the constant. If he encounters a function call, he will start the CTFE interpreter. In this example, he knows what arguments are, and what the operators in this function do, he goes step by step and interprets each of them. If it cannot interpret the statement at compile time, it will throw a compile time error. In this simple example, it simply negates the parameter, but CTFE is able to interpret the structures, classes, loops, and much more described here - http://dlang.org/function#interpretation .

+11
source share

this is essentially an extended form of constant folding , where the compiler tries to calculate the values ​​used so that it is not executed at run time (operations that cannot happen at compile time (IO, memory allocation, ...) will fail)

The CTFE feature is that it can be made explicit (for example, by assigning enum ) and try to evaluate custom functions

in practice, this can be done using the interpreter assembly in the compiler

+1
source share

All Articles