Programming Search⌘K

Conceptcore

Syntactic macros

Also called macro, macros, preprocessor macro, hygienic macro.

A rule that the compiler applies to program text before it gives the text a meaning. The C preprocessor works on tokens; Lisp, Scheme and Rust macros work on syntax.

Applies to
core-languages

Idea

A syntactic macro is a rule that rewrites program text before the compiler gives the text a meaning. The programmer writes a call to the macro. The compiler, or a preprocessor in front of it, replaces the call with the expansion that the rule produces, and then compiles the expansion as if the programmer had written it.

A function receives values when the program runs. A macro receives program text when the program is compiled. This one difference explains what macros can do and what goes wrong with them. A macro can take an argument without evaluating it, evaluate it twice, turn it into a string, or build an identifier from it. It can expand to a declaration, a statement or a whole type. A function can do none of these things. But a macro also has none of the protections of a function: its arguments have no types, its body can be evaluated more than once, and its names can clash with the names around the call.

Two families exist. The C preprocessor works on tokens and knows nothing of the grammar of C. Lisp, Scheme and Rust macros work on syntax: they receive a parsed form, a pattern match or a token tree with structure, and they return a form of the same kind. The second family can respect the scopes of the language. That property is called hygiene.

How it works

Token macros: the C preprocessor

The C standard describes translation in phases. Phase 4 executes the preprocessing directives and expands the macro invocations. The compiler proper sees the result.2 A macro definition "lasts (independent of block structure) until a corresponding #undef directive is encountered", and "macro definitions have no significance after translation phase 4".2 So a macro has no scope, no namespace and no type.

A function-like macro substitutes the token sequences of the arguments for its parameters. Then the preprocessor rescans the result for more macro names to replace. If it finds the name of the macro that is being replaced, it does not replace it again.2 This rule stops infinite expansion. GCC shows the effect: with #define foo (4 + foo), each foo becomes (4 + foo) and stops there.6

Two operators work on the text of an argument. # turns an argument into a string literal, and ## joins two tokens into one.2 The C89 Committee introduced # for stringizing and "invented" ## for token pasting, to replace older practices that the standard did not want to allow.7 C99 added macros with a variable number of arguments, written with ... and __VA_ARGS__, because C89 had no way to write a macro that looks like a call to printf.7 The C example text uses both operators: SHOW prints the text of an expression next to its value, and GETTER builds the functions get_x and get_y.

The Rationale states one of the design principles of macro replacement: "Allow macros to be used wherever functions can be."7 Macros look like function calls. Most of the pitfalls below come from the fact that they do not behave like them.

Syntax macros: Lisp

A Lisp program is a list. So a Lisp macro is a function from a list to a list that the compiler calls. In Common Lisp, defmacro defines a name "as a macro by associating a macro function with that name in the global environment". The expansion function receives a form and an environment and returns a form, which replaces the call.8 The body of the expansion function is a sequence of ordinary forms, and the value of the last one is the expansion.8

Backquote makes the result readable. A backquoted form is a template. A comma marks an expression that is evaluated and inserted, and ,@ marks a list that is spliced into place.9

A macro of this kind is not hygienic. If the template binds a variable called tmp, it hides a tmp that the caller passes in. The Common Lisp answer is gensym, which "creates and returns a fresh, uninterned symbol".10 A macro that binds its temporaries to names from gensym cannot capture the names of the caller.

Hygiene: Scheme

Kohlbecker, Friedman, Felleisen and Duba published "Hygienic macro expansion" at the 1986 ACM Conference on LISP and Functional Programming.11 The Scheme report says that Scheme "became the first programming language to support hygienic macros". R7RS defines two mechanisms that prevent unintended conflicts:12

  • If a macro inserts a binding for an identifier, the identifier is in effect renamed throughout its scope.
  • If a macro inserts a free reference to an identifier, the reference refers to the binding that was visible where the macro was defined, whatever local bindings surround the use.

The report concludes that macros defined with its pattern language "are 'hygienic' and 'referentially transparent' and thus preserve Scheme's lexical scoping". It cites Kohlbecker's thesis, the 1986 paper, and Clinger and Rees, "Macros that work" (1991), for these properties.12 The first rule stops a macro from capturing the names of the caller. The second rule stops the caller from capturing the names of the macro. The C example below breaks the second rule.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

static int verbose = 1;

#define LOG(msg) do { if (verbose) printf("log: %s\n", msg); } while (0)

int main(void) {
    int verbose = 0;
    LOG("start");
    printf("verbose = %d\n", verbose);
}
Output
verbose = 0

The author of LOG meant the global verbose. The expansion of LOG appears inside main, so the name verbose refers to the local variable, and the log line never prints. A hygienic system would look up verbose where LOG was defined.

Rust: macros by example and procedural macros

Rust has two kinds of macros. A macro_rules! macro is a list of rules. Each rule has a matcher and a transcriber, and the first rule whose matcher matches the call is used.13 A matcher binds metavariables to fragments of a given kind: expr, ident, ty, block, pat and others.13 A metavariable is replaced by the syntax element that it matched, and it "can be transcribed more than once or not at all".13 Because an expr fragment stays one syntax element, square!(1 + 2) with the body $x * $x computes 9. The precedence trap of C does not exist. But double evaluation still exists, as the Rust example double-evaluation shows.

Macros by example have mixed-site hygiene: "loop labels, block labels, and local variables are looked up at the macro definition site while other symbols are looked up at the macro invocation site".13 So the Rust swap! macro can declare tmp without hiding the caller's tmp, and a macro cannot read a local variable of its caller unless the caller passes the variable in. Functions, types and other macros are looked up at the call. A macro that names an item of its own crate writes $crate:: so that the path works in other crates.13

A procedural macro is a Rust function that runs at compile time. It consumes and produces Rust syntax, as a stream of tokens. It comes in three kinds: function-like (custom!(...)), derive (#[derive(CustomDerive)]) and attribute (#[CustomAttribute]).14 A procedural macro must be defined in a crate of type proc-macro, and that crate cannot use it.14 Procedural macros are unhygienic: they behave as if the output token stream was written inline at the call.14 They run with the same access to files and input as the compiler, so they have the same security concerns as build scripts.14 The #[derive(Debug, PartialEq)] of the Rust example derive calls derive macros of the standard library.

When a function or a generic is better

The Rust book gives the tradeoff. A macro can take a variable number of arguments, and it runs before the compiler interprets the code, so it can, for example, implement a trait. But macro definitions "are generally more difficult to read, understand, and maintain than function definitions", and a macro must be defined or imported before its use in a file.15 The C++ Core Guidelines are stricter. Rule ES.31 says "Don't use macros for constants or 'functions'", because macros "don't obey the usual scope and type rules" and "don't obey the usual rules for argument passing". It replaces #define PI 3.14 with a constexpr variable and a SQUARE macro with a function template.16

Use a function when the job is a computation on values. A function evaluates each argument once, checks its types and has its own scope. Use a generic function, such as a C++ template or a Rust generic, when the computation must work for many types. See Generics. Use a higher-order function or a closure when the job is to delay or repeat a piece of code. A closure captures its variables by the rules of the language, so it has no capture problems. See Closure. Use Constant evaluation when the job is to compute a value at compile time.

A macro is the right tool when the job needs the program text itself:

  • the text of an argument, as in assert or a test macro that prints the failed expression;
  • an identifier or a declaration made from parts, as in GETTER;
  • the location of the call, unless the language has a library feature for it. In C++, a call to std::source_location::current() in a default argument corresponds to the location of the caller;17
  • syntax that a function cannot accept, such as a variable number of arguments of different kinds, or a block of code that must not run before the macro decides;
  • code that the type system cannot express, such as an impl of a trait for many types, or the derive macros of Rust.

In languages

LanguageVerdictNote
PythonAbsent
C++Native
JavaAbsentThe language has no preprocessor and no macros. Alternative: An annotation processor that generates source files during compilation.
CNative
C#AbsentThe preprocessor directives only control conditional compilation; they cannot create macros. Alternative: Source generators, which add source files during compilation.
JavaScriptAbsentThe language has no macros. Alternative: A build tool that transforms the source before it runs.
TypeScriptAbsentThe language has no macros. Alternative: A build tool that transforms the source before it runs.
GoAbsentThe language has no macros. Alternative: Go generate runs commands, written in special comments, that write Go source before the build.
RustNative
KotlinAbsentThe language has no macros; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: A compiler plugin or a symbol processor that generates code.
SQLAbsentStandard SQL has no macros. Alternative: A view or a stored routine.
BashAbsentThe shell has no macros. Alternative: A shell function.
PowerShellAbsentThe language has no macros; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no macros.
CSSDoes not applyStyle rules have no macros.
Regular expressionsDoes not applyA pattern has no definitions that expand.
Language Verdict Form
C native the preprocessor: object-like and function-like macros, #, ##, __VA_ARGS__
C++ native the preprocessor of C; templates and constexpr replace most uses
Rust native macro_rules! with mixed-site hygiene; procedural macros in a separate crate
Python absent no macros; the ast module can rewrite source text at run time
Java absent no macros; annotation processors generate source files
C# absent directives for conditional compilation only; source generators add files
Go absent no macros; go generate runs tools before the build
JavaScript absent no macros; build tools transform the source
TypeScript absent as JavaScript
Kotlin absent no macros; compiler plugins and symbol processors generate code
PowerShell absent no macros
Bash absent no macros; shell functions
SQL absent no macros in the standard
Regex n/a a pattern has no definitions that expand
HTML/CSS n/a no definitions that expand

C and C++ share the preprocessor. C++ adds scope to almost everything else, but a macro still ignores namespaces. The C++ example no-scope defines a macro max and then calls std::numeric_limits<int>::max(). The preprocessor sees max followed by ( and expands it, and the compilation fails.

Rust is the only tier 1 language with syntactic macros that respect scope. Common parts of the standard library, such as println! and vec!, are macros. println! takes one argument or more, which a Rust function cannot do.15

C# has preprocessor directives, but "unlike C and C++ directives, you can't use these directives to create macros". A symbol can be defined, but it has no value.18 Source generators fill part of the gap. They let a program add source files to a compilation at compile time.19 Kotlin has the Kotlin Symbol Processing API, a framework that generates source code, most often from annotations. It cannot see expressions or the bodies of functions.20 Java has annotation processors in the same role. See Annotations.

Go has no macros. The go generate command scans source files for special comments and runs the commands in them. It is not part of go build and must be run explicitly before it. The generated file must be checked into the source repository to be available to clients.21

Python has no macros, but the ast module exposes the parser. ast.NodeTransformer rewrites a tree, ast.fix_missing_locations repairs the positions, and compile turns the tree into code.22 The Python example ast-transform does at run time what a macro does at compile time. Decorators look like macros but are not. A decorator expression is evaluated when the function is defined, and its result is called with the function object, not with the syntax of the function.23

PythonGitHub
import ast

source = "total = price * quantity"
tree = ast.parse(source)


class CheckedMultiply(ast.NodeTransformer):
    def visit_BinOp(self, node):
        self.generic_visit(node)
        if isinstance(node.op, ast.Mult):
            return ast.Call(
                func=ast.Name("checked_mul", ast.Load()),
                args=[node.left, node.right],
                keywords=[],
            )
        return node


tree = ast.fix_missing_locations(CheckedMultiply().visit(tree))
print(ast.unparse(tree))


def checked_mul(a, b):
    result = a * b
    if result > 1000:
        raise OverflowError(f"{a} * {b} is more than 1000")
    return result


namespace = {"checked_mul": checked_mul, "price": 30, "quantity": 4}
exec(compile(tree, "<generated>", "exec"), namespace)
print(namespace["total"])
Output
total = checked_mul(price, quantity)
120
  • Verdict: absent. Python has no macros. The compiler does not let a program change the syntax tree of the program that it is compiling.
  • The ast module parses source text into a tree, ast.NodeTransformer rewrites it, and compile turns the result into code. This is the work of a syntactic macro, done at run time on code that the program holds as text.
  • Decorators change a function after it is defined. They work on the function object, not on its syntax.

This code does not compile, on purpose.

#include <iostream>
#include <limits>

#define max(a, b) ((a) > (b) ? (a) : (b))

int main() {
    std::cout << std::numeric_limits<int>::max() << '\n';
}

A macro has no scope and no namespace. The name max in std::numeric_limits<int>::max() is followed by (, so the preprocessor treats it as a call of the macro with too few arguments, and the compiler stops.

#include <algorithm>
#include <iostream>
#include <source_location>

template <typename T>
constexpr T square(T x) {
    return x * x;
}

static_assert(square(1 + 2) == 9);

void log(const char *msg, std::source_location where = std::source_location::current()) {
    std::cout << "line " << where.line() << ": " << msg << '\n';
}

int main() {
    int i = 5;
    int m = std::max(i++, 0);
    std::cout << "m = " << m << ", i = " << i << '\n';
    std::cout << "square(2.5) = " << square(2.5) << '\n';
    log("called without a macro");
}
Output
m = 5, i = 6
square(2.5) = 6.25
line 21: called without a macro
#include <iostream>

void check(bool ok, const char *text, int line) {
    std::cout << (ok ? "ok:   " : "FAIL: ") << text << " (line " << line << ")\n";
}

#define CHECK(expr) check((expr), #expr, __LINE__)

int main() {
    int a = 2;
    int b = 3;
    CHECK(a + b == 5);
    CHECK(a * b == 5);
}
Output
ok:   a + b == 5 (line 12)
FAIL: a * b == 5 (line 13)
  • Verdict: native. C++ has the preprocessor of C, with the same # and ## operators and the same lack of scope.
  • A function template replaces a function-like macro: it has a type, evaluates each argument once, and obeys namespaces. A constexpr function also runs at compile time, as the static_assert shows.
  • std::source_location::current() as a default argument gives the line of the caller, which once needed __LINE__ in a macro.
  • The text of an expression (#expr) is the main thing that still needs a macro, as in CHECK and the standard assert.
#include <stdio.h>

#define SHOW(expr) printf("%s = %d\n", #expr, (expr))

struct point {
    int x;
    int y;
};

#define GETTER(field) \
    int get_##field(const struct point *p) { return p->field; }

GETTER(x)
GETTER(y)

int main(void) {
    struct point p = {3, 4};
    SHOW(get_x(&p) + get_y(&p));
    SHOW(p.x * p.y);
}
Output
get_x(&p) + get_y(&p) = 7
p.x * p.y = 12

The # operator turns the argument into a string literal, and ## joins two tokens into one identifier. A function cannot do either of these things, because it receives values, not program text.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

#define SQUARE(x) x * x

int main(void) {
    printf("SQUARE(1 + 2) = %d\n", SQUARE(1 + 2));
}
Output
SQUARE(1 + 2) = 5

The expansion is 1 + 2 * 1 + 2, which is 5, not 9. The fix is a pair of parentheses around each use of a parameter and around the whole body: #define SQUARE(x) ((x) * (x)).

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main(void) {
    int i = 5;
    int m = MAX(i++, 0);
    printf("m = %d, i = %d\n", m, i);
}
Output
m = 6, i = 7

The argument i++ appears twice in the expansion, so it runs twice when it is the larger value. A caller expects m = 5 and i = 6. Parentheses cannot fix this.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

#define SWAP(a, b) do { int tmp = (a); (a) = (b); (b) = tmp; } while (0)

int main(void) {
    int x = 1;
    int tmp = 2;
    SWAP(x, tmp);
    printf("x = %d, tmp = %d\n", x, tmp);
}
Output
x = 1, tmp = 2

The macro declares its own tmp, and that declaration hides the caller's tmp inside the expansion. The swap does nothing. A hygienic macro system renames the macro's tmp, so this cannot happen.

#include <stdio.h>

static inline int max_int(int a, int b) {
    return a > b ? a : b;
}

static inline void swap_int(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void) {
    int i = 5;
    int m = max_int(i++, 0);
    printf("m = %d, i = %d\n", m, i);

    int x = 1;
    int tmp = 2;
    swap_int(&x, &tmp);
    printf("x = %d, tmp = %d\n", x, tmp);
}
Output
m = 5, i = 6
x = 2, tmp = 1
  • Verdict: native. The preprocessor replaces each macro invocation with its replacement list before the compiler parses the program.
  • A macro sees tokens, not expressions, so the body needs parentheses. It has no scope, so its names can clash with the names of the caller.
  • A static inline function evaluates each argument once, has a type, and has its own scope. Use it unless the macro needs the text of its argument (#), an identifier made from parts (##) or the location of the call (__FILE__, __LINE__).
RustGitHub
macro_rules! square {
    ($x:expr) => {
        $x * $x
    };
}

macro_rules! maximum {
    ($x:expr) => { $x };
    ($x:expr, $($rest:expr),+) => {{
        let a = $x;
        let b = maximum!($($rest),+);
        if a > b { a } else { b }
    }};
}

fn main() {
    println!("square!(1 + 2) = {}", square!(1 + 2));
    println!("maximum!(3, 9, 4, 7) = {}", maximum!(3, 9, 4, 7));
}
Output
square!(1 + 2) = 9
maximum!(3, 9, 4, 7) = 9

$x:expr matches a whole expression, and the transcriber puts back that expression as one syntax element. So square!(1 + 2) is (1 + 2) * (1 + 2), with no extra parentheses in the macro. A macro can also take any number of arguments and call itself, as maximum! does.

This code runs but gives a wrong answer on purpose.

macro_rules! square {
    ($x:expr) => {
        $x * $x
    };
}

fn next(counter: &mut i32) -> i32 {
    *counter += 1;
    *counter
}

fn main() {
    let mut counter = 1;
    let s = square!(next(&mut counter));
    println!("s = {s}, counter = {counter}");
}
Output
s = 6, counter = 3

Hygiene and syntax fragments fix the precedence trap, but not double evaluation. The expansion calls next twice, so the result is 2 × 3 = 6, not 4. The fix binds the argument once: { let v = $x; v * v }.

macro_rules! swap {
    ($a:ident, $b:ident) => {
        let tmp = $a;
        $a = $b;
        $b = tmp;
    };
}

fn main() {
    let mut x = 1;
    let mut tmp = 2;
    swap!(x, tmp);
    println!("x = {x}, tmp = {tmp}");
}
Output
x = 2, tmp = 1

The tmp that the macro declares and the tmp of the caller are different variables, although they have the same name. This is the C SWAP of the C example, and here it works.

This code does not compile, on purpose.

macro_rules! show_x {
    () => {
        println!("{}", x);
    };
}

fn main() {
    let x = 5;
    show_x!();
}

Local variables in a macro body are looked up where the macro is defined. No x exists there, so the compiler reports error E0425, "cannot find value x in this scope". To use the caller's x, pass it as an argument.

#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    let q = p.clone();
    println!("{:?}", q);
    println!("{}", p == q);
}
Output
Point { x: 1, y: 2 }
true
  • Verdict: native. macro_rules! defines macros by example: each rule has a matcher and a transcriber, and the matcher binds typed syntax fragments such as expr, ident and ty.
  • Macros by example have mixed-site hygiene. Local variables and labels are looked up at the definition, other names at the call.
  • Procedural macros are Rust functions from a token stream to a token stream. They come in three kinds: function-like, derive (as #[derive(Debug)]) and attribute. They must live in a separate crate of type proc-macro, so this page cannot run one in a single file. They are not hygienic.
  • Use a function or a generic function when it can do the job. A macro is right for a variable number of arguments, for items such as an impl block, or for syntax that a function cannot take.
  • Object-like macros. #define PI 3.14 gives a name to a sequence of tokens. ES.31 replaces it with constexpr double pi = 3.14;, which has a type and a scope.16
  • Conditional compilation. #if, #ifdef and #endif select text before compilation. ES.30 does not ban macros for this use.16 C#, which has no macros, keeps these directives.18
  • Templates and generics. A C++ template also generates code at compile time, but from typed declarations and with the scoping rules of the language. See Generics.
  • Compile-time evaluation. constexpr functions in C++ and const fn in Rust compute values at compile time with the rules of ordinary functions. See Constant evaluation.
  • Code generators. Annotation processors, C# source generators, Kotlin symbol processors and go generate write source files. They see declarations, not the expressions inside functions, and they cannot change the code that the programmer wrote.192021 See Annotations.
  • Run-time code transformation. Python can parse, change and compile source text while the program runs.22 This gives the power of a macro without its compile-time checks.

Pitfalls

Missing parentheses

A C macro sees tokens, not expressions. With #define SQUARE(x) x * x, the call SQUARE(1 + 2) becomes 1 + 2 * 1 + 2, which is 5. The C example parentheses shows it. The rule is to put parentheses around each use of a parameter and around the whole body. GCC shows the same trap with a ceil_div macro and gives the fixed form (((x) + (y) - 1) / (y)).3

Double evaluation

A parameter that appears twice in the body is evaluated twice. GCC calls a min macro with this property "an unsafe macro": in min (x + y, foo (z)), foo may be called twice.5 Parentheses do not help. The C example double-evaluation shows MAX(i++, 0) incrementing i twice, and the Rust example double-evaluation shows the same error in a macro_rules! macro. GCC offers a fix with a GNU extension, a statement expression that copies each argument into a local variable. In standard C, it says, the only solution is to be careful.5 In Rust, the fix is the same idea in standard syntax: { let v = $x; v * v }. A function has this property without effort.

Name capture

A C macro that declares a variable can hide a variable of the caller with the same name. The C example capture shows a SWAP macro that does nothing when the caller's variable is called tmp. The GNU fix for min gives its locals names with trailing underscores "to reduce the risk of conflict", and GCC adds that "it is impossible to avoid this entirely".5 The reverse error is in the free-name example above: the caller's variable captures a name that the macro meant to take from its own scope. Hygiene solves both problems in Scheme and, for local variables, in macro_rules!.1213 Rust procedural macros are not hygienic, so they use absolute paths such as ::std::option::Option.14

Swallowing the semicolon

A macro that expands to a block { ... } breaks an if with an else. The semicolon after the call is an empty statement, so the else has no if.4

This code does not compile, on purpose.

#include <stdio.h>

#define SKIP_SPACES(p) { while (*(p) == ' ') ++(p); }

int main(void) {
    const char *s = "  word";
    if (*s != '\0')
        SKIP_SPACES(s);
    else
        s = "empty";
    printf("%s\n", s);
}

The fix wraps the body in do { ... } while (0). The expansion is then one statement that needs the semicolon, and the loop runs once.4 The SWAP and LOG macros on this page use this form.

Macros that clash with other names

A macro name is replaced everywhere after its definition, in every scope and in every namespace.2 The C++ example no-scope shows a macro max that breaks a call to std::numeric_limits<int>::max(). The C++ Core Guidelines give macros names in ALL_CAPS to distinguish them from other names (rule ES.32).16

A macro that hides a bug

ES.30 shows #define Case break; case. One lower-case c in place of C turns it into a control-flow bug, because the reader sees something different from what the compiler sees.16

Cost

  • At run time. None in principle. The expansion is ordinary code, and it costs what the same code costs when written by hand. A macro that evaluates an argument twice does the work twice.
  • At compile time. Every call is expanded and then compiled. A procedural macro is a program that the compiler builds and runs before it can compile the crate that uses it.14
  • For people and tools. The reader sees the call, and the compiler sees the expansion. Error messages can point into the expansion. ES.30 says that macros "complicate tool building", and it names auto completers, static analyzers and debuggers.16 The Rust book says that macro definitions are harder to read and maintain than function definitions.15

History

  • 1963. Timothy P. Hart proposed "a MACRO instruction expander in define" for LISP 1.5, to replace the special forms that take an indefinite number of arguments or keep their arguments from being evaluated.1
  • 1986. Kohlbecker, Friedman, Felleisen and Duba published "Hygienic macro expansion".11
  • 1989. The C89 Committee introduced the # operator and invented the ## operator, to replace older stringizing and token-pasting practices.7
  • 1991. Clinger and Rees published "Macros that work".12
  • 1999. C99 added macros with a variable number of arguments through ... and __VA_ARGS__.7
  • 2014. Go 1.4 included go generate, a command that runs code generators before the build.21

References

  1. Timothy P. Hart, MACRO Definitions for LISP, MIT AI Memo AIM-057, October 1963, abstract
  2. N3220, working draft of ISO/IEC 9899:2024 (C23), 5.1.1.2 Translation phases, phase 4; 6.10.5 Macro replacement; 6.10.5.4 Rescanning and further replacement, paragraphs 1 and 2; 6.10.5.5 Scope of macro definitions, paragraph 1
  3. The C Preprocessor (GCC), 3.10.2 Operator Precedence Problems, the ceil_div example and the parenthesized definition
  4. The C Preprocessor (GCC), 3.10.3 Swallowing the Semicolon, the SKIP_SPACES example and the do ... while (0) definition
  5. The C Preprocessor (GCC), 3.10.4 Duplication of Side Effects, the min example, "an unsafe macro", and the GNU statement expression
  6. The C Preprocessor (GCC), 3.10.5 Self-Referential Macros, the foo example and the EPERM example
  7. Rationale for International Standard, Programming Languages, C, Revision 5.10, April 2003, 6.10.3 Macro replacement, pages 99 and 101; 6.10.3.2 The
  8. Common Lisp HyperSpec, Macro DEFMACRO, Description
  9. Common Lisp HyperSpec, 2.4.6 Backquote, the first two paragraphs and the comma at-sign paragraph
  10. Common Lisp HyperSpec, Function GENSYM, Description
  11. Hygienic macro expansion, bibliographic record (title, venue, year, pages)
  12. Revised7 Report on the Algorithmic Language Scheme, 4.3 Macros, page 22; Introduction (the paragraph on the history of Scheme); References [9], [21] and [22]
  13. The Rust Reference, Macros by example, [macro.decl.intro]; [macro.decl.meta.specifier]; [macro.decl.meta.transcription]; [macro.decl.hygiene.intro]; [macro.decl.hygiene.crate]
  14. The Rust Reference, Procedural macros, [macro.proc.intro]; [macro.proc.def]; [macro.proc.result]; [macro.proc.proc_macro-crate.token-stream]; [macro.proc.hygiene]
  15. The Rust Programming Language, 20.5 Macros, The Difference Between Macros and Functions
  16. C++ Core Guidelines, ES.30: Don't use macros for program text manipulation; ES.31: Don't use macros for constants or "functions"; ES.32: Use ALL_CAPS for all macro names
  17. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 17.8.2.2 [support.srcloc.cons], paragraph 2 and example 1
  18. C# preprocessor directives, the introduction and Conditional compilation
  19. Source Generators overview, the first paragraphs
  20. Kotlin Symbol Processing API, the introduction and Limitations
  21. Rob Pike, Generating code, The Go Blog, 22 December 2014, the paragraphs on the go generate command and on checking in the generated file
  22. The Python Language Reference, 8.7 Function definitions, the paragraph on decorator expressions
  23. Python documentation, ast, Abstract Syntax Trees, ast.NodeTransformer; ast.unparse; ast.fix_missing_locations

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/HS19Y9/text.yaml