auto-di-macros 0.2.0

Procedural macros for the auto-di dependency injection crate
Documentation
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
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    FnArg, GenericArgument, ImplItem, ImplItemFn, Item, ItemFn, ItemImpl, ItemStruct, LitStr, Pat,
    PathArguments, ReturnType, Signature, Type, parse_macro_input,
};

#[derive(Default, Clone)]
struct ProviderOptions {
    name: Option<String>,
    primary: bool,
    scope: Option<String>,
    eager: bool,
    profile: Option<String>,
    condition_key: Option<String>,
    condition_value: Option<String>,
    post_construct: Option<String>,
    pre_destroy: Option<String>,
}

/// Registers a lazily constructed singleton dependency.
///
/// It can be placed on either a free provider function or an inherent `impl`
/// containing a `new` constructor. Constructors may be synchronous or async.
/// Every injected parameter must have the form `name: Arc<Dependency>`.
pub(crate) fn singleton(attribute: TokenStream, item: TokenStream) -> TokenStream {
    let options = match parse_provider_options(attribute) {
        Ok(options) => options,
        Err(error) => return error.to_compile_error().into(),
    };
    let item = parse_macro_input!(item as Item);

    let expanded = match item {
        Item::Fn(function) => expand_function(function, &options),
        Item::Impl(item_impl) => expand_impl(item_impl, &options),
        other => Err(syn::Error::new_spanned(
            other,
            "#[singleton] can only be used on a function or an inherent impl block",
        )),
    };

    match expanded {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

fn parse_provider_options(attribute: TokenStream) -> syn::Result<ProviderOptions> {
    parse_provider_options2(attribute.into())
}

fn parse_provider_options2(attribute: proc_macro2::TokenStream) -> syn::Result<ProviderOptions> {
    use syn::parse::Parser;
    let mut options = ProviderOptions::default();
    let parser = syn::meta::parser(|meta| {
        if meta.path.is_ident("primary") {
            options.primary = true;
            return Ok(());
        }
        if meta.path.is_ident("eager") {
            options.eager = true;
            return Ok(());
        }
        let value = meta.value()?.parse::<LitStr>()?.value();
        if meta.path.is_ident("name") {
            options.name = Some(value);
        } else if meta.path.is_ident("scope") {
            options.scope = Some(value);
        } else if meta.path.is_ident("profile") {
            options.profile = Some(value);
        } else if meta.path.is_ident("condition") {
            let (key, expected) = value
                .split_once('=')
                .map_or((value.as_str(), None), |(k, v)| (k, Some(v)));
            options.condition_key = Some(key.to_owned());
            options.condition_value = expected.map(str::to_owned);
        } else if meta.path.is_ident("post_construct") {
            options.post_construct = Some(value);
        } else if meta.path.is_ident("pre_destroy") {
            options.pre_destroy = Some(value);
        } else {
            return Err(meta.error("unknown provider option"));
        }
        Ok(())
    });
    parser.parse2(attribute)?;
    if let Some(scope) = &options.scope {
        if !matches!(scope.as_str(), "singleton" | "prototype" | "request") {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "scope must be singleton, prototype, or request",
            ));
        }
    }
    Ok(options)
}

/// Marker consumed from constructor parameters by the surrounding provider macro.
pub(crate) fn qualifier(_attribute: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Boots the global context, creates eager providers, and runs shutdown hooks.
pub(crate) fn application(_attribute: TokenStream, item: TokenStream) -> TokenStream {
    let mut function = parse_macro_input!(item as ItemFn);
    if function.sig.asyncness.is_none() {
        return syn::Error::new_spanned(&function.sig, "#[application] requires async fn")
            .to_compile_error()
            .into();
    }
    let body = function.block;
    function
        .attrs
        .push(syn::parse_quote!(#[::auto_di::__private::tokio::main]));
    function.block = Box::new(syn::parse_quote!({
        let __container = ::auto_di::global_container()?;
        __container.initialize_eager().await?;
        let __result = (async move #body).await;
        __container.shutdown().await?;
        __result
    }));
    quote!(#function).into()
}

/// Generates environment binding and registers the resulting struct as a provider.
pub(crate) fn configuration_properties(attribute: TokenStream, item: TokenStream) -> TokenStream {
    let prefix = parse_macro_input!(attribute as LitStr).value();
    let structure = parse_macro_input!(item as ItemStruct);
    match expand_configuration_properties(prefix, structure) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

fn expand_configuration_properties(
    prefix: String,
    structure: ItemStruct,
) -> syn::Result<proc_macro2::TokenStream> {
    let ident = &structure.ident;
    let fields = match &structure.fields {
        syn::Fields::Named(fields) => &fields.named,
        _ => {
            return Err(syn::Error::new_spanned(
                &structure,
                "configuration properties require named fields",
            ));
        }
    };
    let bindings = fields.iter().map(|field| {
        let name = field.ident.as_ref().expect("named field");
        let ty = &field.ty;
        let key = format!("{}_{}", prefix, name).replace(['.', '-'], "_").to_uppercase();
        quote! {
            #name: ::std::env::var(#key)
                .map_err(|error| ::auto_di::DiError::Configuration { key: #key.into(), message: error.to_string() })?
                .parse::<#ty>()
                .map_err(|_| ::auto_di::DiError::Configuration { key: #key.into(), message: "value could not be parsed".into() })?
        }
    });
    let provider_name = format_ident!("configuration_properties_{ident}");
    let invocation = quote! { <#ident as ::auto_di::ConfigurationProperties>::from_environment()? };
    let registration = registration(
        &provider_name,
        &syn::parse_quote!(#ident),
        &[],
        &[],
        &[],
        invocation,
    );
    Ok(quote! {
        #structure
        impl ::auto_di::ConfigurationProperties for #ident {
            fn from_environment() -> ::std::result::Result<Self, ::auto_di::DiError> {
                Ok(Self { #(#bindings),* })
            }
        }
        #registration
    })
}

/// Registers all `#[provider]` methods in an inherent impl as singleton providers.
/// The configuration object is itself a singleton created through `Default`.
pub(crate) fn configuration(_attribute: TokenStream, item: TokenStream) -> TokenStream {
    let item_impl = parse_macro_input!(item as ItemImpl);
    match expand_configuration(item_impl) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

/// Registers a standalone provider, or is consumed as a provider marker when nested
/// inside a `#[configuration]` impl.
pub(crate) fn provider(attribute: TokenStream, item: TokenStream) -> TokenStream {
    singleton(attribute, item)
}

fn expand_function(
    mut function: ItemFn,
    options: &ProviderOptions,
) -> syn::Result<proc_macro2::TokenStream> {
    let function_name = function.sig.ident.clone();
    let output_type = match &function.sig.output {
        ReturnType::Type(_, ty) => ty.as_ref().clone(),
        ReturnType::Default => {
            return Err(syn::Error::new_spanned(
                &function.sig,
                "a #[singleton] provider must return a value",
            ));
        }
    };
    let (argument_names, dependency_types, qualifiers) = dependencies(&mut function.sig)?;
    let invocation = if function.sig.asyncness.is_some() {
        quote! { #function_name(#(#argument_names),*).await }
    } else {
        quote! { #function_name(#(#argument_names),*) }
    };

    let registration = registration_with_options(
        &function_name,
        &output_type,
        &argument_names,
        &dependency_types,
        &qualifiers,
        invocation,
        options,
    );

    Ok(quote! {
        #function
        #registration
    })
}

fn expand_impl(
    mut item_impl: ItemImpl,
    options: &ProviderOptions,
) -> syn::Result<proc_macro2::TokenStream> {
    if item_impl.trait_.is_some() {
        return Err(syn::Error::new_spanned(
            &item_impl,
            "#[singleton] requires an inherent impl, not a trait impl",
        ));
    }
    if !item_impl.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &item_impl.generics,
            "generic singleton impl blocks are not supported yet",
        ));
    }

    let constructor_index = item_impl
        .items
        .iter()
        .position(|item| match item {
            ImplItem::Fn(function) => function.sig.ident == "new",
            _ => false,
        })
        .ok_or_else(|| {
            syn::Error::new_spanned(
                &item_impl.self_ty,
                "a #[singleton] impl must contain a new(...) -> Self constructor",
            )
        })?;
    let output_type = item_impl.self_ty.as_ref().clone();
    let constructor = match &mut item_impl.items[constructor_index] {
        ImplItem::Fn(function) => function,
        _ => unreachable!(),
    };
    validate_impl_constructor(constructor)?;

    let (argument_names, dependency_types, qualifiers) = dependencies(&mut constructor.sig)?;
    let type_ident = singleton_type_ident(&output_type)?;
    let constructor_name = constructor.sig.ident.clone();
    let invocation = if constructor.sig.asyncness.is_some() {
        quote! { <#output_type>::#constructor_name(#(#argument_names),*).await }
    } else {
        quote! { <#output_type>::#constructor_name(#(#argument_names),*) }
    };
    let registration = registration_with_options(
        type_ident,
        &output_type,
        &argument_names,
        &dependency_types,
        &qualifiers,
        invocation,
        options,
    );

    let mut provider_registrations = Vec::new();
    for item in &mut item_impl.items {
        let ImplItem::Fn(method) = item else { continue };
        let Some(provider_attribute) = method
            .attrs
            .iter()
            .find(|attribute| is_provider_attribute(attribute))
        else {
            continue;
        };
        let provider_options = match &provider_attribute.meta {
            syn::Meta::Path(_) => ProviderOptions::default(),
            syn::Meta::List(list) => parse_provider_options2(list.tokens.clone())?,
            syn::Meta::NameValue(_) => {
                return Err(syn::Error::new_spanned(
                    provider_attribute,
                    "use #[provider(...)]",
                ));
            }
        };
        method
            .attrs
            .retain(|attribute| !is_provider_attribute(attribute));

        let provider_type = match &method.sig.output {
            ReturnType::Type(_, ty) => ty.as_ref().clone(),
            ReturnType::Default => {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "a #[provider] method must return a value",
                ));
            }
        };
        let (has_receiver, provider_arguments, provider_dependencies, provider_qualifiers) =
            provider_dependencies(&mut method.sig)?;
        let method_name = method.sig.ident.clone();
        let provider_registration_name = format_ident!("provider_{type_ident}_{method_name}");
        let provider_invocation = if has_receiver {
            quote! { owner.#method_name(#(#provider_arguments),*) }
        } else {
            quote! { <#output_type>::#method_name(#(#provider_arguments),*) }
        };
        let provider_invocation = if method.sig.asyncness.is_some() {
            quote! { #provider_invocation.await }
        } else {
            provider_invocation
        };
        let prelude = has_receiver.then(|| {
            quote! {
                let owner: ::std::sync::Arc<#output_type> =
                    container.resolve_dependency::<#output_type>(&context).await?;
            }
        });

        provider_registrations.push(registration_with_prelude(
            &provider_registration_name,
            &provider_type,
            &provider_arguments,
            &provider_dependencies,
            &provider_qualifiers,
            prelude.unwrap_or_default(),
            provider_invocation,
            &provider_options,
        ));
    }

    Ok(quote! {
        #item_impl
        #registration
        #(#provider_registrations)*
    })
}

fn expand_configuration(mut item_impl: ItemImpl) -> syn::Result<proc_macro2::TokenStream> {
    if item_impl.trait_.is_some() || !item_impl.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &item_impl,
            "#[configuration] requires a non-generic inherent impl",
        ));
    }

    let configuration_type = item_impl.self_ty.as_ref().clone();
    let configuration_ident = singleton_type_ident(&configuration_type)?.clone();
    let configuration_registration = registration(
        &format_ident!("configuration_{configuration_ident}"),
        &configuration_type,
        &[],
        &[],
        &[],
        quote! { <#configuration_type as ::std::default::Default>::default() },
    );
    let mut registrations = Vec::new();

    for item in &mut item_impl.items {
        let ImplItem::Fn(method) = item else { continue };
        let Some(provider_attribute) = method
            .attrs
            .iter()
            .find(|attribute| is_provider_attribute(attribute))
        else {
            continue;
        };
        let provider_options = match &provider_attribute.meta {
            syn::Meta::Path(_) => ProviderOptions::default(),
            syn::Meta::List(list) => parse_provider_options2(list.tokens.clone())?,
            syn::Meta::NameValue(_) => {
                return Err(syn::Error::new_spanned(
                    provider_attribute,
                    "use #[provider(...)]",
                ));
            }
        };
        method
            .attrs
            .retain(|attribute| !is_provider_attribute(attribute));

        let output_type = match &method.sig.output {
            ReturnType::Type(_, ty) => ty.as_ref().clone(),
            ReturnType::Default => {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "a #[provider] method must return a value",
                ));
            }
        };
        let (has_receiver, argument_names, dependency_types, qualifiers) =
            provider_dependencies(&mut method.sig)?;
        let method_name = method.sig.ident.clone();
        let registration_name = format_ident!("provider_{configuration_ident}_{method_name}");
        let invocation = if has_receiver {
            quote! { configuration.#method_name(#(#argument_names),*) }
        } else {
            quote! { <#configuration_type>::#method_name(#(#argument_names),*) }
        };
        let invocation = if method.sig.asyncness.is_some() {
            quote! { #invocation.await }
        } else {
            invocation
        };
        let prelude = has_receiver.then(|| {
            quote! {
                let configuration: ::std::sync::Arc<#configuration_type> =
                    container.resolve_dependency::<#configuration_type>(&context).await?;
            }
        });

        registrations.push(registration_with_prelude(
            &registration_name,
            &output_type,
            &argument_names,
            &dependency_types,
            &qualifiers,
            prelude.unwrap_or_default(),
            invocation,
            &provider_options,
        ));
    }

    if registrations.is_empty() {
        return Err(syn::Error::new_spanned(
            &item_impl,
            "#[configuration] must contain at least one #[provider] method",
        ));
    }

    Ok(quote! {
        #item_impl
        #configuration_registration
        #(#registrations)*
    })
}

fn validate_impl_constructor(constructor: &ImplItemFn) -> syn::Result<()> {
    if constructor.sig.receiver().is_some() {
        return Err(syn::Error::new_spanned(
            &constructor.sig,
            "the singleton new constructor must be an associated function",
        ));
    }
    match &constructor.sig.output {
        ReturnType::Type(_, ty) if matches!(ty.as_ref(), Type::Path(path) if path.path.is_ident("Self")) => {
            Ok(())
        }
        _ => Err(syn::Error::new_spanned(
            &constructor.sig.output,
            "the singleton new constructor must return Self",
        )),
    }
}

fn dependencies(
    signature: &mut Signature,
) -> syn::Result<(Vec<syn::Ident>, Vec<Type>, Vec<Option<String>>)> {
    let mut argument_names = Vec::new();
    let mut dependency_types = Vec::new();
    let mut qualifiers = Vec::new();

    for input in &mut signature.inputs {
        let FnArg::Typed(argument) = input else {
            return Err(syn::Error::new_spanned(
                input,
                "singleton constructors cannot have a self receiver",
            ));
        };
        let Pat::Ident(pattern) = argument.pat.as_ref() else {
            return Err(syn::Error::new_spanned(
                &argument.pat,
                "use a simple parameter name for an injected dependency",
            ));
        };
        argument_names.push(pattern.ident.clone());
        validate_dependency_type(argument.ty.as_ref())?;
        dependency_types.push(argument.ty.as_ref().clone());
        qualifiers.push(take_qualifier(&mut argument.attrs)?);
    }
    Ok((argument_names, dependency_types, qualifiers))
}

fn provider_dependencies(
    signature: &mut Signature,
) -> syn::Result<(bool, Vec<syn::Ident>, Vec<Type>, Vec<Option<String>>)> {
    let mut has_receiver = false;
    let mut names = Vec::new();
    let mut types = Vec::new();
    let mut qualifiers = Vec::new();
    for input in &mut signature.inputs {
        match input {
            FnArg::Receiver(receiver) => {
                if has_receiver || receiver.reference.is_none() || receiver.mutability.is_some() {
                    return Err(syn::Error::new_spanned(
                        receiver,
                        "a #[provider] method only supports an immutable &self receiver",
                    ));
                }
                has_receiver = true;
            }
            FnArg::Typed(argument) => {
                let Pat::Ident(pattern) = argument.pat.as_ref() else {
                    return Err(syn::Error::new_spanned(
                        &argument.pat,
                        "use a simple parameter name for an injected dependency",
                    ));
                };
                names.push(pattern.ident.clone());
                validate_dependency_type(argument.ty.as_ref())?;
                types.push(argument.ty.as_ref().clone());
                qualifiers.push(take_qualifier(&mut argument.attrs)?);
            }
        }
    }
    Ok((has_receiver, names, types, qualifiers))
}

fn is_provider_attribute(attribute: &syn::Attribute) -> bool {
    attribute.path().is_ident("provider")
}

fn take_qualifier(attributes: &mut Vec<syn::Attribute>) -> syn::Result<Option<String>> {
    let mut value = None;
    for attribute in attributes
        .iter()
        .filter(|attr| attr.path().is_ident("qualifier"))
    {
        if value.is_some() {
            return Err(syn::Error::new_spanned(
                attribute,
                "only one qualifier is allowed",
            ));
        }
        value = Some(attribute.parse_args::<LitStr>()?.value());
    }
    attributes.retain(|attr| !attr.path().is_ident("qualifier"));
    Ok(value)
}

fn registration(
    name: &syn::Ident,
    output_type: &Type,
    argument_names: &[syn::Ident],
    dependency_types: &[Type],
    qualifiers: &[Option<String>],
    invocation: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    registration_with_options(
        name,
        output_type,
        argument_names,
        dependency_types,
        qualifiers,
        invocation,
        &ProviderOptions::default(),
    )
}

fn registration_with_options(
    name: &syn::Ident,
    output_type: &Type,
    argument_names: &[syn::Ident],
    dependency_types: &[Type],
    qualifiers: &[Option<String>],
    invocation: proc_macro2::TokenStream,
    options: &ProviderOptions,
) -> proc_macro2::TokenStream {
    registration_with_prelude(
        name,
        output_type,
        argument_names,
        dependency_types,
        qualifiers,
        quote! {},
        invocation,
        options,
    )
}

fn registration_with_prelude(
    name: &syn::Ident,
    output_type: &Type,
    argument_names: &[syn::Ident],
    dependency_types: &[Type],
    qualifiers: &[Option<String>],
    prelude: proc_macro2::TokenStream,
    invocation: proc_macro2::TokenStream,
    options: &ProviderOptions,
) -> proc_macro2::TokenStream {
    let factory_name = format_ident!("__di_factory_{name}");
    let type_id_name = format_ident!("__di_type_id_{name}");
    let type_name_name = format_ident!("__di_type_name_{name}");
    let destroy_name = format_ident!("__di_destroy_{name}");
    let option_tokens = |value: Option<&str>| match value {
        Some(value) => quote!(Some(#value)),
        None => quote!(None),
    };
    let provider_name = option_tokens(options.name.as_deref());
    let primary = options.primary;
    let eager = options.eager;
    let profile = option_tokens(options.profile.as_deref());
    let condition_key = option_tokens(options.condition_key.as_deref());
    let condition_value = option_tokens(options.condition_value.as_deref());
    let scope = match options.scope.as_deref().unwrap_or("singleton") {
        "prototype" => quote!(::auto_di::Scope::Prototype),
        "request" => quote!(::auto_di::Scope::Request),
        _ => quote!(::auto_di::Scope::Singleton),
    };
    let post_construct = options.post_construct.as_ref().map(|method| {
        let method = format_ident!("{method}");
        quote! { value.#method().await; }
    });
    let (destroy_function, destroy_value) = if let Some(method) = &options.pre_destroy {
        let method = format_ident!("{method}");
        (
            quote! {
                #[doc(hidden)]
                fn #destroy_name(value: ::auto_di::DynArc) -> ::auto_di::BoxFuture<'static, ::std::result::Result<(), ::auto_di::DiError>> {
                    ::std::boxed::Box::pin(async move {
                        let value = value.downcast::<#output_type>()
                            .map_err(|_| ::auto_di::DiError::TypeMismatch(::std::any::type_name::<#output_type>()))?;
                        value.#method().await;
                        Ok(())
                    })
                }
            },
            quote!(Some(#destroy_name as _)),
        )
    } else {
        (quote! {}, quote!(None))
    };
    let resolve_dependencies = argument_names
        .iter()
        .zip(dependency_types.iter())
        .zip(qualifiers.iter())
        .map(|((name, ty), qualifier)| dependency_resolution(name, ty, qualifier.as_deref()));

    quote! {
        #[doc(hidden)]
        fn #type_id_name() -> ::std::any::TypeId {
            ::std::any::TypeId::of::<#output_type>()
        }

        #[doc(hidden)]
        fn #type_name_name() -> &'static str {
            ::std::any::type_name::<#output_type>()
        }

        #[doc(hidden)]
        fn #factory_name<'a>(
            container: &'a ::auto_di::Container,
            context: ::auto_di::ResolutionContext,
        ) -> ::auto_di::BoxFuture<'a, ::std::result::Result<::auto_di::DynArc, ::auto_di::DiError>> {
            ::std::boxed::Box::pin(async move {
                #prelude
                #(#resolve_dependencies)*
                let value: #output_type = #invocation;
                #post_construct
                Ok(::std::sync::Arc::new(value) as ::auto_di::DynArc)
            })
        }

        #destroy_function

        ::auto_di::__private::inventory::submit! {
            ::auto_di::ProviderDescriptor::configured(
                #type_id_name,
                #type_name_name,
                #factory_name,
                #provider_name,
                #primary,
                #scope,
                #eager,
                #profile,
                #condition_key,
                #condition_value,
                #destroy_value,
            )
        }
    }
}

fn singleton_type_ident(ty: &Type) -> syn::Result<&syn::Ident> {
    let Type::Path(path) = ty else {
        return Err(syn::Error::new_spanned(
            ty,
            "singleton impl type must be a named type",
        ));
    };
    path.path
        .segments
        .last()
        .map(|segment| &segment.ident)
        .ok_or_else(|| syn::Error::new_spanned(ty, "singleton impl type must be a named type"))
}

fn validate_dependency_type(ty: &Type) -> syn::Result<()> {
    if generic_inner(ty, "Arc").is_some()
        || generic_inner(ty, "Provider").is_some()
        || generic_inner(ty, "Lazy").is_some()
    {
        return Ok(());
    }
    if let Some(inner) = generic_inner(ty, "Option").or_else(|| generic_inner(ty, "Vec")) {
        if generic_inner(inner, "Arc").is_some() {
            return Ok(());
        }
    }
    Err(syn::Error::new_spanned(
        ty,
        "dependency must be Arc<T>, Option<Arc<T>>, Vec<Arc<T>>, Provider<T>, or Lazy<T>",
    ))
}

fn generic_inner<'a>(ty: &'a Type, expected: &str) -> Option<&'a Type> {
    let Type::Path(path) = ty else { return None };
    let segment = path.path.segments.last()?;
    if segment.ident != expected {
        return None;
    }
    let PathArguments::AngleBracketed(arguments) = &segment.arguments else {
        return None;
    };
    match arguments.args.first() {
        Some(GenericArgument::Type(inner)) if arguments.args.len() == 1 => Some(inner),
        _ => None,
    }
}

fn dependency_resolution(
    name: &syn::Ident,
    ty: &Type,
    qualifier: Option<&str>,
) -> proc_macro2::TokenStream {
    if let Some(inner) = generic_inner(ty, "Arc") {
        if matches!(inner, Type::TraitObject(_)) {
            if let Some(qualifier) = qualifier {
                return quote! {
                    let #name: #ty = (*container.resolve_named_dependency::<#ty>(#qualifier, &context).await?).clone();
                };
            }
            return quote! {
                let #name: #ty = (*container.resolve_dependency::<#ty>(&context).await?).clone();
            };
        }
        if let Some(qualifier) = qualifier {
            return quote! {
                let #name: #ty = container.resolve_named_dependency::<#inner>(#qualifier, &context).await?;
            };
        }
        return quote! {
            let #name: #ty = container.resolve_dependency::<#inner>(&context).await?;
        };
    }
    if let Some(wrapped) = generic_inner(ty, "Option") {
        let inner = generic_inner(wrapped, "Arc").expect("validated Option<Arc<T>>");
        return quote! {
            let #name: #ty = container.resolve_optional_dependency::<#inner>(&context).await?;
        };
    }
    if let Some(wrapped) = generic_inner(ty, "Vec") {
        let inner = generic_inner(wrapped, "Arc").expect("validated Vec<Arc<T>>");
        return quote! {
            let #name: #ty = container.resolve_all_dependency::<#inner>(&context).await?;
        };
    }
    quote! { let #name: #ty = ::std::default::Default::default(); }
}