rune/macros/
quote_fn.rs

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
39
40
41
42
43
44
45
46
47
48
49
50
51
use core::fmt;

use crate::alloc;
use crate::macros::{MacroContext, ToTokens, TokenStream};

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

/// Construct a token stream from a function.
pub fn quote_fn<'a, T>(f: T) -> Quote<'a>
where
    T: 'a + Fn(&mut MacroContext<'_, '_, '_>, &mut TokenStream) -> alloc::Result<()> + Send + Sync,
{
    // TODO: somehow support CoerceUnsized.
    Quote(rust_alloc::boxed::Box::new(f))
}

/// [ToTokens] implementation generated by [quote_fn].
pub struct Quote<'a>(rust_alloc::boxed::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,
        cx: &mut MacroContext<'_, '_, '_>,
    ) -> alloc::Result<TokenStream> {
        let mut stream = TokenStream::new();
        self.to_tokens(cx, &mut stream)?;
        Ok(stream)
    }
}

impl<'a> ToTokens for Quote<'a> {
    fn to_tokens(
        &self,
        context: &mut MacroContext<'_, '_, '_>,
        stream: &mut TokenStream,
    ) -> alloc::Result<()> {
        (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()
    }
}