elif-http-derive 0.2.11

Derive macros for elif-http declarative routing and controller system
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
//! Module system macro implementation
//!
//! Provides comprehensive macros for defining dependency injection modules:
//!
//! ## Macros
//!
//! - `#[module(...)]`: Define modules with providers, controllers, imports, exports
//! - `module_composition!`: Compose multiple modules into applications  
//! - `demo_module!`: Laravel-style simplified syntax for rapid development
//!
//! ## Features
//!
//! - **Provider definitions**: Concrete services and trait mappings
//! - **Controller registration**: Automatic dependency injection for controllers
//! - **Module composition**: Import/export system for module dependencies
//! - **Compile-time validation**: Type-safe dependency resolution
//! - **IDE support**: Full rust-analyzer integration with autocompletion
//!
//! ## Examples
//!
//! ```rust,ignore
//! use elif_http_derive::{module, demo_module};
//!
//! // Mock services for examples
//! #[derive(Default)]
//! pub struct UserService;
//! #[derive(Default)]
//! pub struct SmtpEmailService;
//! #[derive(Default)]
//! pub struct UserController;
//!
//! // Full syntax - concrete providers only
//! #[module(
//!     providers: [UserService, SmtpEmailService],
//!     controllers: [UserController],
//!     exports: [UserService, SmtpEmailService]
//! )]
//! pub struct UserModule;
//!
//! // Demo DSL syntax  
//! let simple_module = demo_module! {
//!     services: [UserService, SmtpEmailService],
//!     controllers: [UserController],
//!     middleware: ["cors", "auth"]
//! };
//! ```

use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use syn::{
    parse::{Parse, ParseStream, Result},
    parse_macro_input,
    punctuated::Punctuated,
    token::{At, Comma, FatArrow},
    Error, ItemStruct, LitStr, Token, Type,
};

/// Main implementation function for the module attribute macro
pub fn module_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    let module_args = match syn::parse::<ModuleArgs>(args) {
        Ok(args) => args,
        Err(err) => return err.to_compile_error().into(),
    };

    let mut item_struct = parse_macro_input!(input as ItemStruct);

    match process_module_attribute(&mut item_struct, module_args) {
        Ok(result) => result.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Main implementation function for the module function-like macro
pub fn module_composition_impl(input: TokenStream) -> TokenStream {
    let composition_args = match syn::parse::<ModuleCompositionArgs>(input) {
        Ok(args) => args,
        Err(err) => return err.to_compile_error().into(),
    };

    match generate_application_composition(composition_args) {
        Ok(result) => result.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Demo DSL sugar syntax implementation
/// Supports Laravel-style simplified syntax for common cases:
/// ```rust,ignore
/// use elif_http_derive::demo_module;
///
/// // Mock services
/// #[derive(Default)]
/// pub struct UserService;
/// #[derive(Default)] 
/// pub struct EmailService;
/// #[derive(Default)]
/// pub struct UserController;
/// #[derive(Default)]
/// pub struct PostController;
///
/// let module_descriptor = demo_module! {
///     services: [UserService, EmailService],
///     controllers: [UserController, PostController],
///     middleware: ["cors", "logging"]
/// };
/// ```
pub fn demo_dsl_impl(input: TokenStream) -> TokenStream {
    let demo_args = match syn::parse::<DemoDslArgs>(input) {
        Ok(args) => args,
        Err(err) => return err.to_compile_error().into(),
    };

    match generate_demo_dsl_expansion(demo_args) {
        Ok(result) => result.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Arguments parsed from the #[module(...)] attribute
#[derive(Debug, Clone)]
pub struct ModuleArgs {
    pub providers: Vec<ProviderDef>,
    pub controllers: Vec<Type>,
    pub imports: Vec<Type>,
    pub exports: Vec<Type>,
    pub is_app_module: bool,
}

impl Parse for ModuleArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut providers = Vec::new();
        let mut controllers = Vec::new();
        let mut imports = Vec::new();
        let mut exports = Vec::new();
        let mut is_app_module = false;

        // Parse comma-separated key-value pairs
        while !input.is_empty() {
            let key: Ident = input.parse()?;
            let key_str = key.to_string();
            
            // Check if this is is_app flag without colon
            if key_str == "is_app" && !input.peek(Token![:]) {
                is_app_module = true;
            } else {
                let _colon: Token![:] = input.parse()?;
                match key_str.as_str() {
                "providers" => {
                    providers = parse_provider_list(input)?;
                }
                "controllers" => {
                    controllers = parse_type_list(input)?;
                }
                "imports" => {
                    imports = parse_type_list(input)?;
                }
                "exports" => {
                    exports = parse_type_list(input)?;
                }
                _ => {
                    return Err(Error::new_spanned(
                        key,
                        format!(
                            "Unknown module section '{}'. Valid sections are: providers, controllers, imports, exports, is_app.\n\
                            \n\
                            💡 Suggestions:\n\
                            • Use 'providers: [ServiceType]' for concrete services\n\
                            • Use 'providers: [dyn Trait => Implementation]' for trait mappings\n\
                            • Use 'controllers: [ControllerType]' for HTTP controllers\n\
                            • Use 'imports: [ModuleType]' for module dependencies\n\
                            • Use 'exports: [ServiceType]' for services available to other modules\n\
                            • Use 'is_app' (without colon) to mark this module as an app module that can bootstrap\n\
                            \n\
                            📖 See: https://docs.elif.rs/modules/module-definition",
                            key_str
                        )
                    ));
                }
            }
            }

            // Optional comma between sections
            if !input.is_empty() {
                let _comma: Option<Comma> = input.parse().ok();
            }
        }

        Ok(ModuleArgs {
            providers,
            controllers,
            imports,
            exports,
            is_app_module,
        })
    }
}

/// Definition of a provider in the module
/// Supports various patterns:
/// - `UserService` (concrete service)
/// - `EmailService => SmtpEmailService` (trait mapping)
/// - `EmailService => SmtpEmailService @ "smtp"` (named trait mapping)
/// - `dyn EmailService => SmtpEmailService` (explicit dyn syntax still supported)
#[derive(Debug, Clone)]
pub struct ProviderDef {
    pub service_type: ProviderType,
    pub implementation: Option<Type>,
    pub name: Option<String>,
}

#[derive(Debug, Clone)]
pub enum ProviderType {
    /// Concrete service type: UserService
    Concrete(Type),
    /// Trait type: dyn EmailService
    Trait(Type),
}

impl Parse for ProviderDef {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse the service type (may be dyn Trait, bare Trait, or concrete type)
        let service_type = if input.peek(Token![dyn]) {
            // Explicit dyn Trait syntax
            let _dyn: Token![dyn] = input.parse()?;
            let trait_type: Type = input.parse()?;
            ProviderType::Trait(trait_type)
        } else {
            let parsed_type: Type = input.parse()?;

            // Check if this will be followed by => (trait mapping)
            if input.peek(FatArrow) {
                // If there's a =>, it's a trait mapping, so treat as trait
                ProviderType::Trait(parsed_type)
            } else {
                // No =>, so it's a concrete service
                ProviderType::Concrete(parsed_type)
            }
        };

        let mut implementation = None;
        let mut name = None;

        // Check for trait mapping: => Implementation
        if input.peek(FatArrow) {
            let _arrow: FatArrow = input.parse()?;
            implementation = Some(input.parse()?);

            // Check for named mapping: @ "name"
            if input.peek(At) {
                let _at: At = input.parse()?;
                let name_lit: LitStr = input.parse()?;
                name = Some(name_lit.value());
            }
        }

        Ok(ProviderDef {
            service_type,
            implementation,
            name,
        })
    }
}

/// Parse a list of providers: [Provider1, dyn Trait => Impl, ...]
fn parse_provider_list(input: ParseStream) -> Result<Vec<ProviderDef>> {
    let content;
    let _bracket = syn::bracketed!(content in input);
    let providers: Punctuated<ProviderDef, Comma> =
        content.parse_terminated(ProviderDef::parse, Comma)?;
    Ok(providers.into_iter().collect())
}

/// Parse a list of types: [Type1, Type2, ...]
fn parse_type_list(input: ParseStream) -> Result<Vec<Type>> {
    let content;
    let _bracket = syn::bracketed!(content in input);
    let types: Punctuated<Type, Comma> = content.parse_terminated(Type::parse, Comma)?;
    Ok(types.into_iter().collect())
}

/// Parse a list of strings: ["string1", "string2", ...]
fn parse_string_list(input: ParseStream) -> Result<Vec<String>> {
    let content;
    let _bracket = syn::bracketed!(content in input);
    let strings: Punctuated<LitStr, Comma> =
        content.parse_terminated(|input| input.parse::<LitStr>(), Comma)?;
    Ok(strings.into_iter().map(|s| s.value()).collect())
}

/// Arguments for module composition macro: module! { ... }
#[derive(Debug, Clone)]
pub struct ModuleCompositionArgs {
    pub modules: Vec<Type>,
    pub overrides: Vec<ProviderDef>,
}

/// Arguments for demo DSL sugar syntax: module! { ... }
/// Supports Laravel-style simplified syntax
#[derive(Debug, Clone, Default)]
pub struct DemoDslArgs {
    pub services: Vec<Type>,
    pub controllers: Vec<Type>,
    pub middleware: Vec<String>,
}

impl Parse for ModuleCompositionArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut modules = Vec::new();
        let mut overrides = Vec::new();

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            let _colon: Token![:] = input.parse()?;

            let key_str = key.to_string();
            match key_str.as_str() {
                "modules" => {
                    modules = parse_type_list(input)?;
                }
                "overrides" => {
                    overrides = parse_provider_list(input)?;
                }
                _ => {
                    return Err(Error::new_spanned(
                        key,
                        format!(
                            "Unknown composition section '{}'. Valid sections are: modules, overrides.\n\
                            \n\
                            💡 Suggestions:\n\
                            • Use 'modules: [ModuleType1, ModuleType2]' to compose multiple modules\n\
                            • Use 'overrides: [Service => Implementation]' to override module bindings\n\
                            \n\
                            📖 Example:\n\
                            module_composition! {{\n\
                                modules: [UserModule, AuthModule],\n\
                                overrides: [dyn EmailService => MockEmailService @ \"test\"]\n\
                            }}\n\
                            \n\
                            📖 See: https://docs.elif.rs/modules/application-composition",
                            key_str
                        )
                    ));
                }
            }

            if !input.is_empty() {
                let _comma: Option<Comma> = input.parse().ok();
            }
        }

        if modules.is_empty() {
            return Err(Error::new(
                Span::call_site(),
                "module! composition requires at least one module in the 'modules' section",
            ));
        }

        Ok(ModuleCompositionArgs { modules, overrides })
    }
}

impl Parse for DemoDslArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut services = Vec::new();
        let mut controllers = Vec::new();
        let mut middleware = Vec::new();

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            let _colon: Token![:] = input.parse()?;

            let key_str = key.to_string();
            match key_str.as_str() {
                "services" => {
                    services = parse_type_list(input)?;
                }
                "controllers" => {
                    controllers = parse_type_list(input)?;
                }
                "middleware" => {
                    middleware = parse_string_list(input)?;
                }
                _ => {
                    return Err(Error::new_spanned(
                        key,
                        format!(
                            "Unknown demo DSL section '{}'. Valid sections are: services, controllers, middleware.\n\
                            \n\
                            💡 Demo DSL Suggestions:\n\
                            • Use 'services: [ServiceType1, ServiceType2]' for concrete services\n\
                            • Use 'controllers: [ControllerType1, ControllerType2]' for HTTP controllers\n\
                            • Use 'middleware: [\"cors\", \"auth\", \"logging\"]' for middleware stack\n\
                            \n\
                            📖 Example:\n\
                            demo_module! {{\n\
                                services: [UserService, EmailService],\n\
                                controllers: [UserController],\n\
                                middleware: [\"cors\", \"auth\"]\n\
                            }}\n\
                            \n\
                            ⚠️ Note: Demo DSL is simplified syntax. For trait mappings and imports/exports,\n\
                            use the full #[module(...)] attribute syntax instead.\n\
                            \n\
                            📖 See: https://docs.elif.rs/modules/demo-dsl-guide",
                            key_str
                        )
                    ));
                }
            }

            if !input.is_empty() {
                let _comma: Option<Comma> = input.parse().ok();
            }
        }

        Ok(DemoDslArgs {
            services,
            controllers,
            middleware,
        })
    }
}

/// Process the module attribute and generate module registration code
fn process_module_attribute(
    item_struct: &mut ItemStruct,
    module_args: ModuleArgs,
) -> Result<proc_macro2::TokenStream> {
    let struct_name = &item_struct.ident;

    // Generate module descriptor method
    let module_descriptor_impl = generate_module_descriptor_method(struct_name, &module_args)?;
    
    // Generate AppBootstrap implementation if this is an app module
    let app_bootstrap_impl = if module_args.is_app_module {
        generate_app_bootstrap_impl(struct_name, &module_args)?
    } else {
        quote! {}
    };

    Ok(quote! {
        #item_struct

        #module_descriptor_impl
        
        #app_bootstrap_impl
    })
}

/// Generate module descriptor method for runtime registration
fn generate_module_descriptor_method(
    struct_name: &Ident,
    module_args: &ModuleArgs,
) -> Result<proc_macro2::TokenStream> {
    let providers_code = generate_providers_descriptors(&module_args.providers)?;
    let controllers_code = generate_controllers_descriptors(&module_args.controllers)?;
    let imports_list = generate_imports_list(&module_args.imports)?;
    let exports_list = generate_exports_list(&module_args.exports)?;
    let auto_configure_code = generate_auto_configure_function(struct_name, module_args)?;
    let registry_registration_code = generate_registry_registration_code(struct_name, module_args)?;

    Ok(quote! {
        impl #struct_name {
            /// Get the module descriptor for this module
            pub fn module_descriptor() -> elif_core::modules::ModuleDescriptor {
                use elif_core::modules::{ModuleDescriptor, ServiceDescriptor, ControllerDescriptor, ServiceLifecycle};
                use std::any::TypeId;

                let mut descriptor = ModuleDescriptor::new(stringify!(#struct_name));

                // Add providers
                #providers_code

                // Add controllers
                #controllers_code

                // Set imports and exports
                descriptor = descriptor
                    .with_imports(#imports_list)
                    .with_exports(#exports_list);

                descriptor
            }
        }

        impl elif_core::modules::ModuleAutoConfiguration for #struct_name {
            fn module_descriptor() -> elif_core::modules::ModuleDescriptor {
                Self::module_descriptor()
            }

            fn auto_configure(container: &mut elif_core::container::IocContainer) -> Result<(), elif_core::modules::ModuleError> {
                #auto_configure_code
            }
        }

        // Auto-register this module in the global registry 
        #registry_registration_code
    })
}

/// Generate provider descriptors for module descriptor creation
fn generate_providers_descriptors(providers: &[ProviderDef]) -> Result<proc_macro2::TokenStream> {
    if providers.is_empty() {
        return Ok(quote! {
            // No providers specified
        });
    }

    let mut descriptor_calls = Vec::new();

    for provider in providers {
        let descriptor_call = match &provider.service_type {
            ProviderType::Concrete(service_type) => match &provider.name {
                Some(name) => {
                    quote! {
                        descriptor = descriptor.with_provider(
                            ServiceDescriptor::new::<#service_type>(stringify!(#service_type), ServiceLifecycle::default())
                                .with_name(#name)
                        );
                    }
                }
                None => {
                    quote! {
                        descriptor = descriptor.with_provider(
                            ServiceDescriptor::new::<#service_type>(stringify!(#service_type), ServiceLifecycle::default())
                        );
                    }
                }
            },
            ProviderType::Trait(trait_type) => match &provider.implementation {
                Some(impl_type) => match &provider.name {
                    Some(name) => {
                        quote! {
                            descriptor = descriptor.with_provider(
                                ServiceDescriptor::trait_mapping::<#trait_type, #impl_type>(
                                    stringify!(#trait_type), stringify!(#impl_type), ServiceLifecycle::default()
                                ).with_name(#name)
                            );
                        }
                    }
                    None => {
                        quote! {
                            descriptor = descriptor.with_provider(
                                ServiceDescriptor::trait_mapping::<#trait_type, #impl_type>(
                                    stringify!(#trait_type), stringify!(#impl_type), ServiceLifecycle::default()
                                )
                            );
                        }
                    }
                },
                None => {
                    return Err(Error::new_spanned(
                            trait_type,
                            "Trait providers must specify implementation type: dyn Trait => Implementation.\n\
                            \n\
                            💡 Suggestions:\n\
                            • Use 'dyn EmailService => SmtpEmailService' for trait mapping\n\
                            • Use 'dyn EmailService => SmtpEmailService @ \"smtp\"' for named mapping\n\
                            • Use 'EmailService => SmtpEmailService' (dyn is optional in simplified syntax)\n\
                            \n\
                            📖 Examples:\n\
                            #[module(\n\
                                providers: [\n\
                                    UserService,  // Concrete service\n\
                                    dyn EmailService => SmtpEmailService,  // Trait mapping\n\
                                    dyn EmailService => MockEmailService @ \"test\"  // Named mapping\n\
                                ]\n\
                            )]\n\
                            \n\
                            📖 See: https://docs.elif.rs/modules/dependency-injection"
                        ));
                }
            },
        };

        descriptor_calls.push(descriptor_call);
    }

    Ok(quote! {
        #(#descriptor_calls)*
    })
}

/// Generate controller descriptors for module descriptor creation
fn generate_controllers_descriptors(controllers: &[Type]) -> Result<proc_macro2::TokenStream> {
    if controllers.is_empty() {
        return Ok(quote! {
            // No controllers specified
        });
    }

    let descriptor_calls: Vec<_> = controllers
        .iter()
        .map(|controller| {
            quote! {
                descriptor = descriptor.with_controller(
                    ControllerDescriptor::new::<#controller>(stringify!(#controller))
                );
            }
        })
        .collect();

    Ok(quote! {
        #(#descriptor_calls)*
    })
}

/// Generate imports list for module descriptor
fn generate_imports_list(imports: &[Type]) -> Result<proc_macro2::TokenStream> {
    if imports.is_empty() {
        return Ok(quote! { vec![] });
    }

    let import_strings: Vec<_> = imports
        .iter()
        .map(|import| {
            quote! { stringify!(#import).to_string() }
        })
        .collect();

    Ok(quote! {
        vec![#(#import_strings),*]
    })
}

/// Generate exports list for module descriptor
fn generate_exports_list(exports: &[Type]) -> Result<proc_macro2::TokenStream> {
    if exports.is_empty() {
        return Ok(quote! { vec![] });
    }

    let export_strings: Vec<_> = exports
        .iter()
        .map(|export| {
            quote! { stringify!(#export).to_string() }
        })
        .collect();

    Ok(quote! {
        vec![#(#export_strings),*]
    })
}

/// Generate code to register module in the global registry
fn generate_registry_registration_code(
    struct_name: &Ident,
    module_args: &ModuleArgs,
) -> Result<proc_macro2::TokenStream> {
    // Extract controller names as strings for logging
    let controller_names: Vec<String> = module_args.controllers
        .iter()
        .map(|controller| controller.to_token_stream().to_string())
        .collect();

    // Extract provider names as strings for logging
    let provider_names: Vec<String> = module_args.providers
        .iter()
        .map(|provider| match &provider.service_type {
            ProviderType::Concrete(service_type) => service_type.to_token_stream().to_string(),
            ProviderType::Trait(trait_type) => {
                if let Some(impl_type) = &provider.implementation {
                    impl_type.to_token_stream().to_string()
                } else {
                    trait_type.to_token_stream().to_string()
                }
            }
        })
        .collect();

    // Extract import names as strings for logging
    let import_names: Vec<String> = module_args.imports
        .iter()
        .map(|import| import.to_token_stream().to_string())
        .collect();

    // Extract export names as strings for logging
    let export_names: Vec<String> = module_args.exports
        .iter()
        .map(|export| export.to_token_stream().to_string())
        .collect();



    Ok(quote! {
        // Generate registration code that runs when module is first referenced
        impl #struct_name {
            pub fn ensure_registered() {
                use elif_core::modules::{CompileTimeModuleMetadata, register_module_globally};
                static REGISTER_MODULE: std::sync::Once = std::sync::Once::new();
                
                REGISTER_MODULE.call_once(|| {
                    let metadata = CompileTimeModuleMetadata::new(stringify!(#struct_name).to_string())
                        .with_controllers(vec![#(#controller_names.to_string()),*])
                        .with_providers(vec![#(#provider_names.to_string()),*])
                        .with_imports(vec![#(#import_names.to_string()),*])
                        .with_exports(vec![#(#export_names.to_string()),*]);
                    
                    // Debug logging removed to fix type inference issues
                        
                    register_module_globally(metadata);
                });
            }
        }
        
        // Force registration by generating a constructor function with ctor
        #[::ctor::ctor]
        fn __register_module() {
            #struct_name::ensure_registered();
        }
    })
}

/// Generate auto-configure function for IoC container integration
fn generate_auto_configure_function(
    _struct_name: &Ident,
    module_args: &ModuleArgs,
) -> Result<proc_macro2::TokenStream> {
    let mut configure_calls = Vec::new();

    // First, configure imported modules (dependencies must be resolved first)
    for import in &module_args.imports {
        configure_calls.push(quote! {
            <#import as elif_core::modules::ModuleAutoConfiguration>::auto_configure(container)?;
        });
    }

    // Configure providers with lifecycle and dependency metadata
    for provider in &module_args.providers {
        let configure_call = match &provider.service_type {
            ProviderType::Concrete(service_type) => {
                match &provider.name {
                    Some(name) => {
                        quote! {
                            // Bind named concrete service with singleton scope by default
                            container.bind_named::<#service_type, #service_type>(#name);
                        }
                    }
                    None => {
                        quote! {
                            // Bind concrete service with singleton scope by default
                            container.bind::<#service_type, #service_type>();
                        }
                    }
                }
            }
            ProviderType::Trait(trait_type) => {
                if let Some(impl_type) = &provider.implementation {
                    match &provider.name {
                        Some(name) => {
                            // Generate a token type based on trait name
                            let _token_name = quote::format_ident!(
                                "{}Token",
                                trait_type.to_token_stream().to_string().replace(" ", "")
                            );
                            quote! {
                                // Bind trait implementation with token-based resolution (named)
                                // For now, we'll use direct concrete binding until token system is fully integrated
                                container.bind_named::<#impl_type, #impl_type>(#name);

                                // TODO: Once token system is integrated:
                                // struct #_token_name;
                                // impl ServiceToken for #_token_name { type Service = dyn #trait_type; }
                                // container.bind_token_named::<#_token_name, #impl_type>(#name)?;
                            }
                        }
                        None => {
                            let _token_name = quote::format_ident!(
                                "{}Token",
                                trait_type.to_token_stream().to_string().replace(" ", "")
                            );
                            quote! {
                                // Bind trait implementation with token-based resolution
                                // For now, we'll use direct concrete binding until token system is fully integrated
                                container.bind::<#impl_type, #impl_type>();

                                // TODO: Once token system is integrated:
                                // struct #_token_name;
                                // impl ServiceToken for #_token_name { type Service = dyn #trait_type; }
                                // container.bind_token::<#_token_name, #impl_type>()?;
                            }
                        }
                    }
                } else {
                    return Err(Error::new_spanned(
                        trait_type,
                        "Trait providers must specify implementation type: dyn Trait => Implementation"
                    ));
                }
            }
        };

        configure_calls.push(configure_call);
    }

    // Configure controllers with dependency injection
    for controller in &module_args.controllers {
        configure_calls.push(quote! {
            // Bind controller as singleton for injection
            container.bind::<#controller, #controller>();
        });
    }

    Ok(quote! {
        use elif_core::modules::{ModuleError, ModuleAutoConfiguration};
        use elif_core::container::ServiceBinder; // Import the binding trait

        // Build container if not already built to enable binding
        if !container.is_built() {
            // We need to defer building until all modules are configured
            // The container will be built by the application after all modules are registered
        }

        #(#configure_calls)*

        Ok(())
    })
}

/// Generate application composition code
fn generate_application_composition(
    composition_args: ModuleCompositionArgs,
) -> Result<proc_macro2::TokenStream> {
    let modules_descriptors = generate_modules_descriptors(&composition_args.modules)?;
    let overrides_descriptors = generate_composition_overrides(&composition_args.overrides)?;

    Ok(quote! {
        {
            use elif_core::modules::{ModuleComposition, ModuleDescriptor, ServiceDescriptor};

            let mut composition = ModuleComposition::new();

            // Add modules to composition
            #modules_descriptors

            // Add overrides
            #overrides_descriptors

            // Compose and return the final descriptor
            composition.compose().unwrap()
        }
    })
}

/// Generate module descriptors for application composition
fn generate_modules_descriptors(modules: &[Type]) -> Result<proc_macro2::TokenStream> {
    if modules.is_empty() {
        return Ok(quote! {
            // No modules specified
        });
    }

    let descriptor_calls: Vec<_> = modules
        .iter()
        .map(|module| {
            quote! {
                composition = composition.with_module(#module::module_descriptor());
            }
        })
        .collect();

    Ok(quote! {
        #(#descriptor_calls)*
    })
}

/// Generate override descriptors for application composition
fn generate_composition_overrides(overrides: &[ProviderDef]) -> Result<proc_macro2::TokenStream> {
    if overrides.is_empty() {
        return Ok(quote! {
            // No overrides specified
        });
    }

    let mut override_descriptors = Vec::new();

    for override_def in overrides {
        let override_descriptor = match &override_def.service_type {
            ProviderType::Concrete(service_type) => {
                let service_name = quote! { stringify!(#service_type) }.to_string();
                match &override_def.name {
                    Some(name) => {
                        quote! {
                            ServiceDescriptor::new::<#service_type>(#service_name, ServiceLifecycle::default())
                                .with_name(#name)
                        }
                    }
                    None => {
                        quote! {
                            ServiceDescriptor::new::<#service_type>(#service_name, ServiceLifecycle::default())
                        }
                    }
                }
            }
            ProviderType::Trait(trait_type) => {
                if let Some(impl_type) = &override_def.implementation {
                    let service_name = quote! { stringify!(#trait_type) }.to_string();
                    let impl_name = quote! { stringify!(#impl_type) }.to_string();
                    match &override_def.name {
                        Some(name) => {
                            quote! {
                                ServiceDescriptor::trait_mapping::<#trait_type, #impl_type>(
                                    #service_name, #impl_name, ServiceLifecycle::default()
                                ).with_name(#name)
                            }
                        }
                        None => {
                            quote! {
                                ServiceDescriptor::trait_mapping::<#trait_type, #impl_type>(
                                    #service_name, #impl_name, ServiceLifecycle::default()
                                )
                            }
                        }
                    }
                } else {
                    return Err(Error::new_spanned(
                        trait_type,
                        "Trait overrides must specify implementation type: dyn Trait => Implementation"
                    ));
                }
            }
        };

        override_descriptors.push(override_descriptor);
    }

    Ok(quote! {
        use elif_core::modules::ServiceLifecycle;

        let overrides = vec![
            #(#override_descriptors),*
        ];
        composition = composition.with_overrides(overrides);
    })
}

/// Generate AppBootstrap implementation for app modules
fn generate_app_bootstrap_impl(struct_name: &Ident, module_args: &ModuleArgs) -> Result<proc_macro2::TokenStream> {
    // Generate references to ensure imported modules are included in the binary
    let import_references: Vec<_> = module_args.imports
        .iter()
        .map(|import| {
            quote! { 
                // Ensure the module type is referenced so it gets included in the binary
                let _ = std::marker::PhantomData::<#import>;
                #import::ensure_registered(); 
            }
        })
        .collect();

    Ok(quote! {
        impl elif_http::AppBootstrap for #struct_name {
            fn bootstrap() -> elif_http::BootstrapResult<elif_http::AppBootstrapper> {
                println!("🚀 AppModule::bootstrap() called for {}", stringify!(#struct_name));
                
                // Ensure all imported modules are registered first
                #(#import_references)*
                
                // Ensure this module is registered last
                Self::ensure_registered();
                
                println!("📋 Module registration completed for {}", stringify!(#struct_name));
                
                elif_http::AppBootstrapper::new()
            }
        }
        
        impl #struct_name {
            fn force_module_inclusion() {
                // This method forces the module to be included in the binary
                // by creating a reference that the compiler cannot optimize away
                Self::ensure_registered();
            }
        }
    })
}

/// Generate expanded code for demo DSL sugar syntax
/// Converts simplified syntax to full #[module(...)] form
fn generate_demo_dsl_expansion(demo_args: DemoDslArgs) -> Result<proc_macro2::TokenStream> {
    // Convert services to providers (concrete services)
    let providers: Vec<ProviderDef> = demo_args
        .services
        .into_iter()
        .map(|service| ProviderDef {
            service_type: ProviderType::Concrete(service),
            implementation: None,
            name: None,
        })
        .collect();

    // Create a module descriptor with the expanded providers
    let module_args = ModuleArgs {
        providers,
        controllers: demo_args.controllers,
        imports: Vec::new(), // Demo DSL doesn't support imports yet
        exports: Vec::new(), // Demo DSL doesn't support exports yet
        is_app_module: false, // Demo DSL modules are not app modules
    };

    // Generate a temporary struct name for the module
    let struct_name = Ident::new("DemoDslModule", Span::call_site());

    let module_descriptor_impl = generate_module_descriptor_method(&struct_name, &module_args)?;

    // Generate middleware application code (simplified for demo)
    let middleware_code = if demo_args.middleware.is_empty() {
        quote! { /* No middleware specified */ }
    } else {
        let middleware_names = &demo_args.middleware;
        quote! {
            // Demo DSL middleware (simplified - would integrate with elif-http middleware system)
            let middleware_stack = vec![#(#middleware_names.to_string()),*];
            println!("Demo DSL: Would apply middleware: {:?}", middleware_stack);
        }
    };

    Ok(quote! {
        {
            // Generate a temporary module struct for the demo DSL
            struct #struct_name;

            #module_descriptor_impl

            // Create the module descriptor
            let descriptor = #struct_name::module_descriptor();

            // Apply middleware (demo implementation)
            #middleware_code

            // Return the descriptor for use in applications
            descriptor
        }
    })
}