Compile Time Function Evaluation (CTFE)

jessekphillips

Jesse Phillips

Posted on November 19, 2019

Compile Time Function Evaluation (CTFE)

Meta programing has been a common feature in languages. Some languages provide reflection, AST manipulation, Javascript provides eval to execute a runtime string as code.

But executing normal runtime functions at compilation is generally reserved only for D and Jai.

enum Val = makeInt("65");

int makeInt(string num) {
    import std.conv;
    return to!int(num);
} 

static assert(Val == 65);
Enter fullscreen mode Exit fullscreen mode

In order to better understand what is happening I should mention that enum is used as manifest const in this context. Well that probably wasn't helpful. Basically the value needs to be known at Compile Time to be copied wherever Val is used. The use of static assert is another compile time operation, the validation is done during compilation.

D has limitations on what can be done at compile time. This is namely device access. This I believe to be a benefit over Jai's complete system access, the build system cannot become a dependency on the binary (Unless of course your build tool does code generation before calling the compiler, so I'm probably just fooling myself).

💖 💪 🙅 🚩
jessekphillips
Jesse Phillips

Posted on November 19, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Compile-Time Reflection
dlang Compile-Time Reflection

December 9, 2019

String Mixin
dlang String Mixin

November 25, 2019