Compile-Time Function Execution (CTFE)
Ordinary D functions run at compile time when their result is required in a compile-time context (enum, static, template arguments, static assert, mixin).
CTFE restrictions: no I/O, no extern C calls, no inline asm, and no unsafe pointer casts. Allocation (new, ~) works.
if (__ctfe) branches between compile-time and runtime implementations.
import("file.txt") with -J path flags reads files at compile time (string imports).
ulong fib(ulong n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
enum fib30 = fib(30); // computed at compile time
static immutable primes = sieve(1000); // compile-time table stored in the binary
static assert(fib(10) == 55);
int[] sieve(int n)
{
auto isPrime = new bool[](n + 1);
isPrime[2 .. $] = true;
for (int i = 2; i * i <= n; i++)
if (isPrime[i]) for (int j = i * i; j <= n; j += i) isPrime[j] = false;
int[] result;
foreach (i, p; isPrime) if (p) result ~= cast(int) i;
return result;
}
string generateGetter(string name) { return "int " ~ name ~ "() { return _" ~ name ~ "; }"; }
struct S { int _x; mixin(generateGetter("x")); } // CTFE + mixin = code generation