aboutsummaryrefslogtreecommitdiff
path: root/macros/src/fn_trait.rs
blob: d88d391d12e630323be382c53f1bb50b7b0ec24d (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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, PartialEq, Eq)]
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);
        }
    }
}

#[cfg(test)]
mod tests
{
    use std::error::Error;

    use quote::{format_ident, quote};
    use syn::token::{Dyn, RArrow};
    use syn::{parse2, PathSegment};

    use super::*;
    use crate::test_utils;

    #[test]
    fn can_parse_fn_trait() -> Result<(), Box<dyn Error>>
    {
        assert_eq!(
            parse2::<FnTrait>(quote! {
                dyn Fn(String, u32) -> Handle
            })?,
            FnTrait {
                dyn_token: Dyn::default(),
                trait_ident: format_ident!("Fn"),
                paren_token: Paren::default(),
                inputs: Punctuated::from_iter(vec![
                    test_utils::create_type(test_utils::create_path(&[
                        PathSegment::from(format_ident!("String"))
                    ])),
                    test_utils::create_type(test_utils::create_path(&[
                        PathSegment::from(format_ident!("u32"))
                    ]))
                ]),
                r_arrow_token: RArrow::default(),
                output: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Handle"))
                ])),
                trait_bounds: Punctuated::new()
            }
        );

        assert!(parse2::<FnTrait>(quote! {
            Fn(u32) -> Handle
        })
        .is_err());

        Ok(())
    }

    #[test]
    fn can_parse_fn_trait_to_tokens()
    {
        assert_eq!(
            FnTrait {
                dyn_token: Dyn::default(),
                trait_ident: format_ident!("Fn"),
                paren_token: Paren::default(),
                inputs: Punctuated::from_iter(vec![
                    test_utils::create_type(test_utils::create_path(&[
                        PathSegment::from(format_ident!("Bread"))
                    ])),
                    test_utils::create_type(test_utils::create_path(&[
                        PathSegment::from(format_ident!("Cheese"))
                    ])),
                    test_utils::create_type(test_utils::create_path(&[
                        PathSegment::from(format_ident!("Tomatoes"))
                    ]))
                ]),
                r_arrow_token: RArrow::default(),
                output: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Taco"))
                ])),
                trait_bounds: Punctuated::new()
            }
            .into_token_stream()
            .to_string(),
            "dyn Fn (Bread , Cheese , Tomatoes) -> Taco".to_string()
        );
    }
}