aboutsummaryrefslogtreecommitdiff
path: root/macros/src/injectable/dependency.rs
blob: 6ff0697055598b3766e2661fdb6cd79ae75232f5 (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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use proc_macro2::{Ident, Span};
use syn::spanned::Spanned;
use syn::{parse2, FnArg, GenericArgument, LitStr, PathArguments, Type};

use crate::injectable::named_attr_input::NamedAttrInput;
use crate::util::error::diagnostic_error_enum;
use crate::util::syn_path::SynPathExt;

/// Interface for a representation of a dependency of a injectable type.
///
/// Found as a argument in the 'new' method of the type.
#[cfg_attr(test, mockall::automock)]
pub trait IDependency: Sized
{
    /// Build a new `Dependency` from a argument in a 'new' method.
    fn build(new_method_arg: &FnArg) -> Result<Self, DependencyError>;

    /// Returns the interface type.
    fn get_interface(&self) -> &Type;

    /// Returns the pointer type identity.
    fn get_ptr(&self) -> &Ident;

    /// Returns optional name of the dependency.
    fn get_name(&self) -> &Option<LitStr>;
}

/// Representation of a dependency of a injectable type.
///
/// Found as a argument in the 'new' method of the type.
#[derive(Debug, PartialEq, Eq)]
pub struct Dependency
{
    interface: Type,
    ptr: Ident,
    name: Option<LitStr>,
}

impl IDependency for Dependency
{
    fn build(new_method_arg: &FnArg) -> Result<Self, DependencyError>
    {
        let typed_new_method_arg = match new_method_arg {
            FnArg::Typed(typed_arg) => Ok(typed_arg),
            FnArg::Receiver(receiver_arg) => Err(DependencyError::UnexpectedSelf {
                self_token_span: receiver_arg.self_token.span,
            }),
        }?;

        let dependency_type_path = match typed_new_method_arg.ty.as_ref() {
            Type::Path(arg_type_path) => Ok(arg_type_path),
            Type::Reference(ref_type_path) => match ref_type_path.elem.as_ref() {
                Type::Path(arg_type_path) => Ok(arg_type_path),
                other_type => Err(DependencyError::InvalidType {
                    type_span: other_type.span(),
                }),
            },
            other_type => Err(DependencyError::InvalidType {
                type_span: other_type.span(),
            }),
        }?;

        let ptr_path_segment = dependency_type_path.path.segments.last().map_or_else(
            || {
                Err(DependencyError::MissingType {
                    arg_span: typed_new_method_arg.span(),
                })
            },
            Ok,
        )?;

        let ptr_ident = ptr_path_segment.ident.clone();

        let ptr_generic_args = match ptr_path_segment.arguments.clone() {
            PathArguments::AngleBracketed(generic_args) => Ok(generic_args),
            _ => Err(DependencyError::DependencyTypeMissingGenerics {
                ptr_ident_span: ptr_ident.span(),
            }),
        }?
        .args;

        let interface =
            if let Some(GenericArgument::Type(interface)) = ptr_generic_args.first() {
                Ok(interface.clone())
            } else {
                Err(DependencyError::DependencyTypeMissingGenerics {
                    ptr_ident_span: ptr_ident.span(),
                })
            }?;

        let arg_attrs = &typed_new_method_arg.attrs;

        let opt_named_attr = arg_attrs.iter().find(|attr| {
            attr.path.get_ident().map_or_else(
                || false,
                |attr_ident| attr_ident.to_string().as_str() == "named",
            ) || &attr.path.to_string() == "syrette::named"
        });

        let opt_named_attr_tokens = opt_named_attr.map(|attr| &attr.tokens);

        let opt_named_attr_input =
            if let Some(named_attr_tokens) = opt_named_attr_tokens {
                Some(parse2::<NamedAttrInput>(named_attr_tokens.clone()).map_err(
                    |err| DependencyError::InvalidNamedAttrInput {
                        arg_span: typed_new_method_arg.span(),
                        err,
                    },
                )?)
            } else {
                None
            };

        Ok(Self {
            interface,
            ptr: ptr_ident,
            name: opt_named_attr_input.map(|named_attr_input| named_attr_input.name),
        })
    }

    fn get_interface(&self) -> &Type
    {
        &self.interface
    }

    fn get_ptr(&self) -> &Ident
    {
        &self.ptr
    }

    fn get_name(&self) -> &Option<LitStr>
    {
        &self.name
    }
}

diagnostic_error_enum! {
pub enum DependencyError
{
    #[error("Unexpected 'self' parameter"), span = self_token_span]
    #[help("Remove the 'self' parameter"), span = self_token_span]
    UnexpectedSelf {
        self_token_span: Span
    },

    #[
        error("Dependency type must either be a path or a path reference"),
        span = type_span
    ]
    InvalidType {
        type_span: Span
    },

    #[error("Dependency is missing a type"), span = arg_span]
    MissingType {
        arg_span: Span
    },

    #[
        error("Expected dependency type to take generic parameters"),
        span = ptr_ident_span
    ]
    DependencyTypeMissingGenerics {
        ptr_ident_span: Span
    },

    #[error("Dependency has a 'named' attribute given invalid input"), span = arg_span]
    #[source(err)]
    InvalidNamedAttrInput {
        arg_span: Span,
        err: syn::Error
    },
}
}

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

    use proc_macro::TokenStream;
    use proc_macro2::Span;
    use quote::{format_ident, quote};
    use syn::punctuated::Punctuated;
    use syn::token::{And, Bang, Bracket, Colon, Paren, Pound, SelfValue};
    use syn::{
        AttrStyle,
        Attribute,
        Pat,
        PatType,
        PathSegment,
        Receiver,
        TypeNever,
        TypeReference,
        TypeTuple,
    };

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

    #[test]
    fn can_build_dependency()
    {
        assert!(matches!(
            Dependency::build(&FnArg::Typed(PatType {
                attrs: vec![],
                pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
                colon_token: Colon::default(),
                ty: Box::new(test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(
                        format_ident!("TransientPtr"),
                        &[test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(format_ident!("Foo"), &[])
                        ]))]
                    ),
                ])))
            })),
            Ok(dependency) if dependency == Dependency {
                interface: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Foo"))
                ])),
                ptr: format_ident!("TransientPtr"),
                name: None
            }
        ));

        assert!(matches!(
            Dependency::build(&FnArg::Typed(PatType {
                attrs: vec![],
                pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
                colon_token: Colon::default(),
                ty: Box::new(test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("syrette"), &[]),
                    test_utils::create_path_segment(format_ident!("ptr"), &[]),
                    test_utils::create_path_segment(
                        format_ident!("SingletonPtr"),
                        &[test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(format_ident!("Bar"), &[])
                        ]))]
                    ),
                ])))
            })),
            Ok(dependency) if dependency == Dependency {
                interface: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Bar"))
                ])),
                ptr: format_ident!("SingletonPtr"),
                name: None
            }
        ));
    }

    #[test]
    fn can_build_dependency_with_name()
    {
        assert!(matches!(
            Dependency::build(&FnArg::Typed(PatType {
                attrs: vec![Attribute {
                    pound_token: Pound::default(),
                    style: AttrStyle::Outer,
                    bracket_token: Bracket::default(),
                    path: test_utils::create_path(&[test_utils::create_path_segment(
                        format_ident!("named"),
                        &[]
                    )]),
                    tokens: quote! { ("cool") }
                }],
                pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
                colon_token: Colon::default(),
                ty: Box::new(test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(
                        format_ident!("TransientPtr"),
                        &[test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(format_ident!("Foo"), &[])
                        ]))]
                    ),
                ])))
            })),
            Ok(dependency) if dependency == Dependency {
                interface: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Foo"))
                ])),
                ptr: format_ident!("TransientPtr"),
                name: Some(LitStr::new("cool", Span::call_site()))
            }
        ));

        assert!(matches!(
            Dependency::build(&FnArg::Typed(PatType {
                attrs: vec![Attribute {
                    pound_token: Pound::default(),
                    style: AttrStyle::Outer,
                    bracket_token: Bracket::default(),
                    path: test_utils::create_path(&[test_utils::create_path_segment(
                        format_ident!("named"),
                        &[]
                    )]),
                    tokens: quote! { ("awesome") }
                }],
                pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
                colon_token: Colon::default(),
                ty: Box::new(test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("syrette"), &[]),
                    test_utils::create_path_segment(format_ident!("ptr"), &[]),
                    test_utils::create_path_segment(
                        format_ident!("FactoryPtr"),
                        &[test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(format_ident!("Bar"), &[])
                        ]))]
                    ),
                ])))
            })),
            Ok(dependency) if dependency == Dependency {
                interface: test_utils::create_type(test_utils::create_path(&[
                    PathSegment::from(format_ident!("Bar"))
                ])),
                ptr: format_ident!("FactoryPtr"),
                name: Some(LitStr::new("awesome", Span::call_site()))
            }
        ));
    }

    #[test]
    fn cannot_build_dependency_with_receiver_arg()
    {
        assert!(Dependency::build(&FnArg::Receiver(Receiver {
            attrs: vec![],
            reference: None,
            mutability: None,
            self_token: SelfValue::default()
        }))
        .is_err());
    }

    #[test]
    fn cannot_build_dependency_with_type_not_path()
    {
        assert!(Dependency::build(&FnArg::Typed(PatType {
            attrs: vec![],
            pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
            colon_token: Colon::default(),
            ty: Box::new(Type::Tuple(TypeTuple {
                paren_token: Paren::default(),
                elems: Punctuated::from_iter(vec![test_utils::create_type(
                    test_utils::create_path(&[test_utils::create_path_segment(
                        format_ident!("EvilType"),
                        &[]
                    )])
                )])
            }))
        }))
        .is_err());

        assert!(Dependency::build(&FnArg::Typed(PatType {
            attrs: vec![],
            pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
            colon_token: Colon::default(),
            ty: Box::new(Type::Reference(TypeReference {
                and_token: And::default(),
                lifetime: None,
                mutability: None,
                elem: Box::new(Type::Never(TypeNever {
                    bang_token: Bang::default()
                }))
            }))
        }))
        .is_err());
    }

    #[test]
    fn cannot_build_dependency_without_generics_args()
    {
        assert!(Dependency::build(&FnArg::Typed(PatType {
            attrs: vec![],
            pat: Box::new(Pat::Verbatim(TokenStream::default().into())),
            colon_token: Colon::default(),
            ty: Box::new(test_utils::create_type(test_utils::create_path(&[
                test_utils::create_path_segment(format_ident!("TransientPtr"), &[]),
            ])))
        }))
        .is_err());
    }
}