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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use better_any::{Tid, TidAble};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{Ident, TraitBound, Type};

use crate::{
    context::Context,
    into_template::IntoTemplate,
    maybe_borrowed::{FromMaybeBorrowed, MaybeBorrowed},
    passed_data::{PassedData, WithData},
    token_cmp_wrapper::TokenCmpWrapper,
};

use super::{Generatable, StaticTid};

/// A trait Generatable / Template. This asserts that some type implements some trait.
#[derive(Tid)]
pub struct Trait<'a> {
    /// The trait bound to check the type implements
    trait_bound: MaybeBorrowed<'a, TraitBound>,
}

impl<'a> Trait<'a> {
    /// Creates a new trait template from some trait bound.
    /// Takes any T that can be turned into a `MaybeBorrowed` type, to support
    /// references as well as owned types
    pub fn new<T>(trait_bound: T) -> Self
    where
        T: Into<MaybeBorrowed<'a, TraitBound>>,
    {
        Self {
            trait_bound: trait_bound.into(),
        }
    }
}

impl<'a> FromMaybeBorrowed<'a, TraitBound> for Trait<'a> {
    fn from_maybe_borrowed(from: MaybeBorrowed<'a, TraitBound>) -> Self {
        Self::new(from)
    }
}

impl<'a> IntoTemplate<'a> for TraitBound {
    type Template = Trait<'a>;

    fn into_template<T: crate::into_template::TypeEq<This = Self::Template>>(
        self,
    ) -> Self::Template {
        Trait::new(self)
    }
}

impl<'a> IntoTemplate<'a> for &'a TraitBound {
    type Template = Trait<'a>;

    fn into_template<T: crate::into_template::TypeEq<This = Self::Template>>(
        self,
    ) -> Self::Template {
        Trait::new(self)
    }
}

impl<'a> PartialOrd for Trait<'a> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(Ord::cmp(self, other))
    }
}

impl<'a> Ord for Trait<'a> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        Ord::cmp(
            &self.trait_bound.to_token_stream().to_string(),
            &other.trait_bound.to_token_stream().to_string(),
        )
    }
}

impl<'a> PartialEq for Trait<'a> {
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(
            &self.trait_bound.to_token_stream().to_string(),
            &other.trait_bound.to_token_stream().to_string(),
        )
    }
}

impl<'a> Eq for Trait<'a> {}

impl<'a> Generatable<'a, TokenCmpWrapper<Type>> for Trait<'a> {
    type GeneratableData = ();
    type TemplateData = Ident;

    const EMITS_NON_CONSTANT_CODE: bool = false;

    fn template(
        &self,
        Context {
            ident_generator, ..
        }: &mut Context,
        _passed: &Self::GeneratableData,
    ) -> PassedData<Self::TemplateData> {
        let fn_ident = ident_generator.prefixed("assert_trait_bound");
        let trait_bound = &*self.trait_bound;

        quote! {
            fn #fn_ident<T: #trait_bound>() {}
        }
        .with_data(fn_ident)
    }

    fn assert(
        &self,
        _context: &mut Context,
        (_, assert_trait_bound): (&Self::GeneratableData, &Self::TemplateData),
        to_assert: &TokenCmpWrapper<syn::Type>,
    ) -> Option<TokenStream> {
        Some(quote! {
            #assert_trait_bound::<#to_assert>();
        })
    }

    fn generatable(_context: &mut Context) -> PassedData<Self::GeneratableData>
    where
        Self: Sized,
    {
        PassedData::default()
    }
}

impl<'a> Generatable<'a, StaticTid<Ident>> for Trait<'a> {
    type GeneratableData = ();
    type TemplateData = Ident;

    const EMITS_NON_CONSTANT_CODE: bool = true;

    fn template(
        &self,
        Context {
            ident_generator, ..
        }: &mut Context,
        _passed: &Self::GeneratableData,
    ) -> PassedData<Self::TemplateData> {
        let fn_ident = ident_generator.prefixed("assert_trait_bound");
        let trait_bound = &*self.trait_bound;

        quote! {
            fn #fn_ident<T: #trait_bound>(_v: T) {}
        }
        .with_data(fn_ident)
    }

    fn assert(
        &self,
        _context: &mut Context,
        (_, assert_trait_bound): (&Self::GeneratableData, &Self::TemplateData),
        to_assert: &StaticTid<proc_macro2::Ident>,
    ) -> Option<TokenStream> {
        Some(quote! {
            #assert_trait_bound(#to_assert);
        })
    }

    fn generatable(_context: &mut Context) -> PassedData<Self::GeneratableData>
    where
        Self: Sized,
    {
        PassedData::default()
    }
}

#[cfg(test)]
mod test {
    use quote::quote;
    use syn::parse_quote;

    use crate::{
        context::Context,
        generatable::Generatable,
        ident_generator::MockIdentGenerator,
        maybe_borrowed::MaybeBorrowed,
        passed_data::{PassedData, WithData},
        token_cmp_wrapper::TokenCmpWrapper,
    };

    use super::Trait;

    #[test]
    fn generate_generatable() {
        let mut mock_ident_gen = MockIdentGenerator::new();
        let mut context = Context::new(&mut mock_ident_gen);

        assert_eq!(
            <Trait as Generatable<TokenCmpWrapper<syn::Type>>>::generatable(&mut context),
            PassedData::default()
        );
        assert!(mock_ident_gen.was_not_called());
    }

    #[test]
    fn generate_template() {
        let mut mock_ident_gen = MockIdentGenerator::new();

        mock_ident_gen.push_ident("mock_1");

        let mut context = Context::new(&mut mock_ident_gen);
        assert_eq!(
            <Trait as Generatable<TokenCmpWrapper<syn::Type>>>::template(
                &Trait {
                    trait_bound: MaybeBorrowed::Owned(parse_quote!(::test_mod::Test))
                },
                &mut context,
                &()
            ),
            quote! {
                fn assert_trait_bound_mock_1<T: ::test_mod::Test>() {}
            }
            .with_data(parse_quote!(assert_trait_bound_mock_1))
        );
        assert!(mock_ident_gen.has_no_idents_remaining());
    }

    #[test]
    fn generate_assert() {
        let mut mock_ident_gen = MockIdentGenerator::new();
        let mut context = Context::new(&mut mock_ident_gen);

        let test_type: syn::Type = parse_quote!(TestType);

        assert_eq!(
            <Trait as Generatable<TokenCmpWrapper<syn::Type>>>::assert(
                &Trait {
                    trait_bound: MaybeBorrowed::Owned(parse_quote!(::test_mod::Test))
                },
                &mut context,
                (&(), &parse_quote!(assert_trait_bound_mock_1)),
                &test_type.into()
            )
            .as_ref()
            .map(ToString::to_string),
            Some(quote! {
                assert_trait_bound_mock_1::<TestType>();
            })
            .as_ref()
            .map(ToString::to_string)
        );
        assert!(mock_ident_gen.was_not_called());
    }
}