liveBook · Manning

Macro repetition

As explained in Write Powerful Rust Macros

A macro repetition operator specifies whether a repeated macro pattern occurs zero or more, one or more, or zero or one times.

Macro repetition controls how often a matched pattern occurs: zero or more times with *, one or more with +, or zero or one time with ?. A matcher captures repeated expressions, while the transcriber emits code for each capture. section 2.1.4

Build a vector from repeated expressions

A matcher such as $[($x:expr),+] accepts one or more expressions. The transcriber repeats v.push($x); for every captured expression, producing a Vec while preserving ordinary Rust compilation and type checking. section 2.1.4

$[($x:expr),+] => (
        {
        let mut v = Vec::new();
        $(
            v.push($x);
        )+
        v
    }
)

Inspect the complete repeated-expression macro, including its + matcher and repeated push operation. section 2.1.4

Captures must be repeated at the matching depth: removing the transcriber’s repetition leaves $x repeating where one expression is expected. Generated code still obeys Rust’s type rules, so mixed integer and string inputs fail to compile. section 2.1.4

How Write Powerful Rust Macros covers it

How deep it goes
Defines *, +, and ?, demonstrates matcher-transcriber depth, and notes an unresolved operator-mismatch bug.
Examples
Uses a repeated-expression macro that pushes each capture into a vector and rejects mixed input types.
What it assumes
Assumes Rust expressions and basic declarative-macro matcher and transcriber syntax.
What you can do after
Apply it via Rust declarative macros to accept repeated expressions and generate repeated operations.
How it connects
Connects macro repetition with matchers, transcribers, declarative macros, Vec construction, and Rust type checking.

Also explained in

Compare how 2 books explain macro repetition →

Related concepts

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