Sub topic 3
Tokens in, tokens out: TokenStream
This chapter assumes you can read Rust comfortably, know how a Cargo package is laid out, and have already created a crate with proc-macro = true under [lib]. You don't need syn or quote yet. Everything here uses only the compiler's own proc_macro library, so the crate has no dependencies.
What a procedural macro actually receives
A procedural macro does not receive source text or a syntax tree. It receives a TokenStream, which is a sequence of tokens that the compiler has already split out of the source. It returns another TokenStream, and the compiler splices that into the program in place of the macro call.
Every macro kind has the same shape at its core:
- A function-like macro takes one stream (the text between the delimiters) and returns one stream.
- A derive macro takes one stream (the annotated item) and returns a stream that is appended after the item.
- An attribute macro takes two streams (the attribute arguments and the item) and returns a stream that replaces the item.
Because the output is only tokens, the compiler checks it afterward like any other code. If your macro emits let x = ;, the error appears when the compiler parses the output, not inside your macro.
Token trees
A TokenStream is an iterator over TokenTree values. A token tree is one of four things:
| Variant | What it represents | Example |
|---|---|---|
| `Ident` | An identifier or keyword | `foo`, `struct`, `r#type` |
| `Punct` | One punctuation character | `+`, `,`, `<` |
| `Literal` | A literal value | `42`, `"text"`, `1.5f32`, `'c'` |
| `Group` | Tokens inside matching delimiters | `(a, b)`, `{ ... }`, `[1, 2]` |
The word "tree" comes from Group. A group holds its own TokenStream, which can contain more groups. Brackets are therefore always balanced and nested correctly before your code runs. A stream with an unmatched ( never reaches your macro.
Three details trip people up.
Punct is one character. The operator => arrives as two Punct values: = and >. Each carries a Spacing. Joint means another punctuation character follows immediately with no whitespace. Alone means it does not. Spacing is how you tell => from = >.
Delimiters come in four kinds. Delimiter has Parenthesis, Brace, Bracket, and None. A None group is invisible. It appears when a macro_rules! macro passes a captured fragment such as $e:expr into your macro, so that the compiler can keep the expression's precedence intact. You rarely write one, but you may need to look inside one.
Lifetimes are two tokens. 'a arrives as a Punct with the character ' (spacing Joint) followed by an Ident named a.
Seeing the tokens
The fastest way to learn the model is to print it. This macro walks the input and returns a string literal that describes each token tree, indenting by nesting depth.
use proc_macro::{Delimiter, Literal, TokenStream, TokenTree};
fn describe(stream: TokenStream, depth: usize, out: &mut Vec<String>) {
let indent = " ".repeat(depth);
for tree in stream {
match tree {
TokenTree::Group(g) => {
let (open, close) = match g.delimiter() {
Delimiter::Parenthesis => ("(", ")"),
Delimiter::Brace => ("{", "}"),
Delimiter::Bracket => ("[", "]"),
Delimiter::None => ("<none>", "</none>"),
};
out.push(format!("{indent}Group {open}"));
describe(g.stream(), depth + 1, out);
out.push(format!("{indent}Group {close}"));
}
TokenTree::Ident(i) => out.push(format!("{indent}Ident {i}")),
TokenTree::Punct(p) => {
out.push(format!("{indent}Punct {} {:?}", p.as_char(), p.spacing()))
}
TokenTree::Literal(l) => out.push(format!("{indent}Literal {l}")),
}
}
}
#[proc_macro]
pub fn token_tree(input: TokenStream) -> TokenStream {
let mut lines = Vec::new();
describe(input, 0, &mut lines);
let text = lines.join("\n");
TokenTree::Literal(Literal::string(&text)).into()
}Call it from another crate that depends on this one, here named my_macros:
fn main() {
println!("{}", my_macros::token_tree!(a + b => (1, "x")));
}The program prints:
Ident a
Punct + Alone
Ident b
Punct = Joint
Punct > Alone
Group (
Literal 1
Punct , Alone
Literal "x"
Group )Note that => appears as = with Joint followed by > with Alone. The > is Alone because whitespace follows it. The parenthesized part is a single Group, and its contents are one level deeper.
The macro returns TokenTree::Literal(...).into(). TokenStream implements From<TokenTree>, so a single tree converts directly into a stream.
Building a stream
You can construct output in three ways.
Parse a string. TokenStream implements FromStr, so a string of Rust code becomes tokens:
use proc_macro::TokenStream;
#[proc_macro]
pub fn make_answer(_input: TokenStream) -> TokenStream {
"fn answer() -> u32 { 42 }".parse().unwrap()
}After my_macros::make_answer!(); at module level, the function answer() exists and returns 42. This is fine for fixed output. It becomes awkward as soon as you need to insert values, which is what quote! solves in a later chapter.
Construct trees by hand. Each variant has constructors: Ident::new("name", span), Punct::new('+', Spacing::Alone), Literal::u32_suffixed(42), and Group::new(Delimiter::Brace, inner_stream). This is precise but verbose.
Collect or extend. TokenStream implements FromIterator<TokenTree> and Extend<TokenTree>, so you can collect() a vector of trees or call stream.extend(...) to append to an existing one.
Every constructed Ident, Punct, Literal, and Group carries a Span, a source location the compiler uses for error messages and name resolution. Hand-built tokens default to Span::call_site(), the location of the macro invocation. A later chapter covers what spans mean for hygiene. For now, keep in mind that tokens copied from the input keep their original spans, and that is why errors can point at the user's code.
proc_macro versus proc_macro2
The proc_macro crate ships with the compiler, and its types only work while the compiler is running a macro. Calling TokenStream::new() or "x".parse::<TokenStream>() from an ordinary test or binary panics, because there is no compiler context behind it.
The proc-macro2 crate mirrors the same API (TokenStream, TokenTree, Span, and so on) and adds a fallback implementation that works anywhere. Inside a macro invocation it wraps the real compiler types. Outside one, it uses its own. This has two consequences:
- Code that uses
proc_macro2types can be unit-tested with plaincargo test. synandquoteare built onproc_macro2, not onproc_macro.
Entry points still must use proc_macro::TokenStream, since the compiler requires it in the signature of every #[proc_macro], #[proc_macro_derive], and #[proc_macro_attribute] function. You convert at the boundary:
use proc_macro::TokenStream;
#[proc_macro]
pub fn passthrough(input: TokenStream) -> TokenStream {
let input2: proc_macro2::TokenStream = input.into();
// ... work with proc_macro2 types, syn, and quote here ...
input2.into()
}Both From conversions are cheap. The usual pattern is to convert once at the entry point, do all work in proc_macro2 types, and convert back once at the end.
Common errors
- Panics in a normal test. Using
proc_macro::TokenStreamin a#[test]fails with "procedural macro API is used outside of a procedural macro". Switch the helper toproc_macro2. - Matching
=>as one token. Compare two consecutivePunctvalues and check that the first isJoint. Better, letsynparse it, as the next chapter shows. - Ignoring
Delimiter::None. Code that expects aParenthesisgroup may fail on an invisible group produced bymacro_rules!. Recurse into it. - Treating the output as checked. Nothing validates your output until the compiler parses it, so a malformed result surfaces as an error at the macro call site.
Exercise
A macro receives the tokens x >= 1 from source code. List the token trees it sees, including the Spacing of each Punct.
Show answer
Four trees: Ident x, Punct > with Spacing::Joint (the = follows immediately), Punct = with Spacing::Alone (whitespace follows), and Literal 1. The operator >= is two separate Punct values, not one token.
Exercise
Why does "x".parse::<proc_macro::TokenStream>() panic when called inside an ordinary #[test], and what is the usual fix?
Show answer
The proc_macro types depend on the compiler's macro-expansion context, which does not exist outside a macro invocation. The fix is to write the logic against proc_macro2 types, which fall back to their own implementation, and convert to and from proc_macro::TokenStream only in the entry-point function.