reinhardt-macros 0.1.2

Procedural macros for Reinhardt framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! # Installed Apps Macro
//!
//! Provides compile-time validation and type-safe registration for application modules.
//!
//! ## Overview
//!
//! The `installed_apps!` macro generates:
//! - An `InstalledApp` enum with variants for each registered application
//! - Trait implementations: `Display`, `FromStr`, `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, `Hash`
//! - Helper methods: `all_apps()`, `path()`
//! - Compile-time validation for framework modules (`reinhardt.*`)
//!
//! **Important**: This macro is for **user applications only**. Built-in framework features
//! (auth, sessions, admin, etc.) are enabled via Cargo feature flags, not through `installed_apps!`.
//!
//! ## Syntax
//!
//! ```rust,ignore
//! use reinhardt::installed_apps;
//!
//! installed_apps! {
//!     label1: "path.to.module1",
//!     label2: "path.to.module2",
//!     // ... more apps
//! }
//! ```
//!
//! ### Input Format
//!
//! - **Label**: Identifier used as enum variant name (will be used as-is, no case conversion)
//! - **Path**: Dot-separated module path as a string literal
//! - **Separator**: Comma-separated entries (trailing comma is optional)
//!
//! ### Path Format
//!
//! - **User apps**: Simple name matching directory (e.g., `"users"`, `"posts"`)
//! - **Framework modules**: Dot-separated path starting with `reinhardt` (e.g., `"reinhardt.contrib.auth"`)
//!   - Note: Most framework modules don't exist yet; use Cargo feature flags instead
//!
//! ## Generated Code
//!
//! ### Enum Definition
//!
//! The macro generates an enum with a variant for each registered application:
//!
//! ```rust,ignore
//! // Generated by: installed_apps! { users: "users", posts: "posts" }
//!
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum InstalledApp {
//!     #[allow(non_camel_case_types)]
//!     users,
//!     #[allow(non_camel_case_types)]
//!     posts,
//! }
//! ```
//!
//! **Note**: `#[allow(non_camel_case_types)]` is added to support user-defined label names
//! without enforcing Rust's CamelCase convention for enum variants.
//!
//! ### Trait Implementations
//!
//! #### `Display` Trait
//!
//! Converts enum variants to their corresponding path strings:
//!
//! ```rust,ignore
//! let app = InstalledApp::users;
//! println!("{}", app);  // Output: "users"
//! ```
//!
//! Implementation:
//!
//! ```rust,ignore
//! impl std::fmt::Display for InstalledApp {
//!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//!         match self {
//!             InstalledApp::users => write!(f, "users"),
//!             InstalledApp::posts => write!(f, "posts"),
//!         }
//!     }
//! }
//! ```
//!
//! #### `FromStr` Trait
//!
//! Parses path strings back to enum variants:
//!
//! ```rust,ignore
//! use std::str::FromStr;
//!
//! let app = InstalledApp::from_str("users")?;
//! assert_eq!(app, InstalledApp::users);
//! ```
//!
//! Implementation:
//!
//! ```rust,ignore
//! impl std::str::FromStr for InstalledApp {
//!     type Err = String;
//!
//!     fn from_str(s: &str) -> Result<Self, Self::Err> {
//!         match s {
//!             "users" => Ok(InstalledApp::users),
//!             "posts" => Ok(InstalledApp::posts),
//!             _ => Err(format!("Unknown app: {}", s))
//!         }
//!     }
//! }
//! ```
//!
//! #### Other Traits
//!
//! - `Debug`: Debug formatting
//! - `Clone`: Create a copy of the enum value
//! - `Copy`: Enable copy semantics (enum is small and copyable)
//! - `PartialEq`, `Eq`: Equality comparison
//! - `Hash`: Hashing support for use in HashMaps, HashSets, etc.
//!
//! ### Generated Methods
//!
//! #### `all_apps() -> Vec<String>`
//!
//! Returns all installed app paths as a vector of strings:
//!
//! ```rust,ignore
//! let apps = InstalledApp::all_apps();
//! assert_eq!(apps, vec!["users".to_string(), "posts".to_string()]);
//! ```
//!
//! **Use case**: Integration with app registry, migration discovery, admin panel auto-discovery.
//!
//! Implementation:
//!
//! ```rust,ignore
//! impl InstalledApp {
//!     pub fn all_apps() -> Vec<String> {
//!         vec![
//!             "users".to_string(),
//!             "posts".to_string(),
//!         ]
//!     }
//! }
//! ```
//!
//! #### `path(&self) -> &'static str`
//!
//! Returns the path for a specific app as a static string:
//!
//! ```rust,ignore
//! let app = InstalledApp::users;
//! assert_eq!(app.path(), "users");
//! ```
//!
//! **Use case**: Getting the string representation without allocating a new `String`.
//!
//! Implementation:
//!
//! ```rust,ignore
//! impl InstalledApp {
//!     pub fn path(&self) -> &'static str {
//!         match self {
//!             InstalledApp::users => "users",
//!             InstalledApp::posts => "posts",
//!         }
//!     }
//! }
//! ```
//!
//! ## Compile-time Validation
//!
//! The macro performs compile-time validation for framework modules (paths starting with `reinhardt.`):
//!
//! ### How It Works
//!
//! For framework modules, the macro generates a const block that attempts to reference the module:
//!
//! ```rust,ignore
//! const _: () = {
//!     let _ = || {
//!         // This will fail to compile if the module doesn't exist
//!         let _ = std::stringify!(reinhardt_core::contrib::auth);
//!     };
//! };
//! ```
//!
//! If the module doesn't exist, compilation will fail with a clear error message.
//!
//! ### What Gets Validated
//!
//! - **Framework modules** (`reinhardt.*`): Validated at compile time
//! - **User apps**: No compile-time validation (runtime discovery)
//!
//! ### Compilation Failure Example
//!
//! ```rust,ignore
//! installed_apps! {
//!     nonexistent: "reinhardt.contrib.nonexistent",
//! }
//! // Compile error: cannot find module `nonexistent` in `contrib`
//! ```
//!
//! ## Examples
//!
//! ### Example 1: Basic User App Registration
//!
//! ```rust,ignore
//! use reinhardt::installed_apps;
//!
//! installed_apps! {
//!     users: "users",
//!     posts: "posts",
//! }
//!
//! // The InstalledApp enum is now available
//! let app = InstalledApp::users;
//! ```
//!
//! ### Example 2: Using the Display Trait
//!
//! ```rust,ignore
//! let app = InstalledApp::users;
//! println!("App path: {}", app);  // Output: "App path: users"
//!
//! // Format into a string
//! let app_str = format!("{}", app);
//! assert_eq!(app_str, "users");
//! ```
//!
//! ### Example 3: Using the FromStr Trait
//!
//! ```rust,ignore
//! use std::str::FromStr;
//!
//! // Parse from string
//! let app = InstalledApp::from_str("users")?;
//! assert_eq!(app, InstalledApp::users);
//!
//! // Error case
//! let result = InstalledApp::from_str("unknown");
//! assert!(result.is_err());
//! assert_eq!(result.unwrap_err(), "Unknown app: unknown");
//! ```
//!
//! ### Example 4: Getting All Apps
//!
//! ```rust,ignore
//! // Get all installed app paths
//! let all_apps = InstalledApp::all_apps();
//! assert_eq!(all_apps, vec!["users", "posts"]);
//!
//! // Use in function for framework integration
//! pub fn get_installed_apps() -> Vec<String> {
//!     InstalledApp::all_apps()
//! }
//! ```
//!
//! ### Example 5: Integration with App Registry
//!
//! ```rust,ignore
//! use reinhardt::installed_apps;
//!
//! installed_apps! {
//!     users: "users",
//!     posts: "posts",
//! }
//!
//! pub fn configure_apps() -> Vec<String> {
//!     InstalledApp::all_apps()
//! }
//!
//! // In your main application setup
//! fn main() {
//!     let apps = configure_apps();
//!     // Pass to migration runner, admin panel, etc.
//! }
//! ```
//!
//! ### Example 6: Using path() Method
//!
//! ```rust,ignore
//! let app = InstalledApp::users;
//! let path = app.path();
//! assert_eq!(path, "users");
//!
//! // Useful when you need a &str instead of String
//! fn process_app(app_path: &str) {
//!     // ...
//! }
//!
//! process_app(app.path());  // No allocation needed
//! ```
//!
//! ## Important Notes
//!
//! ### User Apps Only
//!
//! This macro is designed for **user applications only**. Built-in framework features
//! (auth, sessions, admin, etc.) should be enabled via Cargo feature flags:
//!
//! ```toml
//! [dependencies]
//! reinhardt = { version = "0.1.0-alpha.1", features = ["auth", "sessions", "admin"] }
//! ```
//!
//! Then import them directly:
//!
//! ```rust,ignore
//! use reinhardt::auth::*;
//! use reinhardt::auth::sessions::*;
//! use reinhardt::admin::*;
//! ```
//!
//! ### Single Use Per Scope
//!
//! The macro generates a type named `InstalledApp`. You can only call `installed_apps!` once
//! per scope to avoid duplicate type definitions.
//!
//! ```rust,ignore
//! // ✅ OK
//! mod config {
//!     installed_apps! { users: "users" }
//! }
//!
//! // ❌ Error: duplicate definition of `InstalledApp`
//! installed_apps! { users: "users" }
//! installed_apps! { posts: "posts" }
//! ```
//!
//! ### Enum Name is Fixed
//!
//! The generated enum is always named `InstalledApp`. If you need multiple app registries,
//! place them in different modules:
//!
//! ```rust,ignore
//! mod api_apps {
//!     installed_apps! { api: "api" }
//!     // This creates api_apps::InstalledApp
//! }
//!
//! mod admin_apps {
//!     installed_apps! { admin: "admin" }
//!     // This creates admin_apps::InstalledApp
//! }
//! ```
//!
//! ## See Also
//!
//! - Public API documentation in `lib.rs`
//! - `crates/reinhardt-apps/README.md` for comprehensive usage guide
//! - Tutorial: `docs/tutorials/en/basis/1-project-setup.md`

use crate::crate_paths::{get_reinhardt_apps_crate, get_reinhardt_core_crate};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
	Ident, LitStr, Result, Token,
	parse::{Parse, ParseStream},
	punctuated::Punctuated,
};

/// Represents a single app entry in the macro input.
///
/// Each entry follows the format: `label: "path.to.app"`
///
/// # Fields
///
/// - `label`: Identifier used as the enum variant name (e.g., `users`)
/// - `_colon`: Separator token (`:`) - not used but required for parsing
/// - `path`: String literal representing the app's module path (e.g., `"users"` or `"reinhardt.contrib.auth"`)
///
/// # Example
///
/// ```text
/// users: "users"
/// ^^^^^  ^^^^^^^
/// label   path
/// ```
struct AppEntry {
	label: Ident,
	_colon: Token![:],
	path: LitStr,
}

impl Parse for AppEntry {
	fn parse(input: ParseStream) -> Result<Self> {
		Ok(AppEntry {
			label: input.parse()?,
			_colon: input.parse()?,
			path: input.parse()?,
		})
	}
}

/// Container for all app entries parsed from the macro input.
///
/// This struct holds all the `label: "path"` entries provided to the `installed_apps!` macro,
/// parsed as a comma-separated list.
///
/// # Fields
///
/// - `apps`: A comma-separated list of `AppEntry` items. Trailing comma is optional.
///
/// # Example Input
///
/// ```text
/// installed_apps! {
///     users: "users",
///     posts: "posts",
/// }
/// ```
///
/// This parses into an `InstalledApps` containing two `AppEntry` items.
struct InstalledApps {
	apps: Punctuated<AppEntry, Token![,]>,
}

impl Parse for InstalledApps {
	fn parse(input: ParseStream) -> Result<Self> {
		Ok(InstalledApps {
			apps: Punctuated::parse_terminated(input)?,
		})
	}
}
/// Implementation of the `installed_apps!` procedural macro.
///
/// This function is called by the macro and should not be used directly by users.
///
/// # What It Does
///
/// 1. **Parses** app entries from the macro input
/// 2. **Generates** enum variants (using labels as-is, with `#[allow(non_camel_case_types)]`)
/// 3. **Implements** Display trait (enum → path string conversion)
/// 4. **Implements** FromStr trait (path string → enum parsing)
/// 5. **Generates** helper methods:
///    - `all_apps() -> Vec<String>`: List all app paths
///    - `path(&self) -> &'static str`: Get path for a specific app
/// 6. **Creates** compile-time validation for `reinhardt.*` apps
///
/// # Generated Code Structure
///
/// For input:
/// ```text
/// installed_apps! {
///     users: "users",
///     posts: "posts",
/// }
/// ```
///
/// Generates:
/// ```rust,ignore
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// pub enum InstalledApp {
///     #[allow(non_camel_case_types)]
///     users,
///     #[allow(non_camel_case_types)]
///     posts,
/// }
///
/// impl std::fmt::Display for InstalledApp { /* ... */ }
/// impl std::str::FromStr for InstalledApp { /* ... */ }
/// impl InstalledApp {
///     pub fn all_apps() -> Vec<String> { /* ... */ }
///     pub fn path(&self) -> &'static str { /* ... */ }
/// }
///
/// // Compile-time validation (for reinhardt.* apps only)
/// const _: () = { /* ... */ };
/// ```
///
/// # Compile-time Validation
///
/// - **Framework modules** (starting with `reinhardt.`): Validated using const blocks
/// - **User apps**: No compile-time validation (allows flexible user app names)
///
/// # Parameters
///
/// - `input`: TokenStream from the macro invocation
///
/// # Returns
///
/// - `Ok(TokenStream)`: Generated code for the enum and implementations
/// - `Err(syn::Error)`: Parse error if the input is malformed
///
/// # See Also
///
/// - Module-level documentation for comprehensive examples and usage guide
/// - `lib.rs` for public API documentation
pub(crate) fn installed_apps_impl(input: TokenStream) -> Result<TokenStream> {
	let core_crate = get_reinhardt_core_crate();
	let apps_crate = get_reinhardt_apps_crate();
	let InstalledApps { apps } = syn::parse2(input)?;

	// Handle empty input: generate an uninhabited enum with valid implementations.
	// In Rust 2024 edition, `match self {}` on a reference is illegal because
	// reference types are always considered inhabited. We use `match *self {}`
	// (deref) which is legal for uninhabited enum types.
	if apps.is_empty() {
		return Ok(quote! {
			/// Enum representing all installed applications
			#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
			pub enum InstalledApp {}

			impl std::fmt::Display for InstalledApp {
				fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
					match *self {}
				}
			}

			impl std::str::FromStr for InstalledApp {
				type Err = String;

				fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
					Err(format!("Unknown app: {}", s))
				}
			}

			impl InstalledApp {
				/// Get all installed apps as strings
				///
				/// Returns a vector containing the string representations of all installed applications.
				pub fn all_apps() -> Vec<String> {
					vec![]
				}

				/// Get the path for this app
				///
				pub fn path(&self) -> &'static str {
					match *self {}
				}
			}

			// AppLabel trait impl for typed #[url_patterns] (Issue #3670).
			// `LABEL` is required by the trait but unused here: an empty enum
			// has no values, so `path()` is unreachable.
			impl #apps_crate::apps::AppLabel for InstalledApp {
				const LABEL: &'static str = "";

				fn path(&self) -> &'static str {
					match *self {}
				}
			}
		});
	}

	// Collect app labels and paths
	let labels: Vec<_> = apps.iter().map(|app| &app.label).collect();
	let paths: Vec<_> = apps.iter().map(|app| &app.path).collect();
	let path_strings: Vec<String> = paths.iter().map(|p| p.value()).collect();

	// Write app labels to state file for cross-macro communication with #[routes].
	// This replaces the __reinhardt_for_each_app #[macro_export] callback pattern
	// that triggers macro_expanded_macro_exports_accessed_by_absolute_paths on Rust 1.94+.
	let label_strings: Vec<String> = labels.iter().map(|l| l.to_string()).collect();
	if let Err(err) = crate::macro_state::write_installed_apps(&label_strings) {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			format!(
				"failed to persist installed_apps! macro state: {err}. \
				 Ensure the build directory is writable and try again."
			),
		));
	}

	// Generate enum variants for each app
	// Convert labels to CamelCase for enum variants
	let enum_variants = labels.iter().map(|label| {
		// Allow non_camel_case_types for user-defined labels
		quote! {
			#[allow(non_camel_case_types)]
			#label
		}
	});

	// Generate Display implementation
	let display_arms = labels.iter().zip(paths.iter()).map(|(label, path)| {
		quote! {
			InstalledApp::#label => write!(f, #path)
		}
	});

	// Generate FromStr implementation
	let from_str_arms = labels.iter().zip(paths.iter()).map(|(label, path)| {
		quote! {
			#path => Ok(InstalledApp::#label)
		}
	});

	// Generate the app list array
	let app_list = paths.iter().map(|path| {
		quote! { #path.to_string() }
	});

	// Generate validation code for each app path
	let validations = path_strings.iter().map(|path_str| {
		// Convert "reinhardt.contrib.auth" to module path validation
		let parts: Vec<&str> = path_str.split('.').collect();

		// For reinhardt.contrib.* apps, we validate they exist in the crate
		if parts.first() == Some(&"reinhardt") {
			let module_check = parts[1..].iter().fold(core_crate.clone(), |acc, part| {
				let part_ident = syn::Ident::new(part, proc_macro2::Span::call_site());
				quote! { #acc::#part_ident }
			});

			quote! {
				// Compile-time check that the module path resolves
				// Using `use` ensures the compiler verifies the path exists
				const _: () = {
					#[allow(unused_imports)]
					use #module_check as _;
				};
			}
		} else {
			// For user apps, just add a compile warning
			quote! {
				// User-defined app - runtime validation only
				#[allow(dead_code)]
				const _: &str = #path_str;
			}
		}
	});

	Ok(quote! {
		/// Enum representing all installed applications
		#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
		pub enum InstalledApp {
			#(#enum_variants),*
		}

		impl std::fmt::Display for InstalledApp {
			fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
				match self {
					#(#display_arms),*
				}
			}
		}

		impl std::str::FromStr for InstalledApp {
			type Err = String;

			fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
				match s {
					#(#from_str_arms,)*
					_ => Err(format!("Unknown app: {}", s))
				}
			}
		}

		impl InstalledApp {
			/// Get all installed apps as strings
			///
			/// Returns a vector containing the string representations of all installed applications.
			pub fn all_apps() -> Vec<String> {
				vec![
					#(#app_list),*
				]
			}
			/// Get the path for this app
			///
			pub fn path(&self) -> &'static str {
				match self {
					#(InstalledApp::#labels => #paths),*
				}
			}
		}

		// AppLabel trait impl for typed #[url_patterns] (Issue #3670).
		// Delegates to the inherent `InstalledApp::path()` method defined above.
		// The inherent method is named explicitly to avoid ambiguity with the
		// trait method of the same name (which would otherwise recurse).
		// `LABEL` is required by the trait but unused for enum implementors,
		// which dispatch on `self` via `path()`.
		impl #apps_crate::apps::AppLabel for InstalledApp {
			const LABEL: &'static str = "";

			fn path(&self) -> &'static str {
				InstalledApp::path(self)
			}
		}

		// Compile-time validation
		#(#validations)*
	})
}