pub struct TokensBuilder { /* private fields */ }_helpers only.Expand description
Helper utilities for building procedural macros A builder for accumulating and formatting token streams in procedural macros.
TokensBuilder provides a convenient way to collect multiple token streams
and combine them into a single result. It’s particularly useful when generating
code that consists of multiple statements or items that need to be grouped together.
§Examples
let mut result = TokensBuilder::default();
// Add multiple token streams
result.add(quote! { let x = 1; });
result.add(quote! { let y = 2; });
result.add(quote! { println!("{} + {} = {}", x, y, x + y); });
// Wrap in braces to create a block
result.braced();
let tokens = result.finalize();
assert_eq!(
readable_token_stream(&tokens.to_string()),
"{ let x = 1; let y = 2; println!(\"{} + {} = {}\", x, y, x + y); }"
);Implementations§
Source§impl TokensBuilder
impl TokensBuilder
Sourcepub fn add(&mut self, item: TokenStream)
pub fn add(&mut self, item: TokenStream)
Adds a token stream to the accumulated result.
The new tokens are appended to the existing token stream. This method can be called multiple times to build up complex token sequences.
§Arguments
item- The token stream to add to the result
§Examples
let mut result = TokensBuilder::default();
result.add(quote! { fn hello() });
result.add(quote! { { println!("Hello, world!"); } });
let tokens = result.finalize();
assert_eq!(
readable_token_stream(&tokens.to_string()),
"fn hello() { println!(\"Hello, world!\"); }"
);Sourcepub fn braced(&mut self)
pub fn braced(&mut self)
Wraps the accumulated result with a pair of braces, creating a block expression.
This is useful when you want to group multiple statements or expressions into a single block that can be used as an expression or statement.
§Examples
let mut result = TokensBuilder::default();
result.add(quote! { let x = 42; });
result.add(quote! { x * 2 });
result.braced();
let tokens = result.finalize();
assert_eq!(
readable_token_stream(&tokens.to_string()),
"{ let x = 42; x * 2 }"
);Sourcepub fn finalize(self) -> TokenStream
pub fn finalize(self) -> TokenStream
Consumes the TokensBuilder and returns the final token stream.
This method should be called once you’ve finished building your result and are ready to return it from your function procedural macro.
§Returns
The accumulated token stream
§Examples
let mut result = TokensBuilder::default();
result.add(quote! { println!("Done!"); });
let final_tokens = result.finalize();
assert_eq!(
readable_token_stream(&final_tokens.to_string()),
"println!(\"Done!\");"
);