aboutsummaryrefslogtreecommitdiff
path: root/macros/src/fn_trait.rs
blob: 9820f028e7431582bdd281a290c6c8b4df882336 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use quote::ToTokens;
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::token::Paren;
use syn::{parenthesized, parse_str, Ident, Token, TraitBound, 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,
    pub trait_bounds: Punctuated<TraitBound, Token![+]>,
}

impl FnTrait
{
    pub fn add_trait_bound(&mut self, trait_bound: TraitBound)
    {
        self.trait_bounds.push(trait_bound);
    }
}

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,
            trait_bounds: Punctuated::new(),
        })
    }
}

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);

        if !self.trait_bounds.is_empty() {
            let plus: Token![+] = parse_str("+").unwrap();

            plus.to_tokens(tokens);

            self.trait_bounds.to_tokens(tokens);
        }
    }
}