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
//! action macro implementation

use crate::crate_paths::get_reinhardt_di_crate;
use crate::injectable_common::{
	detect_inject_params, generate_di_context_extraction, generate_injection_calls,
	strip_inject_attrs,
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
	Expr, ExprLit, FnArg, ItemFn, Lit, Meta, Result, Token, parse::Parser, punctuated::Punctuated,
};

/// Parsed `#[action(...)]` attribute metadata reused by `#[viewset]`'s
/// impl-form expansion.
///
/// Phase 5 of Issue #4507 extracts this struct so `viewset_macro.rs` can
/// reuse the exact same parsing logic the `#[action]` macro uses when
/// emitting `__url_resolver_meta_action_*` macros.
///
/// Refs Issue #4507.
// `Debug` is needed for `.expect_err(...)` calls inside the parser tests
// (see `tests` module). Gated to `cfg(test)` so the derive does not affect
// release builds of the proc-macro.
#[cfg_attr(test, derive(Debug))]
pub(crate) struct ActionMeta {
	// `methods` is parsed for parity with `action_impl` but is not consumed
	// by the impl-form `#[viewset]` expansion (which only needs the URL
	// metadata). Kept on the struct so future callers do not need to
	// re-parse the attribute. Refs Issue #4507.
	#[allow(dead_code)]
	pub methods: Vec<String>,
	pub detail: bool,
	/// Empty string when `url_path` is absent from the attribute.
	pub url_path: String,
	/// Defaults to the annotated function's identifier when `url_name` is
	/// absent. Always non-empty.
	pub url_name: String,
}

/// Parse the `#[action(...)]` attribute argument list into an `ActionMeta`.
///
/// Defaults `url_name` to `fn_ident` when absent, leaves `url_path` empty
/// when absent, and reuses the same validation as `action_impl` for
/// `methods` / `detail` / `url_path`.
///
/// This extractor is reused by `viewset_macro.rs::parse_action_meta_for_viewset`
/// (Phase 5 of Issue #4507) so the impl-form of `#[viewset]` emits the same
/// names and parameters that `#[action]` would compute.
///
/// Refs Issue #4507.
pub(crate) fn parse_action_args_with_defaults(
	args: TokenStream,
	fn_ident: &syn::Ident,
) -> Result<ActionMeta> {
	let mut methods = Vec::<String>::new();
	let mut detail = false;
	let mut url_path: Option<String> = None;
	let mut url_name: Option<String> = None;
	let mut has_methods = false;
	let mut has_detail = false;

	let meta_list = Punctuated::<Meta, Token![,]>::parse_terminated.parse2(args)?;
	for meta in meta_list {
		if let Meta::NameValue(nv) = meta {
			if nv.path.is_ident("methods") {
				// Validate the value type BEFORE marking the parameter as
				// present, so a malformed `methods = true` raises a clean
				// compile-time error instead of silently falling back to
				// the default `GET` method. Mirrors `action_impl`.
				let Expr::Lit(ExprLit {
					lit: Lit::Str(lit), ..
				}) = &nv.value
				else {
					return Err(syn::Error::new_spanned(
						&nv.value,
						"methods parameter must be a string literal",
					));
				};
				has_methods = true;
				let s = lit.value();
				let s = s.trim_matches(|c| c == '[' || c == ']');
				for m in s.split(',') {
					let m = m.trim().trim_matches('"');
					if !m.is_empty() {
						methods.push(m.to_string());
					}
				}
			} else if nv.path.is_ident("detail") {
				// Validate the value type BEFORE marking the parameter as
				// present. A non-boolean `detail = "false"` would
				// otherwise be silently treated as `detail = false`,
				// diverging from `action_impl` which rejects it.
				let Expr::Lit(ExprLit {
					lit: Lit::Bool(lit),
					..
				}) = &nv.value
				else {
					return Err(syn::Error::new_spanned(
						&nv.value,
						"detail parameter must be a boolean literal (true or false)",
					));
				};
				has_detail = true;
				detail = lit.value;
			} else if nv.path.is_ident("url_path") {
				// Reject non-string `url_path` values with a clean
				// compile error instead of silently ignoring them, so
				// the impl-form `#[viewset]` and `#[action]` diverge
				// only in surface syntax, not in validation strictness.
				let Expr::Lit(ExprLit {
					lit: Lit::Str(lit), ..
				}) = &nv.value
				else {
					return Err(syn::Error::new_spanned(
						&nv.value,
						"url_path parameter must be a string literal",
					));
				};
				let p = lit.value();
				if p.contains(' ') {
					return Err(syn::Error::new_spanned(
						lit,
						"url_path cannot contain spaces",
					));
				}
				if !p.starts_with('/') {
					return Err(syn::Error::new_spanned(lit, "url_path must start with '/'"));
				}
				url_path = Some(p);
			} else if nv.path.is_ident("url_name") {
				// Reject non-string `url_name` values with a clean
				// compile error. Otherwise a bogus literal (e.g.
				// `url_name = 42`) would silently fall back to the
				// function identifier default.
				let Expr::Lit(ExprLit {
					lit: Lit::Str(lit), ..
				}) = &nv.value
				else {
					return Err(syn::Error::new_spanned(
						&nv.value,
						"url_name parameter must be a string literal",
					));
				};
				// `url_name` is later passed to `syn::Ident::new(...)` by
				// the viewset/routes macro emitters to build identifiers
				// like `__for_each_viewset_meta_<url_name>` and the typed
				// `ResolvedUrls::<route>()` accessor. `syn::Ident::new`
				// panics on non-identifier input (e.g. `"highlight-code"`
				// or `"foo bar"`), which surfaces at proc-macro expansion
				// as an obscure rustc message. Validate as a Rust
				// identifier here so the failure becomes a clean
				// compile-time error tied to the attribute's own span.
				let value = lit.value();
				if syn::parse_str::<syn::Ident>(&value).is_err() {
					return Err(syn::Error::new_spanned(
						lit,
						format!(
							"url_name `{value}` is not a valid Rust identifier (use snake_case ASCII letters, digits, and underscores; cannot start with a digit)"
						),
					));
				}
				url_name = Some(value);
			}
		}
	}

	if !has_methods {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			"action macro requires 'methods' parameter",
		));
	}
	if !has_detail {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			"action macro requires 'detail' parameter",
		));
	}
	if methods.is_empty() {
		methods.push("GET".to_string());
	}

	Ok(ActionMeta {
		methods,
		detail,
		url_path: url_path.unwrap_or_default(),
		url_name: url_name.unwrap_or_else(|| fn_ident.to_string()),
	})
}

/// Implementation of the `action` procedural macro
///
/// This function is used internally by the `#[action]` attribute macro.
/// Users should not call this function directly.
pub(crate) fn action_impl(args: TokenStream, input: ItemFn) -> Result<TokenStream> {
	let mut methods = Vec::new();
	let mut detail = false;
	let mut _url_path: Option<String> = None;
	let mut _url_name: Option<String> = None;
	let mut use_inject = false;
	let mut methods_lit = None;
	let mut has_methods = false;
	let mut has_detail = false;

	// Parse arguments
	let meta_list = Punctuated::<Meta, Token![,]>::parse_terminated.parse2(args)?;

	for meta in meta_list {
		match meta {
			Meta::NameValue(nv) => {
				if nv.path.is_ident("methods") {
					has_methods = true;
					if let Expr::Lit(ExprLit {
						lit: Lit::Str(lit), ..
					}) = &nv.value
					{
						methods_lit = Some(lit.clone());
						let methods_str = lit.value();
						let methods_str = methods_str.trim_matches(|c| c == '[' || c == ']');

						for method in methods_str.split(',') {
							let method = method.trim().trim_matches('"');
							if !method.is_empty() {
								methods.push(method.to_string());
							}
						}
					} else {
						return Err(syn::Error::new_spanned(
							&nv.value,
							"methods parameter must be a string literal",
						));
					}
				} else if nv.path.is_ident("detail") {
					has_detail = true;
					if let Expr::Lit(ExprLit {
						lit: Lit::Bool(lit),
						..
					}) = &nv.value
					{
						detail = lit.value;
					} else {
						return Err(syn::Error::new_spanned(
							&nv.value,
							"detail parameter must be a boolean literal (true or false)",
						));
					}
				} else if nv.path.is_ident("url_path") {
					if let Expr::Lit(ExprLit {
						lit: Lit::Str(lit), ..
					}) = &nv.value
					{
						let path = lit.value();
						// Validate url_path format
						if path.contains(' ') {
							return Err(syn::Error::new_spanned(
								lit,
								"url_path cannot contain spaces",
							));
						}
						if !path.starts_with('/') {
							return Err(syn::Error::new_spanned(
								lit,
								"url_path must start with '/'",
							));
						}
						_url_path = Some(path);
					} else {
						return Err(syn::Error::new_spanned(
							&nv.value,
							"url_path parameter must be a string literal",
						));
					}
				} else if nv.path.is_ident("url_name") {
					if let Expr::Lit(ExprLit {
						lit: Lit::Str(lit), ..
					}) = &nv.value
					{
						_url_name = Some(lit.value());
					} else {
						return Err(syn::Error::new_spanned(
							&nv.value,
							"url_name parameter must be a string literal",
						));
					}
				} else if nv.path.is_ident("use_inject") {
					if let Expr::Lit(ExprLit {
						lit: Lit::Bool(lit),
						..
					}) = &nv.value
					{
						use_inject = lit.value;
					} else {
						return Err(syn::Error::new_spanned(
							&nv.value,
							"use_inject parameter must be a boolean literal (true or false)",
						));
					}
				}
			}
			Meta::Path(path) => {
				if path.is_ident("methods") {
					return Err(syn::Error::new_spanned(
						path,
						"methods parameter requires a value: methods = \"GET,POST\"",
					));
				} else if path.is_ident("detail") {
					return Err(syn::Error::new_spanned(
						path,
						"detail parameter requires a value: detail = true or detail = false",
					));
				}
			}
			_ => {}
		}
	}

	// Validate required parameters
	if !has_methods {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			"action macro requires 'methods' parameter",
		));
	}

	if !has_detail {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			"action macro requires 'detail' parameter",
		));
	}

	// Default to GET if no methods specified
	if methods.is_empty() {
		methods.push("GET".to_string());
	}

	// Validate HTTP methods
	const VALID_METHODS: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
	for method in &methods {
		let method_upper = method.to_uppercase();
		if !VALID_METHODS.contains(&method_upper.as_str()) {
			let error_msg = format!(
				"Invalid HTTP method '{}'. Valid methods are: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS",
				method
			);
			return Err(syn::Error::new_spanned(
				methods_lit.as_ref().unwrap(),
				error_msg,
			));
		}
	}

	let fn_name = &input.sig.ident;
	let fn_block = &input.block;
	let fn_inputs = &input.sig.inputs;
	let fn_output = &input.sig.output;
	let fn_vis = &input.vis;
	let fn_attrs = &input.attrs;
	let asyncness = &input.sig.asyncness;
	let generics = &input.sig.generics;
	let where_clause = &input.sig.generics.where_clause;

	// Generate metadata
	let detail_flag = detail;
	let method_list = methods.join(", ");

	// Detect #[inject] parameters
	let inject_params = detect_inject_params(fn_inputs);

	// Validate: error if #[inject] is used when use_inject = false
	if !use_inject && !inject_params.is_empty() {
		return Err(syn::Error::new_spanned(
			&inject_params[0].pat,
			"#[inject] attribute requires use_inject = true option",
		));
	}

	// Generate wrapper function for DI support
	if use_inject && !inject_params.is_empty() {
		let original_fn_name = quote::format_ident!("{}_original", fn_name);

		// Original function (with #[inject] attributes stripped)
		let stripped_inputs = strip_inject_attrs(fn_inputs);
		let stripped_inputs = Punctuated::<FnArg, Token![,]>::from_iter(stripped_inputs);

		// DI context extraction code
		let request_ident = syn::Ident::new("request", proc_macro2::Span::call_site());
		let di_extraction = generate_di_context_extraction(&request_ident);

		// Injection calls code
		let injection_calls = generate_injection_calls(&inject_params);

		// Argument list
		let inject_args: Vec<_> = inject_params.iter().map(|p| &p.pat).collect();
		let regular_args: Vec<_> = stripped_inputs
			.iter()
			.filter_map(|arg| {
				if let FnArg::Typed(pat_type) = arg {
					Some(&pat_type.pat)
				} else {
					None
				}
			})
			.collect();

		let di_crate = get_reinhardt_di_crate();

		Ok(quote! {
			// Original function (renamed, private)
			#asyncness fn #original_fn_name #generics (#stripped_inputs) #fn_output #where_clause {
				#fn_block
			}

			// Wrapper function (with DI support)
			#(#fn_attrs)*
			#[doc = "Custom action with DI support"]
			#[doc = concat!("Methods: ", #method_list)]
			#[doc = concat!("Detail: ", stringify!(#detail_flag))]
			#fn_vis #asyncness fn #fn_name(request: ::Request) #fn_output {
				// DI context extraction
				#di_extraction

				// Execute handler within resolve context scope
				#di_crate::resolve_context::RESOLVE_CTX.scope(__resolve_ctx, async {
					// Dependency resolution
					#(#injection_calls)*

					// Call original function
					#original_fn_name(#(#regular_args,)* #(#inject_args),*).await
				}).await
			}
		})
	} else {
		// Without DI, use conventional approach
		Ok(quote! {
			#(#fn_attrs)*
			#[doc = "Custom action"]
			#[doc = concat!("Methods: ", #method_list)]
			#[doc = concat!("Detail: ", stringify!(#detail_flag))]
			#fn_vis #asyncness fn #fn_name #generics (#fn_inputs) #fn_output #where_clause {
				#fn_block
			}
		})
	}
}

#[cfg(test)]
mod meta_extractor_tests {
	use super::*;
	use quote::quote;

	#[test]
	fn url_name_defaults_to_fn_name_when_absent() {
		// Arrange
		let args = quote! { methods = "POST", detail = true };
		let fn_ident: syn::Ident = syn::parse_quote! { highlight };

		// Act
		let meta = parse_action_args_with_defaults(args, &fn_ident).unwrap();

		// Assert
		assert_eq!(meta.url_name, "highlight");
		assert!(meta.detail);
		assert!(meta.url_path.is_empty());
	}

	#[test]
	fn explicit_url_name_wins_over_fn_name() {
		// Arrange
		let args = quote! { methods = "POST", detail = true, url_name = "highlight_code" };
		let fn_ident: syn::Ident = syn::parse_quote! { highlight };

		// Act
		let meta = parse_action_args_with_defaults(args, &fn_ident).unwrap();

		// Assert
		assert_eq!(meta.url_name, "highlight_code");
	}

	#[test]
	fn url_path_with_placeholders_is_preserved() {
		// Arrange
		let args = quote! {
			methods = "GET",
			detail = true,
			url_name = "child",
			url_path = "/children/{child_id}"
		};
		let fn_ident: syn::Ident = syn::parse_quote! { child };

		// Act
		let meta = parse_action_args_with_defaults(args, &fn_ident).unwrap();

		// Assert
		assert_eq!(meta.url_path, "/children/{child_id}");
	}

	#[test]
	fn missing_methods_errors() {
		// Arrange
		let args = quote! { detail = true };
		let fn_ident: syn::Ident = syn::parse_quote! { x };

		// Act + Assert
		assert!(parse_action_args_with_defaults(args, &fn_ident).is_err());
	}

	#[test]
	fn non_string_methods_value_errors() {
		// Arrange: `methods = true` is malformed -- value must be a
		// string literal. Previously the parser silently accepted this
		// and fell back to the default `GET` method, diverging from
		// `action_impl`.
		let args = quote! { methods = true, detail = false };
		let fn_ident: syn::Ident = syn::parse_quote! { x };

		// Act
		let err = parse_action_args_with_defaults(args, &fn_ident)
			.expect_err("non-string methods value must error");

		// Assert
		assert!(
			err.to_string()
				.contains("methods parameter must be a string literal"),
			"unexpected error message: {err}"
		);
	}

	#[test]
	fn non_bool_detail_value_errors() {
		// Arrange: `detail = "false"` is malformed -- value must be a
		// boolean literal. Previously the parser silently treated this
		// as `detail = false` (the field's zero value), diverging from
		// `action_impl`.
		let args = quote! { methods = "GET", detail = "false" };
		let fn_ident: syn::Ident = syn::parse_quote! { x };

		// Act
		let err = parse_action_args_with_defaults(args, &fn_ident)
			.expect_err("non-boolean detail value must error");

		// Assert
		assert!(
			err.to_string()
				.contains("detail parameter must be a boolean literal"),
			"unexpected error message: {err}"
		);
	}

	#[test]
	fn non_string_url_path_value_errors() {
		// Arrange: `url_path = 42` is malformed -- value must be a
		// string literal. Previously the parser silently ignored the
		// field, leaving `url_path` empty rather than rejecting the
		// attribute.
		let args = quote! { methods = "GET", detail = true, url_path = 42 };
		let fn_ident: syn::Ident = syn::parse_quote! { x };

		// Act
		let err = parse_action_args_with_defaults(args, &fn_ident)
			.expect_err("non-string url_path value must error");

		// Assert
		assert!(
			err.to_string()
				.contains("url_path parameter must be a string literal"),
			"unexpected error message: {err}"
		);
	}

	#[test]
	fn non_string_url_name_value_errors() {
		// Arrange: `url_name = false` is malformed -- value must be a
		// string literal. Previously the parser silently ignored the
		// field, falling back to the function identifier default.
		let args = quote! { methods = "GET", detail = true, url_name = false };
		let fn_ident: syn::Ident = syn::parse_quote! { x };

		// Act
		let err = parse_action_args_with_defaults(args, &fn_ident)
			.expect_err("non-string url_name value must error");

		// Assert
		assert!(
			err.to_string()
				.contains("url_name parameter must be a string literal"),
			"unexpected error message: {err}"
		);
	}
}