Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Macros and Templates

Compile-Time Execution in Nim

Learn how Nim runs code during compilation with const, static blocks, when and compileTime, to precompute tables and select code per platform, with C stand-ins.

Many languages compute everything when the program runs. Nim can also run ordinary code while compiling, so that tables, hashes and configuration are already baked into the executable. The compiler contains a virtual machine that executes a large subset of Nim at compile time, and you use it with const, static, when and {.compileTime.}.

Nim snippets are read-only on this site; the C stand-ins show the result that the compiler arrives at.

const

A const must be computable at compile time. Its value is inserted directly into the program.

NIM
const
  Limit = 10
  Squares = block:
    var t: array[Limit, int]
    for i in 0 ..< Limit: t[i] = i * i
    t

echo Squares[7]       # 49

The block: runs a real loop during compilation, and at run time Squares is just a constant array in the binary. Procs used in a const expression run in the compile-time VM, so they can only use features it supports: no foreign function calls, and no pointer tricks.

The stand-in shows the same table precomputed, which is the kind of data Nim embeds for you:

C C stand-in: a precomputed lookup table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In C you must write or generate the values yourself. In Nim the compiler computes them from a loop.

static

static: runs a block at compile time and static[T] marks a parameter that must be a compile-time value.

NIM
static:
  echo "compiling..."        # printed by the compiler, not by your program

proc buffer(n: static int): array[n, byte] = discard
let b = buffer(16)           # the size is part of the type

static parameters let you encode sizes in types, so array[16, byte] and array[32, byte] are different types that the compiler can check.

when: compile-time if

when is like if, except the condition is evaluated during compilation and only the chosen branch is compiled. Use it for platform differences and feature switches.

NIM
when defined(windows):
  const Sep = '\\'
elif defined(linux) or defined(macosx):
  const Sep = '/'
else:
  {.error: "unsupported platform".}

when sizeof(int) == 8:
  echo "64-bit"

Branches that are not taken are not even type checked, which is why when can hide code that would not compile on another platform. Defines come from -d:name switches: nim c -d:release -d:myFeature app.nim. Check them with defined(myFeature).

C C stand-in: selecting code at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Reading files at compile time

staticRead and staticExec fetch data during compilation. A common use is embedding an asset:

NIM
const logo = staticRead("logo.txt")      # file contents become a string constant
const version = staticExec("git describe --always")

The file must exist at compile time and relative paths refer to the source file. This is a good way to ship one executable with no extra files.

compileTime procs and macros

Mark a proc {.compileTime.} when it should never exist at run time. Macros are procs of exactly this kind. Use static or const to trigger evaluation of ordinary procs:

NIM
proc fib(n: int): int =
  if n < 2: n else: fib(n - 1) + fib(n - 2)

const Fib20 = fib(20)    # computed by the compiler

Keep compile-time work small: a heavy computation slows down every build.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main property of a const?

    const values must be computable by the compiler and are embedded in the program.
  2. 2. What does when do differently from if?

    when selects code during compilation, and unused branches are not compiled.
  3. 3. How do you set a custom define?

    The -d switch defines a symbol you can test with defined().
  4. 4. What does staticRead return?

    It reads the file during compilation and embeds its content.

Summary

  • const and static run ordinary code in the compiler's VM.
  • when selects code at compile time; skipped branches are never compiled.
  • -d:name plus defined(name) toggles features.
  • staticRead/staticExec embed files and command output.
  • This is the foundation macros build on.

Next: Memory Management with ARC and ORC