aboutsummaryrefslogtreecommitdiff
path: root/macros/src/injectable/implementation.rs
blob: 935a8ae8fd96803456b371b005be7b93cc75b9ce (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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
use std::error::Error;

use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::spanned::Spanned;
use syn::{
    parse2,
    parse_str,
    ExprMethodCall,
    FnArg,
    Generics,
    ImplItemMethod,
    ItemImpl,
    ReturnType,
    Type,
};

use crate::injectable::dependency::{DependencyError, IDependency};
use crate::util::error::diagnostic_error_enum;
use crate::util::item_impl::find_impl_method_by_name_mut;
use crate::util::string::camelcase_to_snakecase;
use crate::util::syn_path::SynPathExt;

const DI_CONTAINER_VAR_NAME: &str = "di_container";
const DEPENDENCY_HISTORY_VAR_NAME: &str = "dependency_history";

pub struct InjectableImpl<Dep: IDependency>
{
    pub dependencies: Vec<Dep>,
    pub self_type: Type,
    pub generics: Generics,
    pub original_impl: ItemImpl,

    constructor_method: ImplItemMethod,
}

impl<Dep: IDependency> InjectableImpl<Dep>
{
    #[cfg(not(tarpaulin_include))]
    pub fn parse(
        input: TokenStream,
        constructor: &Ident,
    ) -> Result<Self, InjectableImplError>
    {
        let mut item_impl = parse2::<ItemImpl>(input).map_err(|err| {
            InjectableImplError::NotAImplementation {
                err_span: err.span(),
            }
        })?;

        if let Some((_, trait_path, _)) = item_impl.trait_ {
            return Err(InjectableImplError::TraitImpl {
                trait_path_span: trait_path.span(),
            });
        }

        let item_impl_span = item_impl.self_ty.span();

        let constructor_method =
            find_impl_method_by_name_mut(&mut item_impl, constructor).ok_or(
                InjectableImplError::MissingConstructorMethod {
                    constructor: constructor.clone(),
                    implementation_span: item_impl_span,
                },
            )?;

        let dependencies =
            Self::build_dependencies(constructor_method).map_err(|err| {
                InjectableImplError::ContainsAInvalidDependency {
                    implementation_span: item_impl_span,
                    err,
                }
            })?;

        Self::remove_method_argument_attrs(constructor_method);

        let constructor_method = constructor_method.clone();

        Ok(Self {
            dependencies,
            self_type: item_impl.self_ty.as_ref().clone(),
            generics: item_impl.generics.clone(),
            original_impl: item_impl,
            constructor_method,
        })
    }

    pub fn validate(&self) -> Result<(), InjectableImplError>
    {
        if matches!(self.constructor_method.sig.output, ReturnType::Default) {
            return Err(InjectableImplError::InvalidConstructorMethodReturnType {
                ctor_method_output_span: self.constructor_method.sig.output.span(),
                expected: "Self".to_string(),
                found: "()".to_string(),
            });
        }

        if let ReturnType::Type(_, ret_type) = &self.constructor_method.sig.output {
            if let Type::Path(path_type) = ret_type.as_ref() {
                if path_type
                    .path
                    .get_ident()
                    .map_or_else(|| true, |ident| *ident != "Self")
                {
                    return Err(
                        InjectableImplError::InvalidConstructorMethodReturnType {
                            ctor_method_output_span: self
                                .constructor_method
                                .sig
                                .output
                                .span(),
                            expected: "Self".to_string(),
                            found: ret_type.to_token_stream().to_string(),
                        },
                    );
                }
            } else {
                return Err(InjectableImplError::InvalidConstructorMethodReturnType {
                    ctor_method_output_span: self.constructor_method.sig.output.span(),
                    expected: "Self".to_string(),
                    found: ret_type.to_token_stream().to_string(),
                });
            }
        }

        if let Some(unsafety) = self.constructor_method.sig.unsafety {
            return Err(InjectableImplError::ConstructorMethodUnsafe {
                unsafety_span: unsafety.span,
            });
        }

        if let Some(asyncness) = self.constructor_method.sig.asyncness {
            return Err(InjectableImplError::ConstructorMethodAsync {
                asyncness_span: asyncness.span,
            });
        }

        if !self.constructor_method.sig.generics.params.is_empty() {
            return Err(InjectableImplError::ConstructorMethodGeneric {
                generics_span: self.constructor_method.sig.generics.span(),
            });
        }
        Ok(())
    }

    #[cfg(not(tarpaulin_include))]
    pub fn expand(&self, no_doc_hidden: bool, is_async: bool)
        -> proc_macro2::TokenStream
    {
        let di_container_var = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dependency_history_var = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        let maybe_doc_hidden = if no_doc_hidden {
            quote! {}
        } else {
            quote! { #[doc(hidden)] }
        };

        let maybe_prevent_circular_deps = if cfg!(feature = "prevent-circular") {
            Self::expand_prevent_circular_deps(&dependency_history_var)
        } else {
            quote! {}
        };

        let injectable_impl = if is_async {
            self.expand_async_impl(
                &maybe_doc_hidden,
                &di_container_var,
                &dependency_history_var,
                &maybe_prevent_circular_deps,
                &Self::create_get_dep_method_calls(&self.dependencies, true).unwrap(),
            )
        } else {
            self.expand_blocking_impl(
                &maybe_doc_hidden,
                &di_container_var,
                &dependency_history_var,
                &maybe_prevent_circular_deps,
                &Self::create_get_dep_method_calls(&self.dependencies, false).unwrap(),
            )
        };

        let original_impl = &self.original_impl;

        quote! {
            #original_impl

            #injectable_impl
        }
    }

    #[cfg(not(tarpaulin_include))]
    fn expand_prevent_circular_deps(
        dependency_history_var: &Ident,
    ) -> proc_macro2::TokenStream
    {
        quote! {
            if #dependency_history_var.contains::<Self>() {
                #dependency_history_var.push::<Self>();

                return Err(InjectableError::DetectedCircular {
                    dependency_history: #dependency_history_var
                });
            }

            #dependency_history_var.push::<Self>();
        }
    }

    #[cfg(not(tarpaulin_include))]
    fn expand_async_impl(
        &self,
        maybe_doc_hidden: &proc_macro2::TokenStream,
        di_container_var: &Ident,
        dependency_history_var: &Ident,
        maybe_prevent_circular_deps: &proc_macro2::TokenStream,
        get_dep_method_calls: &Vec<proc_macro2::TokenStream>,
    ) -> proc_macro2::TokenStream
    {
        let generics = &self.generics;
        let self_type = &self.self_type;
        let constructor = &self.constructor_method.sig.ident;

        let dependency_idents = (0..get_dep_method_calls.len())
            .map(|index| format_ident!("dependency_{index}"))
            .collect::<Vec<_>>();

        quote! {
            #maybe_doc_hidden
            impl #generics syrette::interfaces::async_injectable::AsyncInjectable<
                syrette::di_container::asynchronous::AsyncDIContainer,
            > for #self_type
            {
                fn resolve<'di_container, 'fut>(
                    #di_container_var: &'di_container std::sync::Arc<
                        syrette::di_container::asynchronous::AsyncDIContainer
                    >,
                    mut #dependency_history_var: syrette::dependency_history::DependencyHistory
                ) -> syrette::future::BoxFuture<
                    'fut,
                    Result<
                        syrette::ptr::TransientPtr<Self>,
                        syrette::errors::injectable::InjectableError
                    >
                >
                where
                    Self: Sized + 'fut,
                    'di_container: 'fut
                {
                    Box::pin(async move {
                        use std::any::type_name;

                        use syrette::errors::injectable::InjectableError;

                        let self_type_name = type_name::<#self_type>();

                        #maybe_prevent_circular_deps

                        // Dependencies can't be passed directly to the constructor
                        // because the Rust compiler becomes sad about SomePtr having
                        // a variant with a Rc inside of it and .await being called even
                        // when the Rc variant isn't even being created
                        #(let #dependency_idents = #get_dep_method_calls;)*

                        Ok(syrette::ptr::TransientPtr::new(Self::#constructor(
                            #(#dependency_idents),*
                        )))
                    })
                }
            }
        }
    }

    #[cfg(not(tarpaulin_include))]
    fn expand_blocking_impl(
        &self,
        maybe_doc_hidden: &proc_macro2::TokenStream,
        di_container_var: &Ident,
        dependency_history_var: &Ident,
        maybe_prevent_circular_deps: &proc_macro2::TokenStream,
        get_dep_method_calls: &Vec<proc_macro2::TokenStream>,
    ) -> proc_macro2::TokenStream
    {
        let generics = &self.generics;
        let self_type = &self.self_type;
        let constructor = &self.constructor_method.sig.ident;

        quote! {
            #maybe_doc_hidden
            impl #generics syrette::interfaces::injectable::Injectable<
                ::syrette::di_container::blocking::DIContainer
            > for #self_type
            {
                fn resolve(
                    #di_container_var: &std::rc::Rc<
                        syrette::di_container::blocking::DIContainer
                    >,
                    mut #dependency_history_var: syrette::dependency_history::DependencyHistory
                ) -> Result<
                    syrette::ptr::TransientPtr<Self>,
                    syrette::errors::injectable::InjectableError>
                {
                    use std::any::type_name;

                    use syrette::errors::injectable::InjectableError;

                    let self_type_name = type_name::<#self_type>();

                    #maybe_prevent_circular_deps

                    return Ok(syrette::ptr::TransientPtr::new(Self::#constructor(
                        #(#get_dep_method_calls),*
                    )));
                }
            }
        }
    }

    #[cfg(not(tarpaulin_include))]
    pub fn expand_dummy_blocking_impl(&self) -> proc_macro2::TokenStream
    {
        let generics = &self.generics;
        let self_type = &self.self_type;

        let di_container_var = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dependency_history_var = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        quote! {
            impl #generics syrette::interfaces::injectable::Injectable<
                syrette::di_container::blocking::DIContainer,
                syrette::dependency_history::DependencyHistory
            > for #self_type
            {
                fn resolve(
                    #di_container_var: &std::rc::Rc<
                        syrette::di_container::blocking::DIContainer
                    >,
                    mut #dependency_history_var: syrette::dependency_history::DependencyHistory
                ) -> Result<
                    syrette::ptr::TransientPtr<Self>,
                    syrette::errors::injectable::InjectableError>
                {
                    unimplemented!();
                }
            }
        }
    }

    #[cfg(not(tarpaulin_include))]
    pub fn expand_dummy_async_impl(&self) -> proc_macro2::TokenStream
    {
        let generics = &self.generics;
        let self_type = &self.self_type;

        let di_container_var = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dependency_history_var = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        quote! {
            impl #generics syrette::interfaces::async_injectable::AsyncInjectable<
                syrette::di_container::asynchronous::AsyncDIContainer,
                syrette::dependency_history::DependencyHistory
            > for #self_type
            {
                fn resolve<'di_container, 'fut>(
                    #di_container_var: &'di_container std::sync::Arc<
                        syrette::di_container::asynchronous::AsyncDIContainer
                    >,
                    mut #dependency_history_var: syrette::dependency_history::DependencyHistory
                ) -> syrette::future::BoxFuture<
                    'fut,
                    Result<
                        syrette::ptr::TransientPtr<Self>,
                        syrette::errors::injectable::InjectableError
                    >
                >
                where
                    Self: Sized + 'fut,
                    'di_container: 'fut
                {
                    unimplemented!();
                }
            }
        }
    }

    fn create_get_dep_method_calls(
        dependencies: &[Dep],
        is_async: bool,
    ) -> Result<Vec<proc_macro2::TokenStream>, Box<dyn Error>>
    {
        dependencies
            .iter()
            .filter_map(|dependency| {
                match dependency.get_interface() {
                    Type::TraitObject(_) | Type::Path(_) => Some(()),
                    _ => None,
                }?;

                Some(Self::create_single_get_dep_method_call(
                    dependency, is_async,
                ))
            })
            .collect()
    }

    fn create_single_get_dep_method_call(
        dependency: &Dep,
        is_async: bool,
    ) -> Result<proc_macro2::TokenStream, Box<dyn Error>>
    {
        let dep_interface_str = match &dependency.get_interface() {
            Type::TraitObject(interface_trait) => {
                Ok(interface_trait.to_token_stream().to_string())
            }
            Type::Path(path_interface) => Ok(path_interface.path.to_string()),
            &_ => Err("Invalid type. Expected trait type or path type"),
        }?;

        let method_call = parse_str::<ExprMethodCall>(
            format!(
                concat!(
                    "{}.get_bound::<{}>({}.clone(), ",
                    "syrette::di_container::BindingOptions::new(){})"
                ),
                DI_CONTAINER_VAR_NAME,
                dep_interface_str,
                DEPENDENCY_HISTORY_VAR_NAME,
                dependency
                    .get_name()
                    .as_ref()
                    .map(|name| format!(".name(\"{}\")", name.value()))
                    .unwrap_or_default()
            )
            .as_str(),
        )?;

        let ptr_name = dependency.get_ptr().to_string();

        let to_ptr =
            format_ident!("{}", camelcase_to_snakecase(&ptr_name.replace("Ptr", "")));

        let do_method_call = if is_async {
            quote! { #method_call.await }
        } else {
            quote! { #method_call }
        };

        let resolve_failed_error = if is_async {
            quote! { InjectableError::AsyncResolveFailed }
        } else {
            quote! { InjectableError::ResolveFailed }
        };

        Ok(quote! {
            #do_method_call
                .map_err(|err| #resolve_failed_error {
                    reason: Box::new(err),
                    affected: self_type_name
                })?
                .#to_ptr()
                .map_err(|err| InjectableError:: PrepareDependencyFailed {
                    reason: err,
                    dependency_name: #dep_interface_str
                })?
        })
    }

    fn build_dependencies(
        ctor_method: &ImplItemMethod,
    ) -> Result<Vec<Dep>, DependencyError>
    {
        let ctor_method_args = &ctor_method.sig.inputs;

        let dependencies_result: Result<Vec<_>, _> =
            ctor_method_args.iter().map(Dep::build).collect();

        let deps = dependencies_result?;

        Ok(deps)
    }

    // Removes argument attributes from a method, as they are not actually valid Rust.
    // Not doing this would cause a compilation error.
    fn remove_method_argument_attrs(method: &mut ImplItemMethod)
    {
        let method_args = &mut method.sig.inputs;

        for arg in method_args {
            let typed_arg = if let FnArg::Typed(typed_arg) = arg {
                typed_arg
            } else {
                continue;
            };

            let attrs_to_remove: Vec<_> = typed_arg
                .attrs
                .iter()
                .enumerate()
                .filter_map(|(index, attr)| {
                    if &attr.path.to_string() == "syrette::named" {
                        return Some(index);
                    }

                    if attr.path.get_ident()?.to_string().as_str() == "named" {
                        return Some(index);
                    }

                    None
                })
                .collect();

            for attr_index in attrs_to_remove {
                typed_arg.attrs.remove(attr_index);
            }
        }
    }
}

diagnostic_error_enum! {
pub enum InjectableImplError
{
    #[
        error("The 'injectable' attribute must be placed on a implementation"),
        span = err_span
    ]
    NotAImplementation
    {
        err_span: Span
    },

    #[
        error("The 'injectable' attribute cannot be placed on a trait implementation"),
        span = trait_path_span
    ]
    TraitImpl
    {
        trait_path_span: Span
    },

    #[
        error("No constructor method '{constructor}' found in impl"),
        span = implementation_span
    ]
    #[note("Required by the 'injectable' attribute macro")]
    MissingConstructorMethod {
        constructor: Ident,
        implementation_span: Span
    },

    #[
        error(concat!(
            "Invalid constructor method return type. Expected it to be '{}'. ",
            "Found '{}'"
        ), expected, found),
        span = ctor_method_output_span
    ]
    InvalidConstructorMethodReturnType
    {
        ctor_method_output_span: Span,
        expected: String,
        found: String
    },

    #[error("Constructor method is not allowed to be unsafe"), span = unsafety_span]
    #[note("Required by the 'injectable' attribute macro")]
    ConstructorMethodUnsafe {
        unsafety_span: Span
    },

    #[error("Constructor method is not allowed to be async"), span = asyncness_span]
    #[note("Required by the 'injectable' attribute macro")]
    ConstructorMethodAsync {
        asyncness_span: Span
    },

    #[error("Constructor method is not allowed to have generics"), span = generics_span]
    #[note("Required by the 'injectable' attribute macro")]
    ConstructorMethodGeneric {
        generics_span: Span
    },

    #[error("Has a invalid dependency"), span = implementation_span]
    #[source(err)]
    ContainsAInvalidDependency {
        implementation_span: Span,
        err: DependencyError
    },
}
}

#[cfg(test)]
mod tests
{
    use std::sync::{Mutex, MutexGuard};

    use once_cell::sync::Lazy;
    use pretty_assertions::assert_eq;
    use proc_macro2::{Span, TokenStream};
    use syn::token::{Brace, Bracket, Colon, Paren, Pound};
    use syn::{
        parse2,
        AttrStyle,
        Attribute,
        Block,
        Expr,
        ImplItemMethod,
        LitStr,
        Pat,
        PatType,
        Visibility,
    };

    use super::*;
    use crate::injectable::dependency::MockIDependency;
    use crate::injectable::named_attr_input::NamedAttrInput;
    use crate::test_utils;

    static TEST_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    // When a test panics, it will poison the Mutex. Since we don't actually
    // care about the state of the data we ignore that it is poisoned and grab
    // the lock regardless.  If you just do `let _lock = &TEST_MUTEX.lock().unwrap()`, one
    // test panicking will cause all other tests that try and acquire a lock on
    // that Mutex to also panic.
    fn get_lock(m: &'static Mutex<()>) -> MutexGuard<'static, ()>
    {
        match m.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    #[test]
    fn can_build_dependencies()
    {
        let method = ImplItemMethod {
            attrs: vec![],
            vis: Visibility::Inherited,
            defaultness: None,
            sig: test_utils::create_signature(
                format_ident!("new"),
                vec![
                    (
                        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"),
                                        &[],
                                    ),
                                ]))],
                            ),
                        ])),
                        vec![],
                    ),
                    (
                        test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(
                                format_ident!("FactoryPtr"),
                                &[test_utils::create_type(test_utils::create_path(&[
                                    test_utils::create_path_segment(
                                        format_ident!("BarFactory"),
                                        &[],
                                    ),
                                ]))],
                            ),
                        ])),
                        vec![],
                    ),
                ],
                test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("Self"), &[]),
                ])),
            ),
            block: Block {
                brace_token: Brace::default(),
                stmts: vec![],
            },
        };

        let _lock = get_lock(&TEST_MUTEX);

        let build_context = MockIDependency::build_context();

        build_context
            .expect()
            .returning(|_| Ok(MockIDependency::new()));

        let dependencies = InjectableImpl::<MockIDependency>::build_dependencies(&method)
            .expect("Expected Ok");

        assert_eq!(dependencies.len(), 2);
    }

    #[test]
    fn can_build_named_dependencies()
    {
        let method = ImplItemMethod {
            attrs: vec![],
            vis: Visibility::Inherited,
            defaultness: None,
            sig: test_utils::create_signature(
                format_ident!("new"),
                vec![
                    (
                        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"),
                                        &[],
                                    ),
                                ]))],
                            ),
                        ])),
                        vec![],
                    ),
                    (
                        test_utils::create_type(test_utils::create_path(&[
                            test_utils::create_path_segment(
                                format_ident!("FactoryPtr"),
                                &[test_utils::create_type(test_utils::create_path(&[
                                    test_utils::create_path_segment(
                                        format_ident!("BarFactory"),
                                        &[],
                                    ),
                                ]))],
                            ),
                        ])),
                        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: NamedAttrInput {
                                paren: Paren::default(),
                                name: LitStr::new("awesome", Span::call_site()),
                            }
                            .to_token_stream(),
                        }],
                    ),
                ],
                test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("Self"), &[]),
                ])),
            ),
            block: Block {
                brace_token: Brace::default(),
                stmts: vec![],
            },
        };

        let _lock = get_lock(&TEST_MUTEX);

        let build_context = MockIDependency::build_context();

        build_context
            .expect()
            .returning(|_| Ok(MockIDependency::new()))
            .times(2);

        let dependencies = InjectableImpl::<MockIDependency>::build_dependencies(&method)
            .expect("Expected Ok");

        assert_eq!(dependencies.len(), 2);
    }

    #[test]
    fn can_remove_method_argument_attrs()
    {
        let first_arg_type = 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"), &[]),
                ]))],
            ),
        ]));

        let second_arg_type = test_utils::create_type(test_utils::create_path(&[
            test_utils::create_path_segment(
                format_ident!("FactoryPtr"),
                &[test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("BarFactory"), &[]),
                ]))],
            ),
        ]));

        let mut method = ImplItemMethod {
            attrs: vec![],
            vis: Visibility::Inherited,
            defaultness: None,
            sig: test_utils::create_signature(
                format_ident!("new"),
                vec![
                    (
                        first_arg_type.clone(),
                        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: NamedAttrInput {
                                paren: Paren::default(),
                                name: LitStr::new("cool", Span::call_site()),
                            }
                            .to_token_stream(),
                        }],
                    ),
                    (
                        second_arg_type.clone(),
                        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: NamedAttrInput {
                                paren: Paren::default(),
                                name: LitStr::new("awesome", Span::call_site()),
                            }
                            .to_token_stream(),
                        }],
                    ),
                ],
                test_utils::create_type(test_utils::create_path(&[
                    test_utils::create_path_segment(format_ident!("Self"), &[]),
                ])),
            ),
            block: Block {
                brace_token: Brace::default(),
                stmts: vec![],
            },
        };

        InjectableImpl::<MockIDependency>::remove_method_argument_attrs(&mut method);

        assert_eq!(
            method.sig.inputs.first().unwrap().clone(),
            FnArg::Typed(PatType {
                attrs: vec![],
                pat: Box::new(Pat::Verbatim(TokenStream::new())),
                colon_token: Colon::default(),
                ty: Box::new(first_arg_type),
            })
        );

        assert_eq!(
            method.sig.inputs.last().unwrap().clone(),
            FnArg::Typed(PatType {
                attrs: vec![],
                pat: Box::new(Pat::Verbatim(TokenStream::new())),
                colon_token: Colon::default(),
                ty: Box::new(second_arg_type),
            })
        );
    }

    #[test]
    fn can_create_single_get_dep_method_call() -> Result<(), Box<dyn Error>>
    {
        let mut mock_dependency = MockIDependency::new();

        mock_dependency
            .expect_get_interface()
            .return_const(test_utils::create_type(test_utils::create_path(&[
                test_utils::create_path_segment(format_ident!("Foo"), &[]),
            ])));

        mock_dependency.expect_get_name().return_const(None);

        mock_dependency
            .expect_get_ptr()
            .return_const(format_ident!("TransientPtr"));

        let di_container_var_ident = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dep_history_var_ident = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        let output =
            InjectableImpl::<MockIDependency>::create_single_get_dep_method_call(
                &mock_dependency,
                false,
            )?;

        assert_eq!(
            parse2::<Expr>(output)?,
            parse2::<Expr>(quote! {
                #di_container_var_ident
                    .get_bound::<Foo>(
                        #dep_history_var_ident.clone(),
                        syrette::di_container::BindingOptions::new()
                    )
                    .map_err(|err| InjectableError::ResolveFailed {
                        reason: Box::new(err),
                        affected: self_type_name
                    })?
                    .transient()
                    .map_err(|err| InjectableError::PrepareDependencyFailed {
                        reason: err,
                        dependency_name: "Foo"
                    })?
            })?
        );

        Ok(())
    }

    #[test]
    fn can_create_single_get_dep_method_call_with_name() -> Result<(), Box<dyn Error>>
    {
        let mut mock_dependency = MockIDependency::new();

        mock_dependency
            .expect_get_interface()
            .return_const(test_utils::create_type(test_utils::create_path(&[
                test_utils::create_path_segment(format_ident!("Foo"), &[]),
            ])));

        mock_dependency
            .expect_get_name()
            .return_const(Some(LitStr::new("special", Span::call_site())));

        mock_dependency
            .expect_get_ptr()
            .return_const(format_ident!("TransientPtr"));

        let di_container_var_ident = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dep_history_var_ident = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        let output =
            InjectableImpl::<MockIDependency>::create_single_get_dep_method_call(
                &mock_dependency,
                false,
            )?;

        assert_eq!(
            parse2::<Expr>(output)?,
            parse2::<Expr>(quote! {
                #di_container_var_ident
                    .get_bound::<Foo>(
                        #dep_history_var_ident.clone(),
                        syrette::di_container::BindingOptions::new().name("special")
                    )
                    .map_err(|err| InjectableError::ResolveFailed {
                        reason: Box::new(err),
                        affected: self_type_name
                    })?
                    .transient()
                    .map_err(|err| InjectableError::PrepareDependencyFailed {
                        reason: err,
                        dependency_name: "Foo"
                    })?
            })?
        );

        Ok(())
    }

    #[test]
    fn can_create_single_get_dep_method_call_async() -> Result<(), Box<dyn Error>>
    {
        let mut mock_dependency = MockIDependency::new();

        mock_dependency
            .expect_get_interface()
            .return_const(test_utils::create_type(test_utils::create_path(&[
                test_utils::create_path_segment(format_ident!("Foo"), &[]),
            ])));

        mock_dependency.expect_get_name().return_const(None);

        mock_dependency
            .expect_get_ptr()
            .return_const(format_ident!("TransientPtr"));

        let di_container_var_ident = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dep_history_var_ident = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        let output =
            InjectableImpl::<MockIDependency>::create_single_get_dep_method_call(
                &mock_dependency,
                true,
            )?;

        assert_eq!(
            parse2::<Expr>(output)?,
            parse2::<Expr>(quote! {
                #di_container_var_ident
                    .get_bound::<Foo>(
                        #dep_history_var_ident.clone(),
                        syrette::di_container::BindingOptions::new()
                    )
                    .await
                    .map_err(|err| InjectableError::AsyncResolveFailed {
                        reason: Box::new(err),
                        affected: self_type_name
                    })?
                    .transient()
                    .map_err(|err| InjectableError::PrepareDependencyFailed {
                        reason: err,
                        dependency_name: "Foo"
                    })?
            })?
        );

        Ok(())
    }

    #[test]
    fn can_create_single_get_dep_method_call_async_with_name(
    ) -> Result<(), Box<dyn Error>>
    {
        let mut mock_dependency = MockIDependency::new();

        mock_dependency
            .expect_get_interface()
            .return_const(test_utils::create_type(test_utils::create_path(&[
                test_utils::create_path_segment(format_ident!("Foo"), &[]),
            ])));

        mock_dependency
            .expect_get_name()
            .return_const(Some(LitStr::new("foobar", Span::call_site())));

        mock_dependency
            .expect_get_ptr()
            .return_const(format_ident!("TransientPtr"));

        let di_container_var_ident = format_ident!("{}", DI_CONTAINER_VAR_NAME);
        let dep_history_var_ident = format_ident!("{}", DEPENDENCY_HISTORY_VAR_NAME);

        let output =
            InjectableImpl::<MockIDependency>::create_single_get_dep_method_call(
                &mock_dependency,
                true,
            )?;

        assert_eq!(
            parse2::<Expr>(output)?,
            parse2::<Expr>(quote! {
                #di_container_var_ident
                    .get_bound::<Foo>(
                        #dep_history_var_ident.clone(),
                        syrette::di_container::BindingOptions::new().name("foobar")
                    )
                    .await
                    .map_err(|err| InjectableError::AsyncResolveFailed {
                        reason: Box::new(err),
                        affected: self_type_name
                    })?
                    .transient()
                    .map_err(|err| InjectableError::PrepareDependencyFailed {
                        reason: err,
                        dependency_name: "Foo"
                    })?
            })?
        );

        Ok(())
    }
}