Skip to main content

rustf_macros/
lib.rs

1//! RustF Macros - Procedural macros for auto-discovery
2//!
3//! This crate provides build-time macros to automatically discover and include
4//! controllers and models without requiring manual mod.rs files.
5
6use proc_macro::TokenStream;
7use quote::quote;
8use std::path::PathBuf;
9use syn::{parse_macro_input, parse_quote, ItemFn};
10use walkdir::WalkDir;
11
12/// Auto-discover and include all controllers from src/controllers/*.rs
13///
14/// This macro scans the controllers directory at build time and generates
15/// the necessary module declarations and route aggregation code.
16///
17/// # Usage
18/// ```rust,ignore
19/// use rustf::prelude::*;
20///
21/// let routes = auto_controllers!();
22/// let app = RustF::new().controllers(routes);
23/// ```
24#[proc_macro]
25pub fn auto_controllers(_input: TokenStream) -> TokenStream {
26    generate_auto_discovery("controllers", "install").into()
27}
28
29/// Auto-discover and include all models from src/models/*.rs
30///
31/// This macro scans the models directory at build time and generates
32/// the necessary module declarations and model registration code.
33///
34/// # Usage
35/// ```rust,ignore
36/// use rustf::prelude::*;
37///
38/// let register_fn = auto_models!();
39/// let app = RustF::new().models(register_fn);
40/// ```
41#[proc_macro]
42pub fn auto_models(_input: TokenStream) -> TokenStream {
43    generate_auto_discovery("models", "register").into()
44}
45
46/// Auto-discover and include all middleware from src/middleware/*.rs
47///
48/// This macro scans the middleware directory at build time and generates
49/// the necessary module declarations and middleware registration code.
50///
51/// # Usage
52/// ```rust,ignore
53/// use rustf::prelude::*;
54///
55/// let register_fn = auto_middleware!();
56/// let app = RustF::new().middleware_from(register_fn);
57/// ```
58#[proc_macro]
59pub fn auto_middleware(_input: TokenStream) -> TokenStream {
60    generate_auto_discovery("middleware", "install").into()
61}
62
63/// Auto-discover and include all definitions from src/definitions/*.rs
64///
65/// This macro scans the definitions directory at build time and generates
66/// the necessary module declarations and registration code.
67/// Each file should implement either Helpers or Validators trait.
68///
69/// # Usage
70/// ```rust,ignore
71/// let app = RustF::new()
72///     .definitions_from(auto_definitions!());
73/// ```
74#[proc_macro]
75pub fn auto_definitions(_input: TokenStream) -> TokenStream {
76    generate_auto_discovery("definitions", "install").into()
77}
78
79/// Auto-discover and include all modules from src/modules/*.rs
80///
81/// This macro scans the modules directory at build time and generates
82/// the necessary module declarations and module registration code.
83/// Following Total.js inspiration, modules contain reusable business logic.
84///
85/// # Usage
86/// ```rust,ignore
87/// use rustf::prelude::*;
88///
89/// let register_fn = auto_modules!();
90/// let app = RustF::new().modules_from(register_fn);
91/// ```
92#[proc_macro]
93pub fn auto_modules(_input: TokenStream) -> TokenStream {
94    generate_auto_discovery("modules", "install").into()
95}
96
97/// Auto-discover and include all event handlers from src/events/*.rs
98///
99/// This macro scans the events directory at build time and generates
100/// the necessary module declarations and event handler registration code.
101///
102/// # Usage
103/// ```rust,ignore
104/// use rustf::prelude::*;
105///
106/// let register_fn = auto_events!();
107/// let app = RustF::new().events_from(register_fn);
108/// ```
109#[proc_macro]
110pub fn auto_events(_input: TokenStream) -> TokenStream {
111    generate_auto_discovery("events", "install").into()
112}
113
114/// Auto-discover and include all workers from src/workers/*.rs
115///
116/// This macro scans the workers directory at build time and generates
117/// the necessary module declarations and worker registration code.
118/// Each file should have an async `install()` function that registers workers.
119///
120/// # Usage
121/// ```rust,ignore
122/// use rustf::prelude::*;
123///
124/// let app = RustF::new()
125///     .with_workers()
126///     .workers_from(auto_workers!());
127/// ```
128#[proc_macro]
129pub fn auto_workers(_input: TokenStream) -> TokenStream {
130    generate_worker_discovery().into()
131}
132
133/// Generate auto-discovery code for a given directory and function name
134fn generate_auto_discovery(dir_name: &str, fn_name: &str) -> proc_macro2::TokenStream {
135    let manifest_dir =
136        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");
137
138    let src_dir = PathBuf::from(&manifest_dir).join("src").join(dir_name);
139
140    // Check if we're in the rustf framework itself by looking for Cargo.toml [package] name
141    let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
142    let is_rustf_framework = if cargo_toml_path.exists() {
143        if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
144            contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
145        } else {
146            false
147        }
148    } else {
149        false
150    };
151
152    // If we're in the rustf framework itself, don't try to auto-discover framework internal modules
153    // Only auto-discover in user projects
154    let should_skip = is_rustf_framework
155        && matches!(
156            dir_name,
157            "models" | "workers" | "definitions" | "middleware" | "events"
158        );
159
160    if should_skip || !src_dir.exists() {
161        // If directory doesn't exist or we should skip it, return empty implementation
162        // Use correct path prefix based on whether we're in rustf framework or user project
163        let path_prefix = if is_rustf_framework {
164            quote! { crate }
165        } else {
166            quote! { rustf }
167        };
168
169        return match dir_name {
170            "controllers" => quote! {
171                {
172                    Vec::new()
173                }
174            },
175            "models" => quote! {
176                {
177                    |_registry: &mut #path_prefix::models::ModelRegistry| {
178                        // No models to register
179                    }
180                }
181            },
182            "middleware" => quote! {
183                {
184                    |_registry: &mut #path_prefix::middleware::MiddlewareRegistry| {
185                        // No middleware to register
186                    }
187                }
188            },
189            "events" => quote! {
190                {
191                    |_emitter: &mut #path_prefix::events::EventEmitter| {
192                        // No event handlers to register
193                    }
194                }
195            },
196            "definitions" => quote! {
197                {
198                    |_defs: &mut #path_prefix::definitions::Definitions| {
199                        // No definitions to register
200                    }
201                }
202            },
203            _ => quote! { compile_error!("Unknown directory type"); },
204        };
205    }
206
207    let mut modules = Vec::new();
208    let mut function_calls = Vec::new();
209
210    // Walk through all .rs files in the directory with max depth of 3
211    for entry in WalkDir::new(&src_dir)
212        .min_depth(1)
213        .max_depth(3) // Support up to 3 levels of nesting
214        .into_iter()
215        .filter_map(|e| e.ok())
216    {
217        let path = entry.path();
218
219        // Skip directories (we only want files)
220        if path.is_dir() {
221            continue;
222        }
223
224        // Skip if not a .rs file
225        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
226            continue;
227        }
228
229        // Skip mod.rs files if they exist
230        if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
231            continue;
232        }
233
234        // Skip .inc.rs files (included code fragments)
235        if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
236            if file_name.ends_with(".inc.rs") {
237                continue;
238            }
239            // Skip files starting with underscore
240            if file_name.starts_with("_") {
241                continue;
242            }
243        }
244
245        // Create the module path relative to the target directory
246        let relative_to_target = path
247            .strip_prefix(&src_dir)
248            .expect("Path should be under target directory");
249
250        // Build nested module path (e.g., api::v1::users for api/v1/users.rs)
251        let mut path_components = Vec::new();
252        for component in relative_to_target.components() {
253            if let std::path::Component::Normal(name) = component {
254                if let Some(name_str) = name.to_str() {
255                    // Remove .rs extension from the last component
256                    if name_str.ends_with(".rs") {
257                        path_components.push(name_str.trim_end_matches(".rs"));
258                    } else {
259                        path_components.push(name_str);
260                    }
261                }
262            }
263        }
264
265        // Create the full module path (e.g., "api::v1::users")
266        let _module_path = path_components.join("::");
267
268        // Generate unique module identifier for nested paths
269        let module_ident_str = path_components.join("_");
270        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
271
272        // Create relative path from the src directory (where main.rs is located)
273        let src_dir_base = PathBuf::from(&manifest_dir).join("src");
274        let relative_path = path
275            .strip_prefix(&src_dir_base)
276            .expect("Path should be under src directory")
277            .to_string_lossy()
278            .replace('\\', "/"); // Normalize path separators
279
280        // Generate module declaration with nested structure
281        if path_components.len() == 1 {
282            // Top-level module (e.g., controllers/home.rs)
283            let module_name = path_components[0];
284            let module_ident = syn::Ident::new(module_name, proc_macro2::Span::call_site());
285            modules.push(quote! {
286                #[path = #relative_path]
287                pub mod #module_ident;
288            });
289
290            // Generate function call using the simple identifier
291            match dir_name {
292                "controllers" => {
293                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
294                    function_calls.push(quote! {
295                        routes.extend(#module_ident::#fn_ident());
296                    });
297                }
298                "models" => {
299                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
300                    function_calls.push(quote! {
301                        #module_ident::#fn_ident(registry);
302                    });
303                }
304                "middleware" => {
305                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
306                    function_calls.push(quote! {
307                        #module_ident::#fn_ident(registry);
308                    });
309                }
310                "modules" => {
311                    // Modules are now discovered but NOT automatically registered
312                    // Developers must explicitly call MODULE::register() with a unique name
313                    // This allows multiple instances of the same type
314                    // (no code generation needed - just module declarations)
315                }
316                "events" => {
317                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
318                    function_calls.push(quote! {
319                        #module_ident::#fn_ident(emitter);
320                    });
321                }
322                "definitions" => {
323                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
324                    function_calls.push(quote! {
325                        #module_ident::#fn_ident(defs);
326                    });
327                }
328                "workers" => {
329                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
330                    function_calls.push(quote! {
331                        #module_ident::#fn_ident().await?;
332                    });
333                }
334                _ => {}
335            }
336        } else {
337            // Nested module (e.g., controllers/api/users.rs)
338            // We need to create nested module structure
339            modules.push(quote! {
340                #[path = #relative_path]
341                pub mod #module_ident;
342            });
343
344            // Generate function call with full module path
345            match dir_name {
346                "controllers" => {
347                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
348                    function_calls.push(quote! {
349                        routes.extend(#module_ident::#fn_ident());
350                    });
351                }
352                "models" => {
353                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
354                    function_calls.push(quote! {
355                        #module_ident::#fn_ident(registry);
356                    });
357                }
358                "middleware" => {
359                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
360                    function_calls.push(quote! {
361                        #module_ident::#fn_ident(registry);
362                    });
363                }
364                "modules" => {
365                    // Modules are now discovered but NOT automatically registered
366                    // Developers must explicitly call MODULE::register() with a unique name
367                    // This allows multiple instances of the same type
368                    // (no code generation needed - just module declarations)
369                }
370                "events" => {
371                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
372                    function_calls.push(quote! {
373                        #module_ident::#fn_ident(emitter);
374                    });
375                }
376                "definitions" => {
377                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
378                    function_calls.push(quote! {
379                        #module_ident::#fn_ident(defs);
380                    });
381                }
382                _ => {}
383            }
384        }
385    }
386
387    // Generate the final code based on directory type
388    // Use correct path prefix based on whether we're in rustf framework or user project
389    let path_prefix = if is_rustf_framework {
390        quote! { crate }
391    } else {
392        quote! { rustf }
393    };
394
395    match dir_name {
396        "controllers" => {
397            let controller_count = function_calls.len();
398            quote! {
399                {
400                    // Module declarations
401                    #(#modules)*
402
403                    log::info!("Auto-discovery: Loading {} controller(s)", #controller_count);
404
405                    // Function to collect all routes
406                    let mut routes = Vec::new();
407                    #(#function_calls)*
408                    routes
409                }
410            }
411        }
412        "models" => {
413            let model_count = function_calls.len();
414            quote! {
415                {
416                    // Module declarations
417                    #(#modules)*
418
419                    // Function to register all models
420                    |registry: &mut #path_prefix::models::ModelRegistry| {
421                        log::info!("Auto-discovery: Registering {} model(s)", #model_count);
422                        #(#function_calls)*
423                    }
424                }
425            }
426        }
427        "middleware" => {
428            let middleware_count = function_calls.len();
429            quote! {
430                {
431                    // Module declarations
432                    #(#modules)*
433
434                    // Function to register all middleware
435                    |registry: &mut #path_prefix::middleware::MiddlewareRegistry| {
436                        log::info!("Auto-discovery: Registering {} middleware", #middleware_count);
437                        #(#function_calls)*
438                    }
439                }
440            }
441        }
442        "modules" => {
443            quote! {
444                {
445                    // Module declarations (auto-discovery only)
446                    #(#modules)*
447
448                    log::info!("Auto-discovery: Found module(s) - explicit MODULE::register() required for registration");
449                    // Modules are no longer auto-registered. Developers must explicitly call
450                    // MODULE::register("unique-name", module_instance) with a unique name.
451                    // This enables multiple instances of the same type with different configs.
452                }
453            }
454        }
455        "events" => {
456            let event_count = function_calls.len();
457            quote! {
458                {
459                    // Module declarations
460                    #(#modules)*
461
462                    // Function to register all event handlers
463                    |emitter: &mut #path_prefix::events::EventEmitter| {
464                        log::info!("Auto-discovery: Registering {} event handler(s)", #event_count);
465                        #(#function_calls)*
466                    }
467                }
468            }
469        }
470        "definitions" => {
471            let definitions_count = function_calls.len();
472            quote! {
473                {
474                    // Module declarations
475                    #(#modules)*
476
477                    // Function to register all definitions
478                    |defs: &mut #path_prefix::definitions::Definitions| {
479                        log::info!("Auto-discovery: Registering {} definition(s)", #definitions_count);
480                        #(#function_calls)*
481                    }
482                }
483            }
484        }
485        _ => quote! { compile_error!("Unknown directory type"); },
486    }
487}
488
489/// Auto-discover and generate module declarations for the entire application
490///
491/// This attribute macro scans the filesystem at compile time and generates
492/// standard Rust module declarations for modules, controllers, and models.
493///
494/// # Usage
495/// ```rust,ignore
496/// use rustf::prelude::*;
497///
498/// #[rustf::auto_discover]
499/// #[tokio::main]
500/// async fn main() -> rustf::Result<()> {
501///     // Modules are now available via standard Rust module system
502///     let user_svc = modules::user_service::UserService::new();
503///
504///     let app = RustF::new()
505///         .controllers(auto_controllers!())
506///         .start().await
507/// }
508/// ```
509#[proc_macro_attribute]
510pub fn auto_discover(_args: TokenStream, input: TokenStream) -> TokenStream {
511    let mut input_fn = parse_macro_input!(input as ItemFn);
512
513    let manifest_dir =
514        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");
515    let src_dir = PathBuf::from(&manifest_dir).join("src");
516
517    // Generate module declarations for each directory
518    let modules_mod = generate_mod_declarations(&src_dir, "modules");
519    let controllers_mod = generate_mod_declarations(&src_dir, "controllers");
520    let models_mod = generate_mod_declarations(&src_dir, "models");
521    let middleware_mod = generate_mod_declarations(&src_dir, "middleware");
522    let events_mod = generate_mod_declarations(&src_dir, "events");
523    let definitions_mod = generate_mod_declarations(&src_dir, "definitions");
524
525    // Conditionally generate embedded provider structs + registrations
526    // Only when the embedded-views feature is active AND we're in a user project
527    #[cfg(feature = "embedded-views")]
528    let is_rustf_framework = {
529        let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
530        if cargo_toml_path.exists() {
531            if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
532                contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
533            } else {
534                false
535            }
536        } else {
537            false
538        }
539    };
540
541    #[cfg(feature = "embedded-views")]
542    let embedded_structs = if !is_rustf_framework {
543        let views_folder = format!("{}/views/", manifest_dir);
544        let assets_folder = format!("{}/public/", manifest_dir);
545        quote! {
546            // Auto-generated by #[auto_discover] — DO NOT EDIT
547            // Embeds views/ and public/ from this crate at compile time.
548            #[derive(rustf::rust_embed::RustEmbed)]
549            #[folder = #views_folder]
550            #[allow(dead_code)]
551            struct __RustfAppViews;
552
553            #[derive(rustf::rust_embed::RustEmbed)]
554            #[folder = #assets_folder]
555            #[allow(dead_code)]
556            struct __RustfAppAssets;
557
558            impl rustf::EmbeddedFileProvider for __RustfAppViews {
559                fn get(&self, path: &str) -> Option<Vec<u8>> {
560                    <__RustfAppViews as rustf::rust_embed::RustEmbed>::get(path)
561                        .map(|f| f.data.into_owned())
562                }
563                fn files(&self) -> Vec<String> {
564                    <__RustfAppViews as rustf::rust_embed::RustEmbed>::iter()
565                        .map(|p| p.to_string())
566                        .collect()
567                }
568            }
569
570            impl rustf::EmbeddedFileProvider for __RustfAppAssets {
571                fn get(&self, path: &str) -> Option<Vec<u8>> {
572                    <__RustfAppAssets as rustf::rust_embed::RustEmbed>::get(path)
573                        .map(|f| f.data.into_owned())
574                }
575                fn files(&self) -> Vec<String> {
576                    <__RustfAppAssets as rustf::rust_embed::RustEmbed>::iter()
577                        .map(|p| p.to_string())
578                        .collect()
579                }
580            }
581        }
582    } else {
583        quote! {}
584    };
585
586    #[cfg(not(feature = "embedded-views"))]
587    let embedded_structs = quote! {};
588
589    // Registration statements injected at the start of main()
590    #[cfg(feature = "embedded-views")]
591    let embed_register_stmt: syn::Stmt = if !is_rustf_framework {
592        parse_quote! {
593            {
594                rustf::register_views_provider(Box::new(__RustfAppViews));
595                rustf::register_assets_provider(Box::new(__RustfAppAssets));
596            }
597        }
598    } else {
599        parse_quote! { {} }
600    };
601
602    #[cfg(not(feature = "embedded-views"))]
603    let embed_register_stmt: syn::Stmt = parse_quote! { {} };
604
605    // Inject auto-discovery hook registration at the start of the function body.
606    // Note: Modules are no longer auto-registered via hooks. They're discovered via
607    // auto_modules!() for IDE support, but developers must call MODULE::register() explicitly.
608    let register_stmt = parse_quote! {
609        rustf::auto::register_hooks(rustf::auto::AutoDiscoveryHooks {
610            controllers: Some(|| controllers::collect_routes()),
611            models: Some(|registry: &mut rustf::models::ModelRegistry| {
612                models::register_all(registry);
613            }),
614            shared: None,  // Modules are no longer auto-registered. Explicit registration only.
615            middleware: Some(|registry: &mut rustf::middleware::MiddlewareRegistry| {
616                middleware::register_all(registry);
617            }),
618            events: Some(|emitter: &mut rustf::events::EventEmitter| {
619                events::register_all(emitter);
620            }),
621            definitions: Some(|defs: &mut rustf::definitions::Definitions| {
622                definitions::register_all(defs);
623            }),
624            workers: Some(auto_workers!()),
625        });
626    };
627
628    let mut fn_block = (*input_fn.block).clone();
629    // Insert in reverse order so index 0 ends up first
630    fn_block.stmts.insert(0, embed_register_stmt);
631    fn_block.stmts.insert(0, register_stmt);
632    input_fn.block = Box::new(fn_block);
633
634    let expanded = quote! {
635        // Auto-generated module declarations
636        #modules_mod
637        #controllers_mod
638        #models_mod
639        #middleware_mod
640        #events_mod
641        #definitions_mod
642
643        // Embedded file provider structs (only when embedded-views feature is active)
644        #embedded_structs
645
646        // Original function
647        #input_fn
648    };
649
650    expanded.into()
651}
652
653/// Generate module declarations for a specific directory
654fn generate_mod_declarations(src_dir: &PathBuf, dir_name: &str) -> proc_macro2::TokenStream {
655    let target_dir = src_dir.join(dir_name);
656
657    if !target_dir.exists() {
658        return fallback_module(dir_name);
659    }
660
661    let mut generated_module_declarations = Vec::new();
662    let mut generated_mod_content = String::new();
663    generated_mod_content
664        .push_str("// Auto-generated by RustF #[auto_discover] macro - DO NOT EDIT\n");
665    generated_mod_content.push_str("// This file is framework-owned and may be overwritten.\n");
666    generated_mod_content.push_str(&format!(
667        "// Generated module declarations for src/{}/\n\n",
668        dir_name
669    ));
670    let mut aggregator_calls = String::new();
671
672    // Scan for .rs files in the directory with max depth of 3
673    for entry in WalkDir::new(&target_dir)
674        .min_depth(1)
675        .max_depth(3) // Support up to 3 levels of nesting
676        .into_iter()
677        .filter_map(|e| e.ok())
678    {
679        let path = entry.path();
680
681        // Skip directories
682        if path.is_dir() {
683            continue;
684        }
685
686        // Skip if not a .rs file
687        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
688            continue;
689        }
690
691        // Skip IDE files, mod.rs files, and .inc.rs files
692        if let Some(filename) = path.file_name().and_then(|s| s.to_str()) {
693            if filename == "mod.rs" || filename.starts_with("_") || filename.ends_with(".inc.rs") {
694                continue;
695            }
696        }
697
698        // Get the relative path from target directory
699        let relative_to_target = path
700            .strip_prefix(&target_dir)
701            .expect("Path should be under target directory");
702
703        // Build nested module path components
704        let mut path_components = Vec::new();
705        for component in relative_to_target.components() {
706            if let std::path::Component::Normal(name) = component {
707                if let Some(name_str) = name.to_str() {
708                    // Remove .rs extension from the last component
709                    if name_str.ends_with(".rs") {
710                        path_components.push(name_str.trim_end_matches(".rs"));
711                    } else {
712                        path_components.push(name_str);
713                    }
714                }
715            }
716        }
717
718        if path_components.is_empty() {
719            continue;
720        }
721
722        // Skip special files for models
723        if dir_name == "models" {
724            let module_name = path_components.last().unwrap();
725            if module_name == &"MODELS_README" || module_name.contains("_generated") {
726                continue;
727            }
728        }
729
730        // Create unique module identifier (e.g., "api_users" for "api/users.rs")
731        let module_ident_str = path_components.join("_");
732        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
733
734        // Generate module declaration with proper path handling
735        if path_components.len() == 1 {
736            // Simple top-level module - no path attribute needed
737            generated_module_declarations.push(quote! {
738                pub mod #module_ident;
739            });
740        } else {
741            // Nested module - use path attribute relative to the module we're in
742            let relative_path = relative_to_target.to_string_lossy().replace('\\', "/");
743            generated_module_declarations.push(quote! {
744                #[path = #relative_path]
745                pub mod #module_ident;
746            });
747        }
748
749        let relative_path = relative_to_target.to_string_lossy().replace('\\', "/");
750        generated_mod_content.push_str(&format!(
751            "#[path = \"../{}/{}\"]\n",
752            dir_name, relative_path
753        ));
754        generated_mod_content.push_str(&format!("pub mod {};\n", module_ident_str));
755
756        match dir_name {
757            "controllers" => aggregator_calls.push_str(&format!(
758                "    routes.extend({}::install());\n",
759                module_ident_str
760            )),
761            "models" => aggregator_calls.push_str(&format!(
762                "    {}::register(registry);\n",
763                module_ident_str
764            )),
765            "middleware" => aggregator_calls.push_str(&format!(
766                "    {}::install(registry);\n",
767                module_ident_str
768            )),
769            "events" => aggregator_calls.push_str(&format!(
770                "    {}::install(emitter);\n",
771                module_ident_str
772            )),
773            "definitions" => aggregator_calls.push_str(&format!(
774                "    {}::install(defs);\n",
775                module_ident_str
776            )),
777            _ => {}
778        }
779    }
780
781    // Handle special case for models with base subdirectory
782    if dir_name == "models" {
783        let base_dir = target_dir.join("base");
784        if base_dir.exists() {
785            let mut base_declarations = Vec::new();
786            let mut base_content = String::new();
787
788            for entry in WalkDir::new(&base_dir)
789                .min_depth(1)
790                .max_depth(1)
791                .into_iter()
792                .filter_map(|e| e.ok())
793            {
794                let path = entry.path();
795
796                if path.extension().and_then(|s| s.to_str()) == Some("rs") {
797                    // Skip .inc.rs files (included code fragments)
798                    if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
799                        if file_name.ends_with(".inc.rs") {
800                            continue;
801                        }
802                    }
803
804                    if let Some(module_name) = path.file_stem().and_then(|s| s.to_str()) {
805                        let module_ident =
806                            syn::Ident::new(module_name, proc_macro2::Span::call_site());
807                        base_declarations.push(quote! {
808                            pub mod #module_ident;
809                        });
810                        base_content
811                            .push_str(&format!("    #[path = \"base/{}.rs\"]\n", module_name));
812                        base_content.push_str(&format!("    pub mod {};\n", module_name));
813                    }
814                }
815            }
816
817            if !base_declarations.is_empty() {
818                generated_module_declarations.push(quote! {
819                    pub mod base {
820                        #(#base_declarations)*
821                    }
822                });
823
824                generated_mod_content.push_str("\npub mod base {\n");
825                generated_mod_content.push_str(&base_content);
826                generated_mod_content.push_str("}\n");
827            }
828        }
829    }
830
831    match dir_name {
832        "controllers" => generated_mod_content.push_str(
833            "\npub fn collect_routes() -> Vec<rustf::routing::Route> {\n    let mut routes = Vec::new();\n",
834        ),
835        "models" => generated_mod_content.push_str(
836            "\npub fn register_all(registry: &mut rustf::models::ModelRegistry) {\n",
837        ),
838        "middleware" => generated_mod_content.push_str(
839            "\npub fn register_all(registry: &mut rustf::middleware::MiddlewareRegistry) {\n",
840        ),
841        "events" => generated_mod_content
842            .push_str("\npub fn register_all(emitter: &mut rustf::events::EventEmitter) {\n"),
843        "definitions" => generated_mod_content.push_str(
844            "\npub fn register_all(defs: &mut rustf::definitions::Definitions) {\n",
845        ),
846        _ => {}
847    }
848
849    if !aggregator_calls.is_empty() {
850        generated_mod_content.push_str(&aggregator_calls);
851    }
852
853    match dir_name {
854        "controllers" => generated_mod_content.push_str("    routes\n}\n"),
855        "models" | "middleware" | "events" | "definitions" => {
856            generated_mod_content.push_str("}\n");
857        }
858        _ => {}
859    }
860
861    // Write generated support files
862    if !generated_module_declarations.is_empty() {
863        let legacy_ide_file_path = src_dir.join(format!("_{}.rs", dir_name));
864        if legacy_ide_file_path.exists() {
865            if let Err(e) = std::fs::remove_file(&legacy_ide_file_path) {
866                let message = format!(
867                    "RustF auto-discovery failed to remove legacy IDE file '{}': {}",
868                    legacy_ide_file_path.display(),
869                    e
870                );
871                return quote! { compile_error!(#message); };
872            }
873        }
874
875        let generated_dir = src_dir.join(".rustf");
876        if let Err(e) = std::fs::create_dir_all(&generated_dir) {
877            let message = format!(
878                "RustF auto-discovery failed to create '{}': {}",
879                generated_dir.display(),
880                e
881            );
882            return quote! { compile_error!(#message); };
883        }
884
885        let generated_file_path = generated_dir.join(format!("{}_gen.rs", dir_name));
886        if let Err(e) = std::fs::write(&generated_file_path, &generated_mod_content) {
887            let message = format!(
888                "RustF auto-discovery failed to write '{}': {}",
889                generated_file_path.display(),
890                e
891            );
892            return quote! { compile_error!(#message); };
893        }
894
895        if let Err(message) = ensure_wrapper_module(src_dir, dir_name) {
896            return quote! { compile_error!(#message); };
897        }
898    }
899
900    if generated_module_declarations.is_empty() {
901        return fallback_module(dir_name);
902    }
903
904    // Return wrapper module import for compilation
905    let dir_ident = syn::Ident::new(dir_name, proc_macro2::Span::call_site());
906    let wrapper_relative_path = format!("{}/mod.rs", dir_name);
907    quote! {
908        #[path = #wrapper_relative_path]
909        mod #dir_ident;
910    }
911}
912
913fn fallback_module(dir_name: &str) -> proc_macro2::TokenStream {
914    let dir_ident = syn::Ident::new(dir_name, proc_macro2::Span::call_site());
915    match dir_name {
916        "controllers" => quote! {
917            mod #dir_ident {
918                pub fn collect_routes() -> Vec<rustf::routing::Route> {
919                    Vec::new()
920                }
921            }
922        },
923        "models" => quote! {
924            mod #dir_ident {
925                pub fn register_all(_registry: &mut rustf::models::ModelRegistry) {}
926            }
927        },
928        "middleware" => quote! {
929            mod #dir_ident {
930                pub fn register_all(_registry: &mut rustf::middleware::MiddlewareRegistry) {}
931            }
932        },
933        "events" => quote! {
934            mod #dir_ident {
935                pub fn register_all(_emitter: &mut rustf::events::EventEmitter) {}
936            }
937        },
938        "definitions" => quote! {
939            mod #dir_ident {
940                pub fn register_all(_defs: &mut rustf::definitions::Definitions) {}
941            }
942        },
943        _ => quote! {
944            mod #dir_ident {}
945        },
946    }
947}
948
949fn ensure_wrapper_module(src_dir: &PathBuf, dir_name: &str) -> Result<(), String> {
950    let wrapper_path = src_dir.join(dir_name).join("mod.rs");
951    if !wrapper_path.exists() {
952        if let Some(parent) = wrapper_path.parent() {
953            std::fs::create_dir_all(parent).map_err(|e| {
954                format!(
955                    "RustF auto-discovery failed to create '{}': {}",
956                    parent.display(),
957                    e
958                )
959            })?;
960        }
961
962        std::fs::write(&wrapper_path, wrapper_template(dir_name)).map_err(|e| {
963            format!(
964                "RustF auto-discovery failed to write '{}': {}",
965                wrapper_path.display(),
966                e
967            )
968        })?;
969        return Ok(());
970    }
971
972    validate_wrapper_module(&wrapper_path, dir_name)
973}
974
975fn wrapper_template(dir_name: &str) -> String {
976    format!(
977        "// Auto-generated scaffold for RustF auto-discovery.\n\
978// You may add custom code here, but keep the generated import and re-export intact.\n\
979#[path = \"../.rustf/{dir_name}_gen.rs\"]\n\
980mod generated;\n\n\
981pub use generated::*;\n"
982    )
983}
984
985fn validate_wrapper_module(wrapper_path: &std::path::Path, dir_name: &str) -> Result<(), String> {
986    let expected_path = format!("../.rustf/{}_gen.rs", dir_name);
987    let contents = std::fs::read_to_string(wrapper_path).map_err(|e| {
988        format!(
989            "RustF auto-discovery failed to read '{}': {}",
990            wrapper_path.display(),
991            e
992        )
993    })?;
994
995    let parsed = syn::parse_file(&contents).map_err(|e| {
996        format!(
997            "RustF auto-discovery found invalid Rust in '{}': {}",
998            wrapper_path.display(),
999            e
1000        )
1001    })?;
1002
1003    let mut has_generated_mod = false;
1004    let mut has_generated_reexport = false;
1005
1006    for item in parsed.items {
1007        match item {
1008            syn::Item::Mod(item_mod) if item_mod.ident == "generated" => {
1009                if item_mod.content.is_some() {
1010                    return Err(format!(
1011                        "RustF auto-discovery rejected '{}': `mod generated` must stay external and point to '{}'",
1012                        wrapper_path.display(),
1013                        expected_path
1014                    ));
1015                }
1016
1017                let mut matches_expected_path = false;
1018                for attr in item_mod.attrs {
1019                    if attr.path().is_ident("path") {
1020                        if let syn::Meta::NameValue(name_value) = &attr.meta {
1021                            if let syn::Expr::Lit(expr_lit) = &name_value.value {
1022                                if let syn::Lit::Str(lit) = &expr_lit.lit {
1023                                    matches_expected_path = lit.value() == expected_path;
1024                                }
1025                            }
1026                        }
1027                    }
1028                }
1029
1030                if !matches_expected_path {
1031                    return Err(format!(
1032                        "RustF auto-discovery rejected '{}': `mod generated` must use #[path = \"{}\"]",
1033                        wrapper_path.display(),
1034                        expected_path
1035                    ));
1036                }
1037
1038                has_generated_mod = true;
1039            }
1040            syn::Item::Use(item_use) if is_generated_glob_reexport(&item_use) => {
1041                has_generated_reexport = true;
1042            }
1043            _ => {}
1044        }
1045    }
1046
1047    if !has_generated_mod {
1048        return Err(format!(
1049            "RustF auto-discovery rejected '{}': missing required generated module import `#[path = \"{}\"] mod generated;`",
1050            wrapper_path.display(),
1051            expected_path
1052        ));
1053    }
1054
1055    if !has_generated_reexport {
1056        return Err(format!(
1057            "RustF auto-discovery rejected '{}': missing required `pub use generated::*;` re-export",
1058            wrapper_path.display()
1059        ));
1060    }
1061
1062    Ok(())
1063}
1064
1065fn is_generated_glob_reexport(item_use: &syn::ItemUse) -> bool {
1066    if !matches!(item_use.vis, syn::Visibility::Public(_)) {
1067        return false;
1068    }
1069
1070    match &item_use.tree {
1071        syn::UseTree::Path(path) if path.ident == "generated" => {
1072            matches!(&*path.tree, syn::UseTree::Glob(_))
1073        }
1074        _ => false,
1075    }
1076}
1077
1078/// Utility macro to include a directory of Rust files as modules
1079///
1080/// This is a more generic version that can be used for custom directory structures.
1081/// Note: This is a placeholder for future extensibility.
1082#[proc_macro]
1083pub fn include_dir_as_modules(_input: TokenStream) -> TokenStream {
1084    // For now, this is a placeholder - could be implemented later if needed
1085    quote! {
1086        compile_error!("include_dir_as_modules! is not yet implemented. Use auto_controllers! or auto_models! instead.");
1087    }.into()
1088}
1089
1090/// Generate worker auto-discovery code
1091/// Returns an async closure compatible with workers_from()
1092fn generate_worker_discovery() -> proc_macro2::TokenStream {
1093    let manifest_dir =
1094        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");
1095
1096    let src_dir = PathBuf::from(&manifest_dir).join("src").join("workers");
1097
1098    // Check if we're in the rustf framework itself by looking for Cargo.toml [package] name
1099    let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
1100    let is_rustf_framework = if cargo_toml_path.exists() {
1101        if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
1102            contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
1103        } else {
1104            false
1105        }
1106    } else {
1107        false
1108    };
1109
1110    // If we're in the rustf framework itself, don't try to auto-discover workers
1111    // (workers/ is an internal module, not user-defined workers)
1112    let path_prefix = if is_rustf_framework {
1113        quote! { crate }
1114    } else {
1115        quote! { rustf }
1116    };
1117
1118    if is_rustf_framework || !src_dir.exists() {
1119        // Return empty implementation
1120        return quote! {
1121            {
1122                |_manager: std::sync::Arc<#path_prefix::workers::WorkerManager>| {
1123                    Box::pin(async move {
1124                        // No workers to register
1125                        Ok(())
1126                    })
1127                }
1128            }
1129        };
1130    }
1131
1132    let mut modules = Vec::new();
1133    let mut function_calls = Vec::new();
1134
1135    // Walk through all .rs files in the workers directory
1136    for entry in WalkDir::new(&src_dir)
1137        .min_depth(1)
1138        .max_depth(3)
1139        .into_iter()
1140        .filter_map(|e| e.ok())
1141    {
1142        let path = entry.path();
1143
1144        // Skip directories
1145        if path.is_dir() {
1146            continue;
1147        }
1148
1149        // Skip if not a .rs file
1150        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
1151            continue;
1152        }
1153
1154        // Skip mod.rs files
1155        if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
1156            continue;
1157        }
1158
1159        // Skip .inc.rs files and files starting with underscore
1160        if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
1161            if file_name.ends_with(".inc.rs") || file_name.starts_with("_") {
1162                continue;
1163            }
1164        }
1165
1166        // Create the module path relative to the workers directory
1167        let relative_to_workers = path
1168            .strip_prefix(&src_dir)
1169            .expect("Path should be under workers directory");
1170
1171        // Build nested module path
1172        let mut path_components = Vec::new();
1173        for component in relative_to_workers.components() {
1174            if let std::path::Component::Normal(name) = component {
1175                if let Some(name_str) = name.to_str() {
1176                    if name_str.ends_with(".rs") {
1177                        path_components.push(name_str.trim_end_matches(".rs"));
1178                    } else {
1179                        path_components.push(name_str);
1180                    }
1181                }
1182            }
1183        }
1184
1185        if path_components.is_empty() {
1186            continue;
1187        }
1188
1189        // Generate unique module identifier
1190        let module_ident_str = path_components.join("_");
1191        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
1192
1193        // Create relative path from src directory
1194        let src_dir_base = PathBuf::from(&manifest_dir).join("src");
1195        let relative_path = path
1196            .strip_prefix(&src_dir_base)
1197            .expect("Path should be under src directory")
1198            .to_string_lossy()
1199            .replace('\\', "/");
1200
1201        // Generate module declaration
1202        modules.push(quote! {
1203            #[path = #relative_path]
1204            pub mod #module_ident;
1205        });
1206
1207        // Generate async install call
1208        function_calls.push(quote! {
1209            #module_ident::install().await?;
1210        });
1211    }
1212
1213    let worker_count = function_calls.len();
1214
1215    quote! {
1216        {
1217            // Module declarations
1218            #(#modules)*
1219
1220            // Return async closure for workers_from()
1221            |_manager: std::sync::Arc<#path_prefix::workers::WorkerManager>| {
1222                Box::pin(async move {
1223                    log::info!("Auto-discovery: Loading {} worker(s)", #worker_count);
1224                    #(#function_calls)*
1225                    Ok(())
1226                })
1227            }
1228        }
1229    }
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234    use super::*;
1235    use std::fs;
1236    use std::path::Path;
1237    use std::sync::{Mutex, MutexGuard};
1238    use tempfile::TempDir;
1239
1240    static ENV_LOCK: Mutex<()> = Mutex::new(());
1241
1242    struct ManifestGuard {
1243        _lock: MutexGuard<'static, ()>,
1244        previous: Option<String>,
1245    }
1246
1247    impl ManifestGuard {
1248        fn enter(manifest_dir: &Path) -> Self {
1249            let lock = ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
1250            let previous = std::env::var("CARGO_MANIFEST_DIR").ok();
1251            std::env::set_var("CARGO_MANIFEST_DIR", manifest_dir);
1252            Self {
1253                _lock: lock,
1254                previous,
1255            }
1256        }
1257    }
1258
1259    impl Drop for ManifestGuard {
1260        fn drop(&mut self) {
1261            if let Some(previous) = &self.previous {
1262                std::env::set_var("CARGO_MANIFEST_DIR", previous);
1263            } else {
1264                std::env::remove_var("CARGO_MANIFEST_DIR");
1265            }
1266        }
1267    }
1268
1269    fn create_manifest(name: &str) -> TempDir {
1270        let temp_dir = TempDir::new().expect("temp dir");
1271        fs::create_dir_all(temp_dir.path().join("src")).expect("src dir");
1272        fs::write(
1273            temp_dir.path().join("Cargo.toml"),
1274            format!("[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", name),
1275        )
1276        .expect("cargo toml");
1277        temp_dir
1278    }
1279
1280    fn write_rs(path: &Path, body: &str) {
1281        if let Some(parent) = path.parent() {
1282            fs::create_dir_all(parent).expect("parent dir");
1283        }
1284        fs::write(path, body).expect("rust file");
1285    }
1286
1287    #[test]
1288    fn auto_discovery_discovers_nested_controllers_and_skips_special_files() {
1289        let temp_dir = create_manifest("fixture-app");
1290        write_rs(
1291            &temp_dir.path().join("src/controllers/home.rs"),
1292            "pub fn install() -> Vec<()> { vec![] }",
1293        );
1294        write_rs(
1295            &temp_dir.path().join("src/controllers/api/users.rs"),
1296            "pub fn install() -> Vec<()> { vec![] }",
1297        );
1298        write_rs(
1299            &temp_dir.path().join("src/controllers/_private.rs"),
1300            "pub fn install() -> Vec<()> { vec![] }",
1301        );
1302        write_rs(
1303            &temp_dir.path().join("src/controllers/shared.inc.rs"),
1304            "pub fn install() -> Vec<()> { vec![] }",
1305        );
1306        write_rs(
1307            &temp_dir.path().join("src/controllers/mod.rs"),
1308            "pub fn ignored() {}",
1309        );
1310
1311        let _guard = ManifestGuard::enter(temp_dir.path());
1312        let tokens = generate_auto_discovery("controllers", "install").to_string();
1313
1314        assert!(tokens.contains("home"));
1315        assert!(tokens.contains("api_users"));
1316        assert!(tokens.contains("routes . extend (home :: install ())"));
1317        assert!(tokens.contains("routes . extend (api_users :: install ())"));
1318        assert!(tokens.contains("Loading {} controller(s)"));
1319        assert!(!tokens.contains("_private"));
1320        assert!(!tokens.contains("shared.inc"));
1321    }
1322
1323    #[test]
1324    fn auto_discovery_skips_framework_internal_models() {
1325        let temp_dir = create_manifest("rustf");
1326        write_rs(
1327            &temp_dir.path().join("src/models/user.rs"),
1328            "pub fn register(_: &mut ()) {}",
1329        );
1330
1331        let _guard = ManifestGuard::enter(temp_dir.path());
1332        let tokens = generate_auto_discovery("models", "register").to_string();
1333
1334        assert!(tokens.contains("| _registry : & mut crate :: models :: ModelRegistry |"));
1335        assert!(!tokens.contains("user"));
1336    }
1337
1338    #[test]
1339    fn worker_discovery_generates_async_install_calls() {
1340        let temp_dir = create_manifest("fixture-app");
1341        write_rs(
1342            &temp_dir.path().join("src/workers/email.rs"),
1343            "pub async fn install() -> Result<(), ()> { Ok(()) }",
1344        );
1345        write_rs(
1346            &temp_dir.path().join("src/workers/jobs/cleanup.rs"),
1347            "pub async fn install() -> Result<(), ()> { Ok(()) }",
1348        );
1349
1350        let _guard = ManifestGuard::enter(temp_dir.path());
1351        let tokens = generate_worker_discovery().to_string();
1352
1353        assert!(tokens.contains("email :: install () . await ?"));
1354        assert!(tokens.contains("jobs_cleanup :: install () . await ?"));
1355        assert!(tokens.contains("Loading {} worker(s)"));
1356    }
1357
1358    #[test]
1359    fn generate_mod_declarations_creates_wrapper_and_generated_files() {
1360        let temp_dir = create_manifest("fixture-app");
1361        write_rs(
1362            &temp_dir.path().join("src/controllers/home.rs"),
1363            "pub fn install() -> Vec<()> { vec![] }",
1364        );
1365
1366        let _guard = ManifestGuard::enter(temp_dir.path());
1367        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "controllers")
1368            .to_string();
1369
1370        assert!(tokens.contains("# [path = \"controllers/mod.rs\"] mod controllers ;"));
1371
1372        let wrapper_path = temp_dir.path().join("src/controllers/mod.rs");
1373        let generated_path = temp_dir.path().join("src/.rustf/controllers_gen.rs");
1374
1375        let wrapper = fs::read_to_string(wrapper_path).expect("wrapper content");
1376        let generated = fs::read_to_string(generated_path).expect("generated content");
1377
1378        assert!(wrapper.contains("#[path = \"../.rustf/controllers_gen.rs\"]"));
1379        assert!(wrapper.contains("mod generated;"));
1380        assert!(wrapper.contains("pub use generated::*;"));
1381
1382        assert!(generated.contains("#[path = \"../controllers/home.rs\"]"));
1383        assert!(generated.contains("pub mod home;"));
1384        assert!(!temp_dir.path().join("src/_controllers.rs").exists());
1385    }
1386
1387    #[test]
1388    fn generate_mod_declarations_removes_legacy_underscore_file() {
1389        let temp_dir = create_manifest("fixture-app");
1390        write_rs(
1391            &temp_dir.path().join("src/models/users.rs"),
1392            "pub fn register(_: &mut ()) {}",
1393        );
1394        write_rs(
1395            &temp_dir.path().join("src/_models.rs"),
1396            "// legacy auto-generated IDE file",
1397        );
1398
1399        let _guard = ManifestGuard::enter(temp_dir.path());
1400        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "models").to_string();
1401
1402        assert!(tokens.contains("# [path = \"models/mod.rs\"] mod models ;"));
1403        assert!(!temp_dir.path().join("src/_models.rs").exists());
1404    }
1405
1406    #[test]
1407    fn generate_mod_declarations_rejects_invalid_wrapper_shape() {
1408        let temp_dir = create_manifest("fixture-app");
1409        write_rs(
1410            &temp_dir.path().join("src/controllers/home.rs"),
1411            "pub fn install() -> Vec<()> { vec![] }",
1412        );
1413        write_rs(
1414            &temp_dir.path().join("src/controllers/mod.rs"),
1415            "mod generated;\n",
1416        );
1417
1418        let _guard = ManifestGuard::enter(temp_dir.path());
1419        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "controllers")
1420            .to_string();
1421
1422        assert!(tokens.contains("compile_error !"));
1423        assert!(tokens.contains("mod generated"));
1424        assert!(tokens.contains("controllers_gen.rs"));
1425    }
1426
1427    #[test]
1428    fn generate_mod_declarations_accepts_valid_existing_wrapper() {
1429        let temp_dir = create_manifest("fixture-app");
1430        write_rs(
1431            &temp_dir.path().join("src/models/users.rs"),
1432            "pub fn register(_: &mut ()) {}",
1433        );
1434        write_rs(
1435            &temp_dir.path().join("src/models/mod.rs"),
1436            "// custom comment is allowed\n#[path = \"../.rustf/models_gen.rs\"]\nmod generated;\n\npub use generated::*;\n",
1437        );
1438
1439        let _guard = ManifestGuard::enter(temp_dir.path());
1440        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "models").to_string();
1441
1442        assert!(tokens.contains("# [path = \"models/mod.rs\"] mod models ;"));
1443    }
1444}