injectable-rs-macros 0.1.0

Proc macros for the injectable-rs DI framework
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
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
//! The `#[injectable]` attribute macro for constructor-based injection.
//!
//! This macro processes an impl block, finds the `#[injectable_ctor]` method,
//! and generates the `Provider`, `Injectable`, and lifecycle hook impls.
//!
//! # Parameter Injection Rules
//!
//! `Inject<T>` parameters are auto-injected. All other types require an explicit
//! `#[injectable(inject)]` annotation (or a factory variant); omitting it is a compile error.
//!
//! | Constructor Parameter | Annotation                              | DI Extraction             | Conversion              |
//! |-----------------------|-----------------------------------------|---------------------------|-------------------------|
//! | `Inject<T>`          | (none needed)                           | `Inject<T>::extract(ctx)` | Pass directly           |
//! | `Arc<T>`             | `#[injectable(inject)]`                 | `Inject<T>::extract(ctx)` | `.0` (inner Arc)        |
//! | `T` (other)          | `#[injectable(inject)]`                 | `Inject<T>::extract(ctx)` | `Arc::unwrap_or_clone`  |
//! | any                  | `#[injectable(inject(use_factory_*=p))]`| factory fn                | as declared             |
//!
//! # Auto-detected Lifecycle Hooks
//!
//! Methods annotated with `#[injectable(post_construct)]` or
//! `#[injectable(pre_destruct)]` are auto-detected. The macro generates
//! the corresponding trait impls automatically.
//!
//! # Hook Return Types
//!
//! Both `#[post_construct]` and `#[pre_destruct]` methods may return either
//! `()` or `Result<(), E>`. The macro detects the return type and adapts
//! accordingly:
//!
//! - `-> ()` → wrapped in `Ok(())` for the trait impl
//! - `-> Result<(), E>` → mapped to `HookResult` via `?` operator

use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use syn::visit_mut::VisitMut;

use crate::attrs::Scope;
use crate::metadata::{
    extract_arc_inner_str, extract_inject_dyn_inner, extract_inject_inner,
    extract_option_inject_dyn_inner, type_to_string,
};

// ─── Public Entry Point ──────────────────────────────────────────────

/// Expand the `#[injectable]` attribute macro.
///
/// `attrs` contains the attribute arguments (e.g., `scope = "transient"`).
/// `item` contains the impl block token stream.
pub fn expand_injectable_impl(attrs: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {
    // Parse attribute arguments
    let injectable_attrs = parse_impl_attrs(attrs)?;

    // Parse the impl block
    let mut impl_block: syn::ItemImpl = syn::parse2(item)?;

    // Extract the type name, full self-type, and generics from the impl block.
    let (type_name, self_ty, impl_generics) = extract_type_name(&impl_block)?;

    // Scan methods for #[injectable_ctor], #[post_construct], #[pre_destruct]
    let scan_result = scan_impl_methods(&impl_block)?;

    // Strip lifecycle attributes from methods in the output impl block
    AttrStripper.visit_item_impl_mut(&mut impl_block);

    if let Some(constructor) = scan_result.constructor {
        // ── Constructor path ────────────────────────────────────────────────
        let provider_code = generate_provider(
            &type_name,
            &self_ty,
            &impl_generics,
            &constructor,
            &scan_result.post_construct_hooks,
            &scan_result.pre_destruct_hooks,
            &injectable_attrs,
        )?;
        Ok(quote! { #impl_block #provider_code })
    } else {
        // ── No-constructor path ─────────────────────────────────────────────
        if scan_result.post_construct_hooks.is_empty() && scan_result.pre_destruct_hooks.is_empty()
        {
            return Err(syn::Error::new(
                impl_block.self_ty.span(),
                "#[injectable] without #[injectable(ctor)] requires at least one \
                 #[injectable(post_construct)] or #[injectable(pre_destruct)] method. \
                 For field injection without lifecycle hooks, use #[injectable] alone.",
            ));
        }
        let post_impl = generate_post_construct_impl(&type_name, &scan_result.post_construct_hooks);
        let pre_impl = generate_pre_destruct_impl(&type_name, &scan_result.pre_destruct_hooks);
        let hooks_submit = generate_hooks_entry_submit(
            &type_name,
            &scan_result.post_construct_hooks,
            &scan_result.pre_destruct_hooks,
        );
        Ok(quote! { #impl_block #post_impl #pre_impl #hooks_submit })
    }
}

// ─── Attribute Parsing ───────────────────────────────────────────────

/// Parsed attributes from `#[injectable_impl(...)]`.
struct InjectableImplAttrs {
    scope: Scope,
}

impl Default for InjectableImplAttrs {
    fn default() -> Self {
        Self {
            scope: Scope::Singleton,
        }
    }
}

/// Parse the attribute arguments for `#[injectable_impl(...)]`.
fn parse_impl_attrs(attrs: TokenStream) -> syn::Result<InjectableImplAttrs> {
    if attrs.is_empty() {
        return Ok(InjectableImplAttrs::default());
    }

    let parsed: syn::punctuated::Punctuated<ImplArg, syn::Token![,]> =
        syn::parse::Parser::parse2(syn::punctuated::Punctuated::parse_terminated, attrs)?;

    let mut result = InjectableImplAttrs::default();
    for arg in parsed {
        match arg {
            ImplArg::Scope(s) => {
                result.scope = match s.as_str() {
                    "singleton" => Scope::Singleton,
                    "transient" => Scope::Transient,
                    "request" => Scope::Request,
                    other => Scope::Custom(other.to_string()),
                };
            }
        }
    }

    Ok(result)
}

/// A single argument within `#[injectable_impl(...)]`.
enum ImplArg {
    /// `scope = "value"`
    Scope(String),
}

impl syn::parse::Parse for ImplArg {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let ident: syn::Ident = input.parse()?;
        if ident == "scope" {
            input.parse::<syn::Token![=]>()?;
            let lit: syn::LitStr = input.parse()?;
            Ok(ImplArg::Scope(lit.value()))
        } else {
            Err(syn::Error::new(
                ident.span(),
                format!("unknown injectable_impl attribute: `{ident}`"),
            ))
        }
    }
}

// ─── Method Scanning ─────────────────────────────────────────────────

/// Information about a constructor method.
struct ConstructorInfo {
    method_name: syn::Ident,
    is_async: bool,
    params: Vec<ParamInfo>,
    /// How the constructor returns its value.
    return_kind: ConstructorReturn,
}

/// How the constructor's return value should be handled in generated code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConstructorReturn {
    /// Returns `Self` directly.
    SelfOwned,
    /// Returns `Result<Self, E>` where `E: Display`.
    /// Error is wrapped as `InjectableError::ConstructionFailed`.
    ResultWrapped,
    /// Returns `Result<Self, InjectableError>`.
    /// Error is passed through with `?` — no re-wrapping.
    ResultInjectableError,
}

/// How a factory attribute on a constructor parameter calls its function.
#[derive(Debug, Clone)]
enum FactoryFn {
    /// `#[inject(use_factory_async = path)]` — calls `path(ctx).await`
    Async(syn::Path),
    /// `#[inject(use_factory_sync = path)]` — calls `path(ctx)` (no `.await`)
    Sync(syn::Path),
}

impl FactoryFn {
    fn path(&self) -> &syn::Path {
        match self {
            FactoryFn::Async(p) | FactoryFn::Sync(p) => p,
        }
    }
    fn is_async(&self) -> bool {
        matches!(self, FactoryFn::Async(_))
    }
}

/// Information about a single constructor parameter.
struct ParamInfo {
    name: syn::Ident,
    ty: syn::Type,
    ty_string: String,
    /// Optional factory function from `#[inject(use_factory_async/sync = path)]`.
    factory_fn: Option<FactoryFn>,
}

/// Information about a lifecycle hook method.
struct HookInfo {
    method_name: syn::Ident,
    is_async: bool,
    /// Whether the method returns `Result<(), E>` (true) or `()` (false).
    returns_result: bool,
}

/// Result of scanning the impl block for annotated methods.
struct ScanResult {
    constructor: Option<ConstructorInfo>,
    post_construct_hooks: Vec<HookInfo>,
    pre_destruct_hooks: Vec<HookInfo>,
}

/// Returns true if `attr` is `#[injectable(sub_arg)]` where the first token
/// inside the parens is the given identifier.
///
/// Used to detect `#[injectable(ctor)]`, `#[injectable(post_construct)]`,
/// and `#[injectable(pre_destruct)]` on impl block methods.
fn is_injectable_sub_arg(attr: &syn::Attribute, sub_arg: &str) -> bool {
    if !attr.path().is_ident("injectable") {
        return false;
    }
    attr.parse_args_with(|input: syn::parse::ParseStream| {
        let ident: syn::Ident = input.parse()?;
        Ok(ident == sub_arg)
    })
    .unwrap_or(false)
}

/// Scan all methods in the impl block for lifecycle annotations.
fn scan_impl_methods(impl_block: &syn::ItemImpl) -> syn::Result<ScanResult> {
    let mut result = ScanResult {
        constructor: None,
        post_construct_hooks: Vec::new(),
        pre_destruct_hooks: Vec::new(),
    };

    for item in &impl_block.items {
        if let syn::ImplItem::Fn(method) = item {
            let has_constructor = method
                .attrs
                .iter()
                .any(|a| is_injectable_sub_arg(a, "ctor"));
            let has_post_construct = method
                .attrs
                .iter()
                .any(|a| is_injectable_sub_arg(a, "post_construct"));
            let has_pre_destruct = method
                .attrs
                .iter()
                .any(|a| is_injectable_sub_arg(a, "pre_destruct"));

            if has_constructor {
                if result.constructor.is_some() {
                    return Err(syn::Error::new(
                        method.sig.ident.span(),
                        "#[injectable] requires exactly one #[injectable(ctor)] method, but found multiple",
                    ));
                }

                let params = extract_params(&method.sig)?;
                result.constructor = Some(ConstructorInfo {
                    method_name: method.sig.ident.clone(),
                    is_async: method.sig.asyncness.is_some(),
                    return_kind: classify_constructor_return(&method.sig),
                    params,
                });
            }

            if has_post_construct {
                result.post_construct_hooks.push(HookInfo {
                    method_name: method.sig.ident.clone(),
                    is_async: method.sig.asyncness.is_some(),
                    returns_result: returns_result(&method.sig),
                });
            }

            if has_pre_destruct {
                result.pre_destruct_hooks.push(HookInfo {
                    method_name: method.sig.ident.clone(),
                    is_async: method.sig.asyncness.is_some(),
                    returns_result: returns_result(&method.sig),
                });
            }
        }
    }

    Ok(result)
}

/// Classify a constructor's return type.
fn classify_constructor_return(sig: &syn::Signature) -> ConstructorReturn {
    match &sig.output {
        syn::ReturnType::Default => ConstructorReturn::SelfOwned,
        syn::ReturnType::Type(_, ty) => {
            let ty_str = type_to_string(ty);
            if !ty_str.starts_with("Result") {
                return ConstructorReturn::SelfOwned;
            }
            // If the error type is InjectableError (any path ending in it),
            // pass through with `?`; otherwise wrap as ConstructionFailed.
            if ty_str.contains("InjectableError") {
                ConstructorReturn::ResultInjectableError
            } else {
                ConstructorReturn::ResultWrapped
            }
        }
    }
}

/// Check if a method signature returns `Result` (vs `()`).
///
/// Returns `true` if the return type is `Result<(), ...>` or any `Result<...>`.
/// Returns `false` if the return type is `()` or absent (implicit `()`).
fn returns_result(sig: &syn::Signature) -> bool {
    match &sig.output {
        syn::ReturnType::Default => false, // implicit ()
        syn::ReturnType::Type(_, ty) => {
            let ty_str = type_to_string(ty);
            ty_str.starts_with("Result")
        }
    }
}

/// Extract parameter information from a method signature.
fn extract_params(sig: &syn::Signature) -> syn::Result<Vec<ParamInfo>> {
    let mut params = Vec::new();

    for input in &sig.inputs {
        if let syn::FnArg::Typed(pat_type) = input {
            let name = match &*pat_type.pat {
                syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
                _ => {
                    return Err(syn::Error::new(
                        pat_type.pat.span(),
                        "constructor parameters must be named",
                    ));
                }
            };

            let ty = (*pat_type.ty).clone();
            let ty_string = type_to_string(&ty);

            // Parse optional #[injectable(inject)] / #[injectable(inject(use_factory_*=path))]
            let (has_inject, factory_fn) = parse_param_inject(&pat_type.attrs)?;

            // Non-Inject<T> params require an explicit #[injectable(inject)] annotation
            if extract_inject_inner(&ty).is_none() && !has_inject {
                return Err(syn::Error::new(
                    ty.span(),
                    format!(
                        "parameter `{}: {}` is not auto-injectable; \
                         only `Inject<T>` parameters are injected automatically — \
                         annotate with `#[injectable(inject)]` to extract this from the container",
                        name, ty_string
                    ),
                ));
            }

            params.push(ParamInfo {
                name,
                ty,
                ty_string,
                factory_fn,
            });
        }
        // Skip `self` parameters (shouldn't appear in constructors)
    }

    Ok(params)
}

/// Parse `#[injectable(inject)]` / `#[injectable(inject(use_factory_async/sync = path))]`
/// from a constructor parameter's attributes.
///
/// Returns `(has_inject_annotation, optional_factory)`:
/// - `#[injectable(inject)]`                      → `(true, None)`
/// - `#[injectable(inject(use_factory_async=…))]` → `(true, Some(FactoryFn::Async(…)))`
/// - `#[injectable(inject(use_factory_sync=…))]`  → `(true, Some(FactoryFn::Sync(…)))`
/// - no matching attr                             → `(false, None)`
fn parse_param_inject(attrs: &[syn::Attribute]) -> syn::Result<(bool, Option<FactoryFn>)> {
    for attr in attrs {
        if attr.path().is_ident("injectable") {
            let factory = attr.parse_args_with(|input: syn::parse::ParseStream| {
                let kw: syn::Ident = input.parse()?;
                if kw != "inject" {
                    return Err(syn::Error::new(
                        kw.span(),
                        format!(
                            "expected `inject` inside `#[injectable(...)]` on a parameter, \
                             found `{kw}`"
                        ),
                    ));
                }
                if input.is_empty() {
                    // #[injectable(inject)] — bare, no factory args
                    return Ok(None);
                }
                // #[injectable(inject(use_factory_async/sync = path))]
                let content;
                syn::parenthesized!(content in input);
                let ident: syn::Ident = content.parse()?;
                let is_async = if ident == "use_factory_async" || ident == "use_factory" {
                    true
                } else if ident == "use_factory_sync" {
                    false
                } else {
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown inject argument on parameter: `{ident}`; \
                             expected `use_factory_async = path` or `use_factory_sync = path`"
                        ),
                    ));
                };
                content.parse::<syn::Token![=]>()?;
                let path: syn::Path = content.parse()?;
                if is_async {
                    Ok(Some(FactoryFn::Async(path)))
                } else {
                    Ok(Some(FactoryFn::Sync(path)))
                }
            })?;
            return Ok((true, factory));
        }
    }
    Ok((false, None))
}

// ─── Type Name Extraction ────────────────────────────────────────────

/// Extract the type name, full self-type, and generics from an impl block.
///
/// Returns `(ident, self_ty, impl_generics)` where:
/// - `ident` is the bare type name (e.g. `Cache` from `impl<T> Cache<T>`)
/// - `self_ty` is the full self type (e.g. `Cache<T>`) — used in generated impls
/// - `impl_generics` is the impl block's generic parameter list
fn extract_type_name(
    impl_block: &syn::ItemImpl,
) -> syn::Result<(syn::Ident, syn::Type, syn::Generics)> {
    let ident = match &*impl_block.self_ty {
        syn::Type::Path(type_path) => type_path
            .path
            .segments
            .last()
            .map(|s| s.ident.clone())
            .ok_or_else(|| {
                syn::Error::new(
                    impl_block.self_ty.span(),
                    "cannot determine type name from impl block",
                )
            })?,
        _ => {
            return Err(syn::Error::new(
                impl_block.self_ty.span(),
                "#[injectable] can only be used on impl blocks for named types",
            ));
        }
    };
    Ok((
        ident,
        (*impl_block.self_ty).clone(),
        impl_block.generics.clone(),
    ))
}

// ─── Attribute Stripping ─────────────────────────────────────────────

/// Visitor that strips `#[injectable_ctor]`, `#[post_construct]`, and
/// `#[pre_destruct]` attributes from methods in the output impl block.
struct AttrStripper;

impl VisitMut for AttrStripper {
    fn visit_impl_item_fn_mut(&mut self, node: &mut syn::ImplItemFn) {
        // Strip all #[injectable(...)] from method attrs:
        // covers #[injectable(ctor)], #[injectable(post_construct)], #[injectable(pre_destruct)].
        node.attrs.retain(|a| !a.path().is_ident("injectable"));
        // Strip #[injectable(inject)] from parameter-level attributes so rustc
        // doesn't see an unknown attribute in the output impl block.
        for input in node.sig.inputs.iter_mut() {
            if let syn::FnArg::Typed(pat_type) = input {
                pat_type.attrs.retain(|a| !a.path().is_ident("injectable"));
            }
        }
        syn::visit_mut::visit_impl_item_fn_mut(self, node);
    }
}

// ─── Code Generation ─────────────────────────────────────────────────

/// Generate all the DI infrastructure code for the type.
fn generate_provider(
    type_name: &syn::Ident,
    self_ty: &syn::Type,
    impl_generics: &syn::Generics,
    constructor: &ConstructorInfo,
    post_construct_hooks: &[HookInfo],
    pre_destruct_hooks: &[HookInfo],
    attrs: &InjectableImplAttrs,
) -> syn::Result<TokenStream> {
    let provider_name = syn::Ident::new(
        &format!("{}Provider", type_name),
        proc_macro2::Span::call_site(),
    );
    let (gen_impl, ty_generics, where_clause) = impl_generics.split_for_impl();
    let is_generic = !impl_generics.params.is_empty();

    // Generate extraction statements and constructor call arguments
    let (extract_statements, call_args, dep_strings) = generate_extraction_code(constructor)?;

    // Generate the constructor call
    let method_name = &constructor.method_name;
    let await_token = if constructor.is_async {
        quote! { .await }
    } else {
        quote! {}
    };
    let type_str = type_name.to_string();

    // For generic types we call the constructor via the full self_ty path;
    // for concrete types the bare ident is sufficient.
    let ctor_path = if is_generic {
        quote! { <#self_ty>::#method_name }
    } else {
        quote! { #type_name::#method_name }
    };

    let construction = match constructor.return_kind {
        ConstructorReturn::SelfOwned => quote! {
            #ctor_path(#(#call_args),*) #await_token
        },
        ConstructorReturn::ResultWrapped => quote! {
            #ctor_path(#(#call_args),*) #await_token
                .map_err(|e| injectable_rs_runtime::InjectableError::ConstructionFailed {
                    type_name: #type_str,
                    reason: e.to_string(),
                })?
        },
        // Result<Self, InjectableError> — error is already the right type, pass through.
        ConstructorReturn::ResultInjectableError => quote! {
            #ctor_path(#(#call_args),*) #await_token?
        },
    };

    // Generate post_construct hook calls in the provider body.
    // These propagate errors — if a hook fails, the entire resolution fails.
    let post_construct_calls = generate_post_construct_calls(post_construct_hooks, &type_str);

    // Generate PreDestruct impl and registration
    let pre_destruct_impl = generate_pre_destruct_impl(type_name, pre_destruct_hooks);
    let (pre_destruct_registration, return_instance) = if !pre_destruct_hooks.is_empty() {
        // Register destructor by wrapping instance in Arc<dyn PreDestruct>.
        // We create an Arc, register a clone of it for destruction, then
        // unwrap the original Arc to return the owned instance.
        // This requires T: Clone (reasonable bound for types with pre_destruct).
        (
            quote! {
                let __destructor_arc: std::sync::Arc<#self_ty> = std::sync::Arc::new(instance);
                ctx.register_destructor_with_name(
                    #type_str,
                    std::sync::Arc::clone(&__destructor_arc) as std::sync::Arc<dyn injectable_rs_runtime::PreDestruct>,
                );
                let instance = std::sync::Arc::unwrap_or_clone(__destructor_arc);
            },
            quote! { Ok(instance) },
        )
    } else {
        (quote! {}, quote! { Ok(instance) })
    };

    // Generate graph metadata
    let scope_str = attrs.scope.as_str();
    let graph_metadata = generate_graph_metadata(type_name, &dep_strings, scope_str);
    let is_singleton: bool = attrs.scope != crate::attrs::Scope::Transient;

    // InjectableArcFactory only for concrete (non-generic) types — see provider_gen.rs.
    let arc_factory_submit = if is_generic {
        quote! {}
    } else {
        crate::provider_gen::generate_arc_factory_submit(type_name, is_singleton)
    };

    // Generate PostConstruct impl if there are hooks
    let post_construct_impl = generate_post_construct_impl(type_name, post_construct_hooks);

    // Provider struct: plain for concrete types, PhantomData-carrying for generic types.
    let provider_struct = if is_generic {
        let phantom = crate::provider_gen::phantom_for_generics(impl_generics);
        quote! { pub struct #provider_name #ty_generics (#phantom); }
    } else {
        quote! { pub struct #provider_name; }
    };

    Ok(quote! {
        #provider_struct

        #[async_trait::async_trait]
        impl #gen_impl injectable_rs_runtime::Provider<#self_ty>
            for #provider_name #ty_generics
        #where_clause
        {
            async fn provide(
                ctx: &injectable_rs_runtime::ResolveContext,
            ) -> injectable_rs_runtime::InjectableResult<#self_ty> {
                #(#extract_statements)*
                let instance = #construction;
                #post_construct_calls
                #pre_destruct_registration
                #return_instance
            }
        }

        impl #gen_impl injectable_rs_runtime::Injectable for #self_ty
        #where_clause
        {
            type Provider = #provider_name #ty_generics;
            const IS_SINGLETON: bool = #is_singleton;
        }

        #post_construct_impl
        #pre_destruct_impl
        #graph_metadata
        #arc_factory_submit
    })
}

/// Generate the extraction statements and constructor call arguments.
///
/// Every parameter uses `<ParamType as Extract>::extract(ctx).await?`.
/// For `Inject<T>` this is direct; for `Arc<T>` it uses the blanket
/// `impl<T: Injectable> Extract for Arc<T>`.  No AST-level type detection
/// is needed — the Rust compiler verifies `ParamType: Extract`.
fn generate_extraction_code(
    constructor: &ConstructorInfo,
) -> syn::Result<(Vec<TokenStream>, Vec<TokenStream>, Vec<String>)> {
    let mut extract_statements = Vec::new();
    let mut call_args = Vec::new();
    let mut dep_strings = Vec::new();

    for param in &constructor.params {
        let name = &param.name;
        let ty = &param.ty;
        let ty_str = &param.ty_string;

        // ── factory param ─────────────────────────────────────────────────
        if let Some(factory) = &param.factory_fn {
            let path = factory.path();
            if factory.is_async() {
                extract_statements.push(quote! {
                    let #name: #ty = #path(ctx).await.map_err(|e|
                        injectable_rs_runtime::InjectableError::ConstructionFailed {
                            type_name: #ty_str,
                            reason: e.to_string(),
                        })?;
                });
            } else {
                extract_statements.push(quote! {
                    let #name: #ty = #path(ctx);
                });
            }
            call_args.push(quote! { #name });
            // Factory params are external — not added to dep_strings.
            continue;
        }

        // ── Inject<dyn Trait> / Option<Inject<dyn Trait>>: resolve via Arc ──
        if let Some(dyn_ty) = extract_inject_dyn_inner(ty) {
            extract_statements.push(quote! {
                let #name: #ty = {
                    let __arc = ctx.resolve_external::<::std::sync::Arc<#dyn_ty>>().await?;
                    injectable_rs_runtime::Inject::new(__arc)
                };
            });
            call_args.push(quote! { #name });
            // trait bindings are not tracked in the static dep graph
            continue;
        }
        if let Some(dyn_ty) = extract_option_inject_dyn_inner(ty) {
            extract_statements.push(quote! {
                let #name: #ty = match ctx.resolve_external::<::std::sync::Arc<#dyn_ty>>().await {
                    Ok(__arc) => Some(injectable_rs_runtime::Inject::new(__arc)),
                    Err(injectable_rs_runtime::InjectableError::MissingDependency { .. }) => None,
                    Err(__e) => return Err(__e),
                };
            });
            call_args.push(quote! { #name });
            continue;
        }

        // ── standard: <T as Extract>::extract(ctx) ────────────────────────
        extract_statements.push(quote! {
            let #name: #ty =
                <#ty as injectable_rs_runtime::Extract>::extract(ctx).await?;
        });
        call_args.push(quote! { #name });

        // dep_strings for graph metadata: unwrap inner type from Inject<T> or Arc<T>
        if let Some(inner) = extract_inject_inner(ty) {
            dep_strings.push(inner);
        } else if let Some(inner) = extract_arc_inner_str(ty) {
            dep_strings.push(inner);
        } else {
            dep_strings.push(ty_str.clone());
        }
    }

    Ok((extract_statements, call_args, dep_strings))
}

/// Generate post_construct hook calls for the provider body.
///
/// These calls happen after construction. If a hook returns `Result`,
/// errors are propagated via `?`. If a hook returns `()`, it's called
/// as a statement. On failure, the error is wrapped in
/// `InjectableError::LifecycleHookFailed`.
fn generate_post_construct_calls(hooks: &[HookInfo], type_name_str: &str) -> TokenStream {
    if hooks.is_empty() {
        return quote! {};
    }

    let calls: Vec<TokenStream> = hooks
        .iter()
        .map(|hook| {
            let hook_name = &hook.method_name;
            let await_token = if hook.is_async {
                quote! { .await }
            } else {
                quote! {}
            };

            if hook.returns_result {
                // Hook returns Result — propagate errors
                quote! {
                    instance.#hook_name()#await_token.map_err(|e| injectable_rs_runtime::InjectableError::LifecycleHookFailed {
                        type_name: #type_name_str,
                        hook: "post_construct",
                        reason: e.to_string(),
                    })?;
                }
            } else {
                // Hook returns () — just call it
                quote! {
                    instance.#hook_name()#await_token;
                }
            }
        })
        .collect();

    quote! { #(#calls)* }
}

/// Generate a `PostConstruct` impl if there are `#[post_construct]` hooks.
///
/// The trait's `post_construct` method returns `HookResult` (= `Result<(), Box<dyn Error + Send + Sync>>`).
/// The generated impl adapts the user's method:
/// - If the user's method returns `()`, we wrap in `Ok(())`
/// - If the user's method returns `Result<(), E>`, we map via `?`
fn generate_post_construct_impl(type_name: &syn::Ident, hooks: &[HookInfo]) -> TokenStream {
    if hooks.is_empty() {
        return quote! {};
    }

    let calls: Vec<TokenStream> = hooks
        .iter()
        .map(|hook| {
            let hook_name = &hook.method_name;
            let await_token = if hook.is_async {
                quote! { .await }
            } else {
                quote! {}
            };

            if hook.returns_result {
                // User's method returns Result — use ? to convert to HookResult
                quote! {
                    self.#hook_name()#await_token.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
                }
            } else {
                // User's method returns () — just call it
                quote! {
                    self.#hook_name()#await_token;
                }
            }
        })
        .collect();

    quote! {
        #[async_trait::async_trait]
        impl injectable_rs_runtime::PostConstruct for #type_name {
            async fn post_construct(&self) -> injectable_rs_runtime::HookResult {
                #(#calls)*
                Ok(())
            }
        }
    }
}

/// Generate a `PreDestruct` impl if there are `#[pre_destruct]` hooks.
///
/// The trait's `pre_destruct` method returns `HookResult`.
/// Same adaptation logic as `PostConstruct`.
fn generate_pre_destruct_impl(type_name: &syn::Ident, hooks: &[HookInfo]) -> TokenStream {
    if hooks.is_empty() {
        return quote! {};
    }

    let calls: Vec<TokenStream> = hooks
        .iter()
        .map(|hook| {
            let hook_name = &hook.method_name;
            let await_token = if hook.is_async {
                quote! { .await }
            } else {
                quote! {}
            };

            if hook.returns_result {
                // User's method returns Result — use ? to convert to HookResult
                quote! {
                    self.#hook_name()#await_token.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
                }
            } else {
                // User's method returns () — just call it
                quote! {
                    self.#hook_name()#await_token;
                }
            }
        })
        .collect();

    quote! {
        #[async_trait::async_trait]
        impl injectable_rs_runtime::PreDestruct for #type_name {
            async fn pre_destruct(&self) -> injectable_rs_runtime::HookResult {
                #(#calls)*
                Ok(())
            }
        }
    }
}

/// Generate an `InjectableHooksEntry` inventory submit for `#[injectable]`
/// blocks that have NO `#[injectable_ctor]`.
///
/// Called from the no-constructor path of `expand_injectable_impl`. Submits a
/// type-erased entry so the field-injection provider (generated by
/// `#[injectable]`) can call these hooks at runtime without any extra
/// struct annotation.
fn generate_hooks_entry_submit(
    type_name: &syn::Ident,
    post_hooks: &[HookInfo],
    pre_hooks: &[HookInfo],
) -> TokenStream {
    if post_hooks.is_empty() && pre_hooks.is_empty() {
        return quote! {};
    }

    let post_fn_name = syn::Ident::new(
        &format!("__injectable_impl_post_{}", type_name),
        proc_macro2::Span::call_site(),
    );
    let pre_fn_name = syn::Ident::new(
        &format!("__injectable_impl_make_pre_{}", type_name),
        proc_macro2::Span::call_site(),
    );
    let pre_adapter_name = syn::Ident::new(
        &format!("__InjectableImplPreDestruct_{}", type_name),
        proc_macro2::Span::call_site(),
    );

    // Build the post_construct wrapper (calls all #[post_construct] methods in order).
    let post_part = if !post_hooks.is_empty() {
        let hook_calls: Vec<TokenStream> = post_hooks.iter().map(|hook| {
            let method = &hook.method_name;
            let await_tok = if hook.is_async { quote! { .await } } else { quote! {} };
            if hook.returns_result {
                quote! {
                    instance.#method()#await_tok.map_err(|e|
                        Box::new(e) as Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync>
                    )?;
                }
            } else {
                quote! { instance.#method()#await_tok; }
            }
        }).collect();

        quote! {
            #[doc(hidden)]
            #[allow(non_snake_case)]
            fn #post_fn_name(
                arc: ::std::sync::Arc<dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync>,
            ) -> ::std::pin::Pin<Box<dyn ::std::future::Future<
                Output = injectable_rs_runtime::HookResult
            > + ::std::marker::Send + 'static>> {
                // Use Arc::downcast to get an owned Arc<T> (avoids self-referential borrows
                // in the async block and eliminates the need for T: Clone).
                let typed = ::std::sync::Arc::downcast::<#type_name>(arc)
                    .expect("InjectableHooksEntry TypeId guarantees correct type");
                Box::pin(async move {
                    let instance: &_ = &*typed;
                    #(#hook_calls)*
                    Ok(())
                })
            }
        }
    } else {
        quote! {}
    };

    // Build the pre_destruct adapter (calls all #[pre_destruct] methods in order).
    let pre_part = if !pre_hooks.is_empty() {
        let hook_calls: Vec<TokenStream> = pre_hooks.iter().map(|hook| {
            let method = &hook.method_name;
            let await_tok = if hook.is_async { quote! { .await } } else { quote! {} };
            if hook.returns_result {
                quote! {
                    instance.#method()#await_tok.map_err(|e|
                        Box::new(e) as Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync>
                    )?;
                }
            } else {
                quote! { instance.#method()#await_tok; }
            }
        }).collect();

        quote! {
            #[doc(hidden)]
            #[allow(non_camel_case_types)]
            struct #pre_adapter_name(
                ::std::sync::Arc<dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync>
            );

            #[async_trait::async_trait]
            impl injectable_rs_runtime::PreDestruct for #pre_adapter_name {
                async fn pre_destruct(&self) -> injectable_rs_runtime::HookResult {
                    // Clone the Arc before downcasting (we keep self.0 for potential
                    // multiple pre_destruct calls, though in practice it's called once).
                    let typed = ::std::sync::Arc::downcast::<#type_name>(
                        ::std::sync::Arc::clone(&self.0)
                    ).expect("InjectableHooksEntry TypeId guarantees correct type");
                    let instance: &_ = &*typed;
                    #(#hook_calls)*
                    Ok(())
                }
            }

            #[doc(hidden)]
            #[allow(non_snake_case)]
            fn #pre_fn_name(
                arc: ::std::sync::Arc<dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync>,
            ) -> ::std::sync::Arc<dyn injectable_rs_runtime::PreDestruct> {
                ::std::sync::Arc::new(#pre_adapter_name(arc))
            }
        }
    } else {
        quote! {}
    };

    let post_fn_ref = if !post_hooks.is_empty() {
        quote! { Some(#post_fn_name as injectable_rs_runtime::PostConstructFnPtr) }
    } else {
        quote! { None }
    };
    let pre_fn_ref = if !pre_hooks.is_empty() {
        quote! { Some(#pre_fn_name as injectable_rs_runtime::MakePreDestructFnPtr) }
    } else {
        quote! { None }
    };

    quote! {
        #post_part
        #pre_part

        injectable_rs_runtime::inventory::submit! {
            injectable_rs_runtime::InjectableHooksEntry::new_const(
                || ::std::any::TypeId::of::<#type_name>(),
                #post_fn_ref,
                #pre_fn_ref,
            )
        }
    }
}

/// Generate graph node metadata for dependency validation.
///
/// Generates an `inventory::submit!` call that registers this type's
/// `GraphNode` for automatic collection at container build time.
fn generate_graph_metadata(
    type_name: &syn::Ident,
    dependencies: &[String],
    scope: &str,
) -> TokenStream {
    let type_str = type_name.to_string();

    if dependencies.is_empty() {
        quote! {
            inventory::submit! {
                injectable_rs_graph::GraphNode::leaf_with_scope(
                    #type_str,
                    #scope,
                )
            }
        }
    } else {
        let dep_literals: Vec<_> = dependencies
            .iter()
            .map(|d| {
                let d: &str = d;
                quote! { #d }
            })
            .collect();

        let dep_const_name = syn::Ident::new(
            &format!(
                "__INJECTABLE_GRAPH_DEPS_{}",
                type_name.to_string().to_uppercase()
            ),
            proc_macro2::Span::call_site(),
        );

        quote! {
            #[allow(dead_code)]
            const #dep_const_name: &[&str] = &[#(#dep_literals),*];

            inventory::submit! {
                injectable_rs_graph::GraphNode::with_scope(
                    #type_str,
                    #dep_const_name,
                    #scope,
                )
            }
        }
    }
}