Sub topic 3
Tokens in, tokens out: TokenStream
This chapter assumes you have a proc-macro crate set up with proc-macro = true and know what a #[proc_macro] function is. It does not use syn or quote yet. Those build on the types described here.
What a procedural macro receives
Every procedural macro is a function from TokenStream to TokenStream. The compiler lexes the source text into tokens. It hands your macro the tokens, not a syntax tree and not text. Whatever you return is parsed as ordinary Rust at the call site.
A TokenStream is a sequence of TokenTree values. You can iterate over it.
The four kinds of token tree
TokenTree is an enum with four variants.
| Variant | Meaning | Example |
|---|---|---|
| `Ident` | A name or keyword | `foo`, `struct` |
| `Punct` | One punctuation character | `+`, `,`, `#` |
| `Literal` | A literal value | `42`, `"hi"`, `1.5f32` |
| `Group` | Tokens inside `()`, `[]`, `{}` or an invisible delimiter | `(a, b)` |
A Group holds a nested TokenStream, so the stream is a tree, not a flat list. Matching brackets are therefore always paired for you.
Multi-character operators are split into several Punct tokens. Each Punct carries a Spacing. Joint means another punctuation character follows immediately. Alone means it does not. So -> arrives as - (Joint) and > (Alone).
Inspecting a stream
The macro below prints each top-level token tree during compilation and expands to nothing.
use proc_macro::{TokenStream, TokenTree};
#[proc_macro]
pub fn dump_tokens(input: TokenStream) -> TokenStream {
for tree in input {
match tree {
TokenTree::Group(g) => eprintln!("Group {:?}: {}", g.delimiter(), g),
TokenTree::Ident(i) => eprintln!("Ident: {}", i),
TokenTree::Punct(p) => eprintln!("Punct: {} ({:?})", p.as_char(), p.spacing()),
TokenTree::Literal(l) => eprintln!("Literal: {}", l),
}
}
TokenStream::new()
}Call it from another crate that depends on this one:
fn main() {
my_macros::dump_tokens!(a -> (b, 2) "hi");
}Build the calling crate and the compiler output shows an Ident, two Punct tokens, a parenthesis Group and a Literal. The (b, 2) group appears as one item. Its contents are a nested stream you would have to iterate separately.
Tokens carry no meaning. The input a -> (b, 2) "hi" is not valid Rust, but the lexer accepts it, so the macro runs. Rejecting bad input is your job, and later chapters cover it with syn.
proc_macro versus proc_macro2
The proc_macro crate ships with the compiler, and its types work only while the compiler is running your macro. If you call them from a unit test or a plain binary, they panic.
proc_macro2 mirrors the same types (TokenStream, TokenTree, Span) with a fallback implementation that works anywhere. syn and quote are built on it. You convert at the boundary with .into():
use proc_macro::TokenStream;
#[proc_macro]
pub fn passthrough(input: TokenStream) -> TokenStream {
let inner: proc_macro2::TokenStream = input.into();
// ...work with proc_macro2 types here...
inner.into()
}Common errors
- Calling
proc_macroAPIs outside a macro invocation fails at runtime with a panic about "procedural macro API is used outside of a procedural macro". - Treating
->or==as one token. Each is severalPuncttokens. - Forgetting that a
Groupis one tree. Walking only the top level skips nested tokens.
Exercise
The input x >= (1) reaches your macro. How many top-level token trees does it contain, and what are their kinds?
Show answer
Four. The tokens are an Ident (x), two Punct tokens (> Joint, then = Alone), and one Group ((1)). The 1 is inside the group's nested stream, not at the top level.