liveBook · Manning

Fragment specifier

As explained in Learn Rust in a Month of Lunches

A fragment specifier is a macro pattern annotation that declares what syntactic category of token input a metavariable can match.

A fragment specifier tells a Rust macro what syntactic category a metavariable may match. In `$input:expr`, `expr` accepts an expression; in `$input:stmt`, `stmt` accepts a statement. section 22.2

Expression versus statement

A macro expecting `$input:expr` rejects `let x = 9` with a “no rules expected” error. Changing the specifier to `$input:stmt` makes that input match. The compiler feedback identifies both the unexpected token and the metavariable pattern being matched. section 22.2

block | expr | ident | item | lifetime | literal  | meta | pat | path 
| stmt | tt | ty | vis.

Browse the available fragment specifiers, including `expr`, `ident`, `stmt`, `tt`, `ty`, and others. section 22.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains matching with expression and statement examples, then lists the available specifiers without requiring memorization.
Examples
Uses `$input:expr` with values and vectors, contrasts it with `$input:stmt`, and demonstrates `ident` and `tt` patterns.
What it assumes
Assumes basic Rust macro use while defining fragment terminology and categories from examples.
What you can do after
Build macro_rules! patterns that accept appropriately categorized input and interpret compiler matching errors.
How it connects
Connects macro_rules!, metavariables, expressions, statements, identifiers, and token trees.

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 Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.