Macros

A macro is a special function that is executed at compile time. Normally the input for a macro is an abstract syntax tree (AST) of the code that is passed to it. The macro can then do transformations on it and return the transformed AST. This can be used to add custom language features and implement domain specific languages.

Macro invocation is a case where semantic analysis does not entirely proceed top to bottom and left to right. Instead, semantic analysis happens at least twice:

  • Semantic analysis recognizes and resolves the macro invocation.
  • The compiler executes the macro body (which may invoke other procs).
  • It replaces the AST of the macro invocation with the AST returned by the macro.
  • It repeats semantic analysis of that region of the code.
  • If the AST returned by the macro contains other macro invocations, this process iterates.

While macros enable advanced compile-time code transformations, they cannot change Nim’s syntax.