Skip to main content

easy_macros_helpers/
tokens_builder.rs

1use proc_macro2::TokenStream;
2
3/// A builder for accumulating and formatting token streams in procedural macros.
4///
5/// `TokensBuilder` provides a convenient way to collect multiple token streams
6/// and combine them into a single result. It's particularly useful when generating
7/// code that consists of multiple statements or items that need to be grouped together.
8///
9/// # Examples
10///
11#[doc = docify::embed!("src/examples.rs", tokens_builder_basic_usage)]
12#[derive(Debug, Default)]
13pub struct TokensBuilder {
14    result: TokenStream,
15}
16
17impl TokensBuilder {
18    /// Adds a token stream to the accumulated result.
19    ///
20    /// The new tokens are appended to the existing token stream.
21    /// This method can be called multiple times to build up complex token sequences.
22    ///
23    /// # Arguments
24    ///
25    /// * `item` - The token stream to add to the result
26    ///
27    /// # Examples
28    ///
29    #[doc = docify::embed!("src/examples.rs", tokens_builder_add_example)]
30    pub fn add(&mut self, item: TokenStream) {
31        self.result.extend(item);
32    }
33
34    /// Wraps the accumulated result with a pair of braces, creating a block expression.
35    ///
36    /// This is useful when you want to group multiple statements or expressions
37    /// into a single block that can be used as an expression or statement.
38    ///
39    /// # Examples
40    ///
41    #[doc = docify::embed!("src/examples.rs", tokens_builder_braced_example)]
42    pub fn braced(&mut self) {
43        replace_with::replace_with_or_abort(&mut self.result, |result| {
44            quote::quote! {
45                {
46                    #result
47                }
48            }
49        });
50    }
51
52    /// Consumes the `TokensBuilder` and returns the final token stream.
53    ///
54    /// This method should be called once you've finished building your result
55    /// and are ready to return it from your function procedural macro.
56    ///
57    /// # Returns
58    ///
59    /// The accumulated token stream
60    ///
61    /// # Examples
62    ///
63    #[doc = docify::embed!("src/examples.rs", tokens_builder_finalize_example)]
64    pub fn finalize(self) -> TokenStream {
65        self.result
66    }
67}