TokenStream in Rust

In Rust, a TokenStream is a fundamental component used in the creation of procedural macros. It represents a sequence of tokens that can be manipulated programmatically to generate or transform Rust code. This concept is crucial for metaprogramming, allowing developers to write code that writes other code, thus enhancing the capabilities of Rust programs.

Understanding TokenStream

A TokenStream is essentially a sequence of tokens that represents Rust code. It serves as both the input and output of procedural macros, which are a type of macro in Rust that operates on the abstract syntax tree (AST) of the code. By using TokenStream, macros can manipulate Rust code at a syntactic level, providing the ability to generate and transform code programmatically.

Procedural Macros and TokenStream

Procedural macros in Rust are functions that take a TokenStream as input and produce a TokenStream as output. This allows developers to write code that can generate or modify other code at compile time. The proc_macro crate provides the necessary tools to work with TokenStream.

Example: A Simple Procedural Macro

Below is a simple example of a procedural macro that prints "hello world":

use proc_macro::TokenStream;

#[proc_macro]
pub fn say_hello_world(_item: TokenStream) -> TokenStream {
    "println!(\"hello world\")".parse().unwrap()
}
  • Attributes: The #[proc_macro] attribute indicates that the function is a procedural macro.
  • Function Signature: The function say_hello_world takes a TokenStream and returns a TokenStream.
  • Implementation: The macro parses a string into a TokenStream using the parse() method, which is part of the FromStr trait.

Derive Macros and TokenStream

Derive macros are a specific type of procedural macro that automatically implements traits for data structures. The TokenStream is used to parse the input and generate the necessary code.

Example: Implementing a Derive Macro

The following example demonstrates how to implement a derive macro named PrintName:

#[proc_macro_derive(PrintName)]
pub fn print_name(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let generics = add_trait_bounds(input.generics);
    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();

    let name = input.ident;

    let expanded = quote! {
        impl #impl_generics print_name::PrintName for #name #type_generics
                #where_clause {
            fn name() -> &'static str {
                stringify!(#name)
            }
        }
    };

    TokenStream::from(expanded)
}

fn add_trait_bounds(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(print_name::PrintName));
        }
    }
    generics
}
  • Parsing Input: The parse_macro_input! macro from the syn crate is used to convert the input TokenStream into a syntax tree.
  • Trait Bounds: The add_trait_bounds function adds necessary trait bounds to generic parameters.
  • Code Generation: The quote! macro from the quote crate is used to generate the implementation of the PrintName trait. The stringify! macro is used to convert the type name into a string.
  • Output: The generated code is converted back into a TokenStream using TokenStream::from.

Example: Using TokenStream Without External Crates

The following example demonstrates how to use TokenStream without relying on external crates like syn and quote. This example defines a procedural macro named Hello that generates an implementation of a hello_world method for a given struct.

[Listing 3.11: Without syn and quote](https://livebook.manning.com/write-powerful-rust-macros/chapter-3/listing--3-11): Without syn and quote](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81)

use proc_macro::{TokenStream, TokenTree};

#[proc_macro_derive(Hello)]
pub fn hello_alt(item: TokenStream) -> TokenStream {
    fn ident_name(item: TokenTree) -> String {
        match item {
            TokenTree::Ident(i) => i.to_string(),
            _ => panic!("no ident")
        }
    }                 
    let name = ident_name(item.into_iter().nth(1).unwrap());

    format!("impl {} {{ fn hello_world(&self) {{ println!(\"Hello, World\") }} }} ", name
        ).parse()
        .unwrap()
}
  • Extracting the Identifier: The function ident_name takes a TokenTree and matches it to extract an identifier. If the token is an identifier, it converts it to a string. If not, it panics with the message "no ident".
  • Retrieving the Struct Name: The macro function hello_alt takes a TokenStream as input. It retrieves the second element of the TokenStream, which is expected to be the name of the struct, and passes it to the ident_name function to get the name as a string.
  • Generating the Implementation: The format! macro is used to create a string representation of an impl block that includes the hello_world method. This string is then parsed back into a TokenStream. The unwrap method is used to handle any parsing errors, which will cause a panic if the format is incorrect.

By understanding and utilizing TokenStream, developers can create powerful macros that enhance the capabilities of their Rust programs.

| Book Title | Usage of tokenstream | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|----------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Write Powerful Rust Macros](https://www.manning.com/books/write-powerful-rust-macros) | Discusses `TokenStream` as a core component in writing macros, focusing on its role in manipulating Rust code at a syntactic level. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81) | Explores `TokenStream` in the context of procedural macros, detailing its input and output roles. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81) | Connects `TokenStream` to procedural macros and the abstract syntax tree (AST). [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81) | Provides an example of using `TokenStream` without external crates like `syn` and `quote`. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81) | Demonstrates practical macro creation by generating a `hello_world` method for a struct. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-3/81) |
| [Idiomatic Rust](https://www.manning.com/books/idiomatic-rust) | Describes `TokenStream` as essential for procedural macros, used to generate or transform code. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-8/67) | Covers the use of `TokenStream` in procedural and derive macros, with emphasis on code generation. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-8/67) | Links `TokenStream` to procedural and derive macros, highlighting its role in trait implementation. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-8/67) | Includes examples of simple procedural macros and derive macros using `syn` and `quote`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-8/67) | Illustrates macro creation for trait implementation, enhancing code flexibility. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-8/67) |

FAQ (Frequently asked questions)

What is the role of the add_trait_bounds function in the PrintName derive macro?