aboutsummaryrefslogtreecommitdiff
path: root/macros/src/fn_trait.rs
blob: f9b3514b4022a735807429b07127cecbb18aabb9 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use quote::ToTokens;
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::token::Paren;
use syn::{parenthesized, Ident, Token, Type};

/// A function trait. `dyn Fn(u32) -> String`
#[derive(Debug, Clone)]
pub struct FnTrait
{
    pub dyn_token: Token![dyn],
    pub trait_ident: Ident,
    pub paren_token: Paren,
    pub inputs: Punctuated<Type, Token![,]>,
    pub r_arrow_token: Token![->],
    pub output: Type,
}

impl Parse for FnTrait
{
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self>
    {
        let dyn_token = input.parse::<Token![dyn]>()?;

        let trait_ident = input.parse::<Ident>()?;

        if trait_ident.to_string().as_str() != "Fn" {
            return Err(syn::Error::new(trait_ident.span(), "Expected 'Fn'"));
        }

        let content;

        let paren_token = parenthesized!(content in input);

        let inputs = content.parse_terminated(Type::parse)?;

        let r_arrow_token = input.parse::<Token![->]>()?;

        let output = input.parse::<Type>()?;

        Ok(Self {
            dyn_token,
            trait_ident,
            paren_token,
            inputs,
            r_arrow_token,
            output,
        })
    }
}

impl ToTokens for FnTrait
{
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream)
    {
        self.dyn_token.to_tokens(tokens);

        self.trait_ident.to_tokens(tokens);

        self.paren_token.surround(tokens, |tokens_inner| {
            self.inputs.to_tokens(tokens_inner);
        });

        self.r_arrow_token.to_tokens(tokens);

        self.output.to_tokens(tokens);
    }
}