1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use crate::macros::{MacroContext, ToTokens, TokenStream};
use std::fmt;

type EncodeFn<'a> = dyn Fn(&MacroContext, &mut TokenStream) + Send + Sync + 'a;

/// Construct a token stream from a function.
pub fn quote_fn<'a, T>(f: T) -> Quote<'a>
where
    T: 'a + Fn(&MacroContext, &mut TokenStream) + Send + Sync,
{
    Quote(Box::new(f))
}

/// [ToTokens] implementation generated by [quote_fn].
pub struct Quote<'a>(Box<EncodeFn<'a>>);

impl<'a> Quote<'a> {
    /// Convert into token stream.
    ///
    /// # Panics
    ///
    /// This panics if called outside of a macro context.
    pub fn into_token_stream(self) -> TokenStream {
        TokenStream::from_to_tokens(self)
    }
}

impl<'a> ToTokens for Quote<'a> {
    fn to_tokens(&self, context: &MacroContext, stream: &mut TokenStream) {
        (self.0)(context, stream)
    }
}

impl<'a> fmt::Debug for Quote<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Quote").finish()
    }
}