TokenTree in Rust Macros
Overview
In Rust, a TokenTree is a fundamental component used in macro systems to handle tokens. It provides a flexible way to define and manipulate macros, allowing for complex and dynamic macro definitions. A TokenTree is an intermediary structure that sits between a TokenStream and simple tokens. Essentially, a TokenStream is a sequence of TokenTrees, which can recursively contain more trees and/or tokens. This hierarchical structure allows for the iteration over a stream, enabling the extraction and manipulation of individual TokenTree elements.
Usage in Macros
Declarative Macros
In declarative macros, the tt fragment specifier is used to denote a TokenTree. This allows the macro to capture a sequence of tokens as a single unit, which can then be processed or transformed as needed. This capability is particularly useful in scenarios where the macro needs to handle complex patterns or structures.
Procedural Macros
In procedural macros, TokenTree is used to parse and manipulate the input TokenStream. For example, in the lazy_static macro, TokenTrees are used to capture optional additional information, ensuring that the macro can handle a wide range of input patterns.
Example: Procedural Macro Without syn and quote
The following example demonstrates how a procedural macro can be implemented using TokenTree without relying on external libraries like syn and quote. This approach can lead to faster compilation times, although it may require more manual handling of tokens.
Listing 3.11 Without syn and quote
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(), // #1
_ => panic!("no ident")
}
}
let name = ident_name(item.into_iter().nth(1).unwrap()); // #2
format!("impl {} {{ fn hello_world(&self) \
{{ println!(\"Hello, World\\") }} }} ", name
).parse()
.unwrap() // #3
}
// #1 If we have a TokenTree containing an identifier, we return it as a string.
// #2 As an input for the previous function, we provide the second element of the TokenStream, which should be the name.
// #3 We use format! to add the retrieved name to a string representation of our impl block. Then we parse to turn it into a TokenStream. This will only fail if we made a mistake, in which case unwrap panicking is fine.
In this example, the macro extracts an identifier from the TokenStream and uses it to generate an implementation block. The format! macro is used to inject the identifier into a string, which is then parsed back into a TokenStream.
lazy_static Macro
The lazy_static macro is a well-known example that utilizes TokenTrees to manage its input. The macro allows for the creation of lazily initialized static variables. The input to the macro includes metadata, a static reference, an identifier, a type, and an initialization expression. These components are captured as TokenTrees, which are then processed by an internal macro to generate the necessary code.
Listing 2.20 lazy_static macro entry point, simplified slightly
#[macro_export]
macro_rules! lazy_static {
($(#[$attr:meta])* static ref $N:ident : $T:ty =
$e:expr; $($t:tt)*) => {
__lazy_static_internal!($(#[$attr])* () static ref $N :
$T = $e; $($t)*);
};
// other arms...
}
The lazy_static macro uses an internal macro, __lazy_static_internal, to handle the captured TokenTrees. This internal macro defines additional arms to create the necessary types and implement the Deref trait, ensuring that the static variable is initialized only once.
Listing 2.21 lazy_static internal, again simplified
macro_rules! __lazy_static_internal { // #1
($(#[$attr:meta])* ($($vis:tt)*) static ref
$N:ident : $T:ty = $e:expr; $($t:tt)*) => { // #2
__lazy_static_internal!(@MAKE TY, $(#[$attr])*,
($($vis)*), $N); // #3
__lazy_static_internal!(@TAIL, $N : $T = $e); // #4
};
(@TAIL, $N:ident : $T:ty = $e:expr) => {
impl $crate::__Deref for $N { // #5
type Target = $T;
fn deref(&self) -> &$T {
fn __static_ref_initialize() -> $T { $e }
fn __stability() -> &'static $T {
__lazy_static_create!(LAZY, $T);
LAZY.get(__static_ref_initialize)
}
__stability()
}
}
impl $crate::LazyStatic for $N { // #6
fn initialize(lazy: &Self) {
let _ = &**lazy;
}
}
};
(@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*),
$N:ident) => {
$(#[$attr])*
$($vis)* struct $N {__private_field: ()}
$($vis)* static $N: $N = $N {__private_field: ()};
};
}
macro_rules! __lazy_static_create {
($NAME:ident, $T:ty) => {
static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT;
};
}
// #1 This is a declarative macro declaration for a macro called lazy_static_internal.
// #2 The first matcher expects optional attributes, optional visibility, a literal “static ref” value, an identifier, type, and expression. Finally, and again optionally, we capture everything else in a TokenTree.
// #3 We call our own macro, and the @MAKE TY literal makes sure we end up in the last arm.
// #4 Similarly, here @TAIL makes sure we end up in the next arm.
// #5 This contains a lot of the magic of lazy static, using Deref to initialize our static.
// #6 Here, $crate is used to make sure that there is no collision with a LazyStatic defined anywhere else (i.e., we only want the LazyStatic defined in our crate).
In summary, TokenTree is a versatile tool in Rust's macro system, enabling the creation of powerful and flexible macros like lazy_static. By understanding and utilizing TokenTrees, developers can craft macros that handle complex patterns and generate efficient code.
FAQ (Frequently asked questions)
What is a TokenTree used for in the lazy_static macro?
How does a TokenTree help in macro definitions?
What is the relationship between a TokenTree and a TokenStream?
Why can we iterate over a TokenStream and assure Rust that the type is TokenTree?
What is the 'tt' fragment specifier in declarative macros?
How do you extract an identifier from a TokenTree?
What is the input for the ident_name function in the provided code?
How is the retrieved name used in the code example?