1use proc_macro::TokenStream;
7use quote::quote;
8use std::path::PathBuf;
9use syn::{parse_macro_input, parse_quote, ItemFn};
10use walkdir::WalkDir;
11
12#[proc_macro]
25pub fn auto_controllers(_input: TokenStream) -> TokenStream {
26 generate_auto_discovery("controllers", "install").into()
27}
28
29#[proc_macro]
42pub fn auto_models(_input: TokenStream) -> TokenStream {
43 generate_auto_discovery("models", "register").into()
44}
45
46#[proc_macro]
59pub fn auto_middleware(_input: TokenStream) -> TokenStream {
60 generate_auto_discovery("middleware", "install").into()
61}
62
63#[proc_macro]
75pub fn auto_definitions(_input: TokenStream) -> TokenStream {
76 generate_auto_discovery("definitions", "install").into()
77}
78
79#[proc_macro]
93pub fn auto_modules(_input: TokenStream) -> TokenStream {
94 generate_auto_discovery("modules", "install").into()
95}
96
97#[proc_macro]
110pub fn auto_events(_input: TokenStream) -> TokenStream {
111 generate_auto_discovery("events", "install").into()
112}
113
114#[proc_macro]
129pub fn auto_workers(_input: TokenStream) -> TokenStream {
130 generate_worker_discovery().into()
131}
132
133fn 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 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 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 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 }
180 }
181 },
182 "middleware" => quote! {
183 {
184 |_registry: &mut #path_prefix::middleware::MiddlewareRegistry| {
185 }
187 }
188 },
189 "events" => quote! {
190 {
191 |_emitter: &mut #path_prefix::events::EventEmitter| {
192 }
194 }
195 },
196 "definitions" => quote! {
197 {
198 |_defs: &mut #path_prefix::definitions::Definitions| {
199 }
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 for entry in WalkDir::new(&src_dir)
212 .min_depth(1)
213 .max_depth(3) .into_iter()
215 .filter_map(|e| e.ok())
216 {
217 let path = entry.path();
218
219 if path.is_dir() {
221 continue;
222 }
223
224 if path.extension().and_then(|s| s.to_str()) != Some("rs") {
226 continue;
227 }
228
229 if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
231 continue;
232 }
233
234 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 if file_name.starts_with("_") {
241 continue;
242 }
243 }
244
245 let relative_to_target = path
247 .strip_prefix(&src_dir)
248 .expect("Path should be under target directory");
249
250 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 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 let _module_path = path_components.join("::");
267
268 let module_ident_str = path_components.join("_");
270 let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
271
272 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('\\', "/"); if path_components.len() == 1 {
282 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 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 }
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 modules.push(quote! {
340 #[path = #relative_path]
341 pub mod #module_ident;
342 });
343
344 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 }
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 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 #(#modules)*
402
403 log::info!("Auto-discovery: Loading {} controller(s)", #controller_count);
404
405 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 #(#modules)*
418
419 |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 #(#modules)*
433
434 |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 #(#modules)*
447
448 log::info!("Auto-discovery: Found module(s) - explicit MODULE::register() required for registration");
449 }
453 }
454 }
455 "events" => {
456 let event_count = function_calls.len();
457 quote! {
458 {
459 #(#modules)*
461
462 |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 #(#modules)*
476
477 |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#[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 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 #[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 #[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 #[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 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, 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 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 #modules_mod
637 #controllers_mod
638 #models_mod
639 #middleware_mod
640 #events_mod
641 #definitions_mod
642
643 #embedded_structs
645
646 #input_fn
648 };
649
650 expanded.into()
651}
652
653fn 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 for entry in WalkDir::new(&target_dir)
674 .min_depth(1)
675 .max_depth(3) .into_iter()
677 .filter_map(|e| e.ok())
678 {
679 let path = entry.path();
680
681 if path.is_dir() {
683 continue;
684 }
685
686 if path.extension().and_then(|s| s.to_str()) != Some("rs") {
688 continue;
689 }
690
691 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 let relative_to_target = path
700 .strip_prefix(&target_dir)
701 .expect("Path should be under target directory");
702
703 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 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 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 let module_ident_str = path_components.join("_");
732 let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
733
734 if path_components.len() == 1 {
736 generated_module_declarations.push(quote! {
738 pub mod #module_ident;
739 });
740 } else {
741 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 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 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 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 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#[proc_macro]
1083pub fn include_dir_as_modules(_input: TokenStream) -> TokenStream {
1084 quote! {
1086 compile_error!("include_dir_as_modules! is not yet implemented. Use auto_controllers! or auto_models! instead.");
1087 }.into()
1088}
1089
1090fn 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 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 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 quote! {
1121 {
1122 |_manager: std::sync::Arc<#path_prefix::workers::WorkerManager>| {
1123 Box::pin(async move {
1124 Ok(())
1126 })
1127 }
1128 }
1129 };
1130 }
1131
1132 let mut modules = Vec::new();
1133 let mut function_calls = Vec::new();
1134
1135 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 if path.is_dir() {
1146 continue;
1147 }
1148
1149 if path.extension().and_then(|s| s.to_str()) != Some("rs") {
1151 continue;
1152 }
1153
1154 if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
1156 continue;
1157 }
1158
1159 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 let relative_to_workers = path
1168 .strip_prefix(&src_dir)
1169 .expect("Path should be under workers directory");
1170
1171 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 let module_ident_str = path_components.join("_");
1191 let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());
1192
1193 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 modules.push(quote! {
1203 #[path = #relative_path]
1204 pub mod #module_ident;
1205 });
1206
1207 function_calls.push(quote! {
1209 #module_ident::install().await?;
1210 });
1211 }
1212
1213 let worker_count = function_calls.len();
1214
1215 quote! {
1216 {
1217 #(#modules)*
1219
1220 |_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}