liveBook · Manning

Macro expansion

As explained in Idiomatic Rust

A macro expansion is the compiler-generated source or language construct produced from a macro invocation.

Macro expansion is the source or language construct produced when Rust evaluates a macro invocation. A macro can match recursive token trees, repeat arguments, and pass them into another macro. section 5.1.2

In a variadic `special_println!`, `$($arg:tt)*` captures any number of token-tree arguments, while `$($arg)*` transcribes them into `println!` or `format!`. Expansions can therefore nest and call other macros. section 5.1.2

Tracing nested expansion

Enabling `trace_macros!` around `special_println!("hello world!")` reveals successive expansions through `special_println!`, `println!`, `format!`, and the compiler-built-in `format_args!`. section 5.1.2

note: trace_macro
  --> src/main.rs:84:5
   |
84 |     special_println!("hello world!");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: expanding `special_println! { "hello world!" }`
   = note: to `println! ("Printed specially: {}", format! ("hello world!"))`
   = note: expanding `println! { "Printed specially: {}", format!
 ("hello world!") }`
   = note: to `{
               $crate :: io ::
               _print($crate :: format_args_nl!
               ("Printed specially: {}", format! ("hello world!"))) ;
           }`
   = note: expanding `format! { "hello world!" }`
   = note: to `{
          let res = $crate :: fmt ::
          format($crate :: __export :: format_args! ("hello world!")) ; res
        }`

Inspect the compiler-style expansion trace to follow how one macro invocation becomes nested generated constructs. section 5.1.2

How Idiomatic Rust covers it

How deep it goes
Demonstrates matching, repetition, nesting, and compiler tracing, then stops at the built-in implementation of format_args!.
Examples
Uses special_println!, var_print!, formatted output, and trace_macros! expansion output.
What it assumes
Assumes familiarity with Rust macro syntax and introduces token-tree repetition through focused printing examples.
What you can do after
Evaluate macro behavior by reading repeated token patterns and tracing nested expansions into generated Rust constructs.
How it connects
Connects token trees, macro_rules!, println!, format!, format_args!, recursion, and compiler tracing.

Also explained in

Compare how 4 books explain macro expansion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.