liveBook · Manning

Fragment specifier

As explained in Write Powerful Rust Macros

A fragment specifier is the annotation in a declarative macro matcher that selects the syntactic category accepted by a metavariable.

A fragment specifier tells a declarative macro matcher which Rust syntactic category a metavariable may capture. For example, $x:expr captures one expression, while ident captures an identifier or keyword. section 2.1.4

Choose the narrowest fragment category that fits the macro input:

  • Use expr for expressions and ident for identifiers; other categories include block, item, literal, and type. section 2.1.4
  • Use tt, or TokenTree, when the matcher must accept almost anything, but expect less precise checking and test carefully. section 2.1.4

Capturing an expression

A matcher such as {$x:expr} accepts one expression and binds it to x, allowing the expansion to push that value into a newly created vector. section 2.1.4

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

Inspect the expression matcher and its expansion, including the metavariable binding and generated vector operations. section 2.1.4

How Write Powerful Rust Macros covers it

How deep it goes
Explains common categories and the precision trade-off between concrete specifiers and TokenTree matching.
Examples
Uses expression capture to build vectors and contrasts concrete fragment matching with broad TokenTree matching.
What you can do after
Apply via declarative macros by choosing fragment specifiers that constrain inputs and testing broader TokenTree matchers carefully.
How it connects
Connects declarative macros with metavariables, expressions, identifiers, TokenTree matching, and regular-expression selectivity.

Also explained in

Compare how 2 books explain fragment specifier →

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.