The proc_macro Crate
The compiler-provided proc_macro crate defines the primary low-level types for
procedural macro manipulation. These are the actual types underlying the tokens
we match in declarative macros:
TokenStream: An iterator over a sequence ofTokenTreevalues.TokenTree: An enum representing individual lexical units. It has four variants:Group: A bracketed group of tokens (e.g.,(a + b),{ ... }).Ident: An identifier or keyword (e.g.,foo,fn,let,false).Punct: A single punctuation character (e.g.,+,,,:, but not combined operators like+=, nor brackets).Literal: A literal value (e.g.,"hello",42,3.14).
pub enum TokenTree {
Group(Group),
Ident(Ident),
Punct(Punct),
Literal(Literal),
}
- Discuss that
proc_macrois a built-in crate, so you don’t need to add it to yourCargo.tomldependencies (just definingproc-macro = truemakes it automatically available). TokenStreamcan be converted to and from strings viato_string()andparse(), but doing so breaks its relation to its original source code location (Span), which should be preserved so compiler error messages can point at the relevant code.