Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Macros and Templates

Macros and the AST in Nim

Learn what Nim macros are, how code becomes an abstract syntax tree, how to build new code with quote do, and how a tree evaluator works, with runnable C stand-ins.

A macro is a Nim procedure that runs at compile time. It receives your code as a tree of nodes (an abstract syntax tree, or AST), and returns a new tree that replaces the call. Macros are how Nim libraries add features that other languages need compiler changes for: a web route DSL, a JSON-to-type generator, a test framework with pretty assertions.

Nim code here is read-only on this site. The C stand-ins build and walk small trees to show the idea.

Code is a tree

The expression 1 + 2 * 3 is not a flat string to the compiler. It is a tree:

flowchart TD
  P["+"] --> A["1"]
  P --> M["*"]
  M --> B["2"]
  M --> C["3"]

The tree for 1 + 2 * 3: multiplication binds tighter, so it sits lower.

In Nim, nodes are of type NimNode, with a kind (nnkInfix, nnkIntLit, nnkIdent...). You can print the tree your code produces with dumpTree:

NIM
import std/macros

dumpTree:
  1 + 2 * 3

The output lists the nodes (an Infix node with the operator and two children, one of which is another Infix). Run it with your own Nim install to see the exact kind names for your version.

Your first macro

Macros take untyped or typed arguments, and return NimNode. The easiest way to build output is quote do:, which writes real code and lets you splice values in with backticks.

NIM
import std/macros

macro unrollTimes(n: static int, body: untyped): untyped =
  result = newStmtList()
  for i in 1 .. n:
    result.add body          # paste the block n times

unrollTimes(3):
  echo "hi"

Here n is a static int: a value that must be known at compile time. The macro loops during compilation, and the program that is compiled contains three echo calls with no loop.

A macro that inspects code is more interesting. This one prints an expression together with its value:

NIM
macro show(e: untyped): untyped =
  let text = e.repr
  result = quote do:
    echo `text`, " = ", `e`

let x = 4
show x * 10           # prints: x * 10 = 40

e.repr turns the tree back into source text, and the backticks insert the text and the original expression into the generated echo call.

Evaluating a tree

What a macro does is traverse and rebuild trees. The stand-in below builds the tree for 1 + 2 * 3 and evaluates it recursively, which is the same walk a macro does when it analyzes an expression.

C C stand-in: build and walk an expression tree

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.

Generating code from data

The same walk can produce code instead of a number. This stand-in turns a tree into C-like source text, which is what a macro's output is conceptually: a new tree that the compiler then compiles.

C C stand-in: emit source from a tree

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.

Guidelines

  • Prefer a template or a proc when they are enough. Macros are harder to read and debug.
  • Use quote do for simple output; build nodes by hand (newCall, newIdentNode, newStmtList) for dynamic shapes.
  • Print the result with echo result.repr or expandMacros while developing.
  • Macros can run compile-time code that reads files and builds tables.
  • Keep macros pure: the same input tree should give the same output tree.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a macro run?

    Macros are compile-time procedures that rewrite the AST.
  2. 2. What does quote do: provide?

    It turns the indented code into a tree, with backticks for splicing values.
  3. 3. What type does a macro return?

    A macro produces a syntax tree that replaces the call.
  4. 4. Which tool prints the tree of some code?

    dumpTree from std/macros shows the node kinds.

Summary

  • Macros receive and return syntax trees (NimNode) at compile time.
  • quote do: is the easy way to build output; backticks splice in values.
  • static parameters are values known at compile time.
  • Walking a tree recursively is the core technique, shown here in C.
  • Use macros only when procs and templates cannot do the job.

Next: Compile-Time Execution