#[non_exhaustive]pub enum Pattern<K> {
Token(K),
Group {
open: K,
close: K,
body: Vec<Pattern<K>>,
},
Bind {
name: Symbol,
fragment: Fragment<K>,
},
Repeat {
body: Vec<Pattern<K>>,
separator: Option<K>,
kleene: Kleene,
},
}Expand description
One element of a rule’s pattern — the left-hand side of a macro_rules! arm.
A pattern is a sequence of elements matched against an invocation’s token
trees from left to right. Literal tokens and groups must appear exactly;
a Bind captures a tree under a name the template can
substitute; a Repeat matches its body any number of
times. The whole pattern must consume the whole invocation.
Patterns are plain data: a language’s front end parses its own macro
syntax (say $x:ident or $($e:expr),*) and lowers it into these
elements. Macro::new validates and compiles them.
Literal tokens compare by kind alone. Spans never matter to a match, and
neither do hygiene contexts: a literal else in a pattern matches an else
token whichever expansion introduced it.
The enum is #[non_exhaustive] so that new kinds of pattern element can be
added in a minor release. Constructing any variant is unaffected; code that
matches on a Pattern needs a wildcard arm.
§Examples
The pattern $name:tt = ( $($arg:tt),* ) with char tokens:
use macro_lang::{Fragment, Kleene, Pattern};
use intern_lang::Interner;
let mut names = Interner::new();
let pattern: Vec<Pattern<char>> = vec![
Pattern::Bind { name: names.intern("name"), fragment: Fragment::Tree },
Pattern::Token('='),
Pattern::Group {
open: '(',
close: ')',
body: vec![Pattern::Repeat {
body: vec![Pattern::Bind { name: names.intern("arg"), fragment: Fragment::Tree }],
separator: Some(','),
kleene: Kleene::ZeroOrMore,
}],
},
];
assert_eq!(pattern.len(), 3);Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
Token(K)
Matches a single token whose kind equals this one.
Group
Matches a delimited group with these delimiter kinds whose contents
match body exactly.
Bind
Captures one tree under name — a metavariable, $name:fragment.
Fields
Repeat
Matches body repeatedly — $( ... ) sep kleene.
Every metavariable bound inside the body captures one tree per
repetition, and a template must expand it inside a matching
Template::Repeat.
Fields
body: Vec<Pattern<K>>The pattern matched on each repetition. It must consume at least one tree; a body that can match nothing is rejected, since it could repeat forever.
separator: Option<K>A token kind required between repetitions, such as ,. Not allowed
with Kleene::ZeroOrOne, which never repeats.