1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Implementation of the `component!` proc macro
use proc_macro::TokenStream;
use quote::quote;
use std::collections::HashSet;
use syn::{
Attribute, Ident, LitStr, Result, Token, Visibility,
parse::{Parse, ParseStream},
punctuated::Punctuated,
token::{Brace, Comma},
};
/// Parse the entire component! macro input
pub fn expand(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as ComponentInput);
let output = input.generate();
TokenStream::from(output)
}
/// Top-level input for component! macro
#[allow(dead_code)]
struct ComponentInput {
attributes: Vec<Attribute>,
visibility: Visibility,
enum_keyword: Option<Token![enum]>,
enum_name: Option<Ident>,
brace: Option<Brace>,
variants: Punctuated<ComponentVariant, Comma>,
/// Parsed auto_register attribute with format list
auto_register_formats: Option<Vec<Ident>>,
}
impl Parse for ComponentInput {
fn parse(input: ParseStream) -> Result<Self> {
let attributes = input.call(Attribute::parse_outer)?;
// Parse auto_register attribute if present
let auto_register_formats = Self::extract_auto_register_formats(&attributes)?;
// Check if we have explicit `pub enum Name { ... }` syntax
let visibility = input.parse::<Visibility>()?;
if input.peek(Token![enum]) {
// Full syntax: pub enum Component { ... }
let enum_keyword = Some(input.parse()?);
let enum_name = Some(input.parse()?);
let content;
let brace = Some(syn::braced!(content in input));
let variants = content.parse_terminated(ComponentVariant::parse, Token![,])?;
Ok(ComponentInput {
attributes,
visibility,
enum_keyword,
enum_name,
brace,
variants,
auto_register_formats,
})
} else {
// Simple syntax: just variants
let variants = input.parse_terminated(ComponentVariant::parse, Token![,])?;
Ok(ComponentInput {
attributes,
visibility,
enum_keyword: None,
enum_name: None,
brace: None,
variants,
auto_register_formats,
})
}
}
}
/// A single component variant with optional metadata
struct ComponentVariant {
attributes: Vec<Attribute>,
name: Ident,
metadata: Option<ComponentMetadata>,
}
impl Parse for ComponentVariant {
fn parse(input: ParseStream) -> Result<Self> {
let attributes = input.call(Attribute::parse_outer)?;
let name = input.parse()?;
let metadata = if input.peek(Brace) {
Some(input.parse()?)
} else {
None
};
Ok(ComponentVariant {
attributes,
name,
metadata,
})
}
}
/// Metadata fields for a component variant
struct ComponentMetadata {
// Role-based docs fields
docs_pub: Option<LitStr>,
docs_dev: Option<LitStr>,
docs_int: Option<LitStr>,
introduced: Option<LitStr>,
deprecated: Option<LitStr>,
// Role-based examples
examples_pub: Option<Vec<LitStr>>,
examples_dev: Option<Vec<LitStr>>,
examples_int: Option<Vec<LitStr>>,
tags: Option<Vec<LitStr>>,
related: Option<Vec<LitStr>>,
}
impl Parse for ComponentMetadata {
fn parse(input: ParseStream) -> Result<Self> {
let content;
syn::braced!(content in input);
let mut docs_pub = None;
let mut docs_dev = None;
let mut docs_int = None;
let mut introduced = None;
let mut deprecated = None;
let mut examples_pub = None;
let mut examples_dev = None;
let mut examples_int = None;
let mut tags = None;
let mut related = None;
while !content.is_empty() {
// Check for optional role marker ('Pub, 'Dev, 'Int)
let role_marker = if content.peek(syn::Lifetime) {
let lifetime: syn::Lifetime = content.parse()?;
Some(lifetime.ident.to_string())
} else {
None
};
let field_name: Ident = content.parse()?;
content.parse::<Token![:]>()?;
let field_str = field_name.to_string();
match field_str.as_str() {
"docs" | "description" => {
let doc_str: LitStr = content.parse()?;
match role_marker.as_deref() {
Some("Pub") | None => docs_pub = Some(doc_str),
Some("Dev") => docs_dev = Some(doc_str),
Some("Int") => docs_int = Some(doc_str),
Some(other) => {
return Err(syn::Error::new(
field_name.span(),
format!("unknown role marker '{}. Valid: 'Pub, 'Dev, 'Int", other),
));
}
}
}
"introduced" => {
introduced = Some(content.parse()?);
}
"deprecated" => {
deprecated = Some(content.parse()?);
}
"examples" => {
let array_content;
syn::bracketed!(array_content in content);
let examples_vec =
Punctuated::<LitStr, Token![,]>::parse_terminated(&array_content)?
.into_iter()
.collect();
match role_marker.as_deref() {
Some("Pub") | None => examples_pub = Some(examples_vec),
Some("Dev") => examples_dev = Some(examples_vec),
Some("Int") => examples_int = Some(examples_vec),
Some(other) => {
return Err(syn::Error::new(
field_name.span(),
format!("unknown role marker '{}. Valid: 'Pub, 'Dev, 'Int", other),
));
}
}
}
"tags" => {
let array_content;
syn::bracketed!(array_content in content);
tags = Some(
Punctuated::<LitStr, Token![,]>::parse_terminated(&array_content)?
.into_iter()
.collect(),
);
}
"related" => {
let array_content;
syn::bracketed!(array_content in content);
related = Some(
Punctuated::<LitStr, Token![,]>::parse_terminated(&array_content)?
.into_iter()
.collect(),
);
}
_ => {
return Err(syn::Error::new(
field_name.span(),
format!(
"unknown field `{}`. Valid fields: description (or docs), introduced, deprecated, examples, tags, related. Use 'Pub/'Dev/'Int markers for role-based visibility",
field_name
),
));
}
}
// Optional trailing comma
if !content.is_empty() {
content.parse::<Token![,]>()?;
}
}
Ok(ComponentMetadata {
docs_pub,
docs_dev,
docs_int,
introduced,
deprecated,
examples_pub,
examples_dev,
examples_int,
tags,
related,
})
}
}
impl ComponentInput {
/// Extract auto_register attribute and parse its formats
/// Supports: #[auto_register(json, html)]
fn extract_auto_register_formats(attributes: &[Attribute]) -> Result<Option<Vec<Ident>>> {
for attr in attributes {
if attr.path().is_ident("auto_register") {
// Parse the attribute arguments
let formats: Vec<Ident> = attr
.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated)?
.into_iter()
.collect();
if formats.is_empty() {
return Err(syn::Error::new_spanned(
attr,
"auto_register attribute requires at least one format (e.g., #[auto_register(json, html)])",
));
}
return Ok(Some(formats));
}
}
Ok(None)
}
/// Validate that component variants don't have duplicate normalized names
/// Auth, auth, and AUTH all normalize to "AUTH" and should be considered duplicates
fn validate_no_duplicates(&self) -> Result<()> {
let mut seen_normalized = HashSet::new();
for variant in &self.variants {
let name = variant.name.to_string();
let normalized = name.to_ascii_uppercase();
if seen_normalized.contains(&normalized) {
return Err(syn::Error::new(
variant.name.span(),
format!(
"duplicate component `{}` (normalizes to `{}`, already defined)",
name, normalized
),
));
}
seen_normalized.insert(normalized);
}
Ok(())
}
fn generate(&self) -> proc_macro2::TokenStream {
// Validate no duplicates first
if let Err(err) = self.validate_no_duplicates() {
return err.to_compile_error();
}
let enum_name = self
.enum_name
.clone()
.unwrap_or_else(|| Ident::new("Component", proc_macro2::Span::call_site()));
let visibility = &self.visibility;
let attributes = &self.attributes;
let variant_names: Vec<_> = self.variants.iter().map(|v| &v.name).collect();
let variant_attrs: Vec<_> = self.variants.iter().map(|v| &v.attributes).collect();
let as_str_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let name_str = name.to_string();
quote! {
Self::#name => #name_str
}
})
.collect();
// Generate from_str match arms (reverse mapping)
let from_str_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let name_str = name.to_string();
quote! {
#name_str => Some(Self::#name)
}
})
.collect();
// Generate metadata methods (only if metadata feature enabled)
let metadata_impl = self.generate_metadata_impl(&enum_name);
// Generate auto-registration code (always enabled for components)
let auto_registrations = self.generate_auto_registration(&enum_name);
// Generate validation constants for cross-module access
let validation_constants = self.generate_validation_constants();
quote! {
#(#attributes)*
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#visibility enum #enum_name {
#(
#(#variant_attrs)*
#variant_names
),*
}
impl waddling_errors::ComponentId for #enum_name {
fn as_str(&self) -> &'static str {
self.const_as_str()
}
}
impl #enum_name {
/// Get the string value of this component (const-compatible)
///
/// Returns the VALUE field from the component definition,
/// or the variant name if no explicit value was specified.
pub const fn const_as_str(&self) -> &'static str {
match self {
#(#as_str_arms),*
}
}
/// Look up a component variant by its string value
pub fn from_str(s: &str) -> Option<Self> {
match s {
#(#from_str_arms),*,
_ => None,
}
}
}
// Validation constants for cross-module hash computation
#validation_constants
#metadata_impl
#auto_registrations
}
}
/// Generate string constants for cross-module access
/// These constants are pub to allow re-export via __wd_paths module
/// The constant name matches the variant identifier name
fn generate_validation_constants(&self) -> proc_macro2::TokenStream {
let constants: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let name_str = name.to_string();
let doc = format!(
"Component value constant for compile-time hash computation: {}",
name
);
quote! {
#[doc = #doc]
#[allow(non_upper_case_globals)]
pub const #name: &str = #name_str;
}
})
.collect();
quote! {
#(#constants)*
}
}
fn generate_metadata_impl(&self, enum_name: &Ident) -> proc_macro2::TokenStream {
let custom_methods = self.generate_custom_methods(enum_name);
let trait_impl = self.generate_documented_trait_impl(enum_name);
quote! {
#custom_methods
#trait_impl
}
}
fn generate_custom_methods(&self, enum_name: &Ident) -> proc_macro2::TokenStream {
// Generate role-based docs arms
let docs_pub_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let docs = v
.metadata
.as_ref()
.and_then(|m| m.docs_pub.as_ref())
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #docs }
})
.collect();
let docs_dev_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let docs = v
.metadata
.as_ref()
.and_then(|m| m.docs_dev.as_ref())
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #docs }
})
.collect();
let docs_int_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let docs = v
.metadata
.as_ref()
.and_then(|m| m.docs_int.as_ref())
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #docs }
})
.collect();
let introduced_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let intro = v
.metadata
.as_ref()
.and_then(|m| m.introduced.as_ref())
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #intro }
})
.collect();
let deprecated_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let depr = v
.metadata
.as_ref()
.and_then(|m| m.deprecated.as_ref())
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #depr }
})
.collect();
// Generate role-based examples arms
let examples_pub_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let examples = v
.metadata
.as_ref()
.and_then(|m| m.examples_pub.as_ref())
.map(|arr| quote! { &[#(#arr),*] as &[&str] })
.unwrap_or_else(|| quote! { &[] as &[&str] });
quote! { Self::#name => #examples }
})
.collect();
let examples_dev_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let examples = v
.metadata
.as_ref()
.and_then(|m| m.examples_dev.as_ref())
.map(|arr| quote! { &[#(#arr),*] as &[&str] })
.unwrap_or_else(|| quote! { &[] as &[&str] });
quote! { Self::#name => #examples }
})
.collect();
let examples_int_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let examples = v
.metadata
.as_ref()
.and_then(|m| m.examples_int.as_ref())
.map(|arr| quote! { &[#(#arr),*] as &[&str] })
.unwrap_or_else(|| quote! { &[] as &[&str] });
quote! { Self::#name => #examples }
})
.collect();
let tags_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let tags = v
.metadata
.as_ref()
.and_then(|m| m.tags.as_ref())
.map(|arr| quote! { &[#(#arr),*] })
.unwrap_or_else(|| quote! { &[] });
quote! { Self::#name => #tags }
})
.collect();
quote! {
#[cfg(feature = "metadata")]
impl #enum_name {
/// Get introduction version/date
pub const fn introduced(&self) -> Option<&'static str> {
match self {
#(#introduced_arms),*
}
}
/// Get deprecation info
pub const fn deprecated(&self) -> Option<&'static str> {
match self {
#(#deprecated_arms),*
}
}
/// Get documentation for the given role
pub fn docs_for_role(&self, role: waddling_errors::Role) -> Option<&'static str> {
use waddling_errors::Role;
match role {
Role::Public => match self {
#(#docs_pub_arms),*
},
Role::Developer => match self {
#(#docs_dev_arms),*
}.or_else(|| match self {
#(#docs_pub_arms),*
}),
Role::Internal => match self {
#(#docs_int_arms),*
}.or_else(|| match self {
#(#docs_dev_arms),*
}).or_else(|| match self {
#(#docs_pub_arms),*
}),
}
}
/// Get examples for the given role
pub fn examples_for_role(&self, role: waddling_errors::Role) -> &'static [&'static str] {
use waddling_errors::Role;
// Use hierarchical fallback: try role-specific, then fallback to less restrictive
let (primary, fallback1, fallback2) = match role {
Role::Public => (
match self { #(#examples_pub_arms),* },
&[] as &[&str],
&[] as &[&str],
),
Role::Developer => (
match self { #(#examples_dev_arms),* },
match self { #(#examples_pub_arms),* },
&[] as &[&str],
),
Role::Internal => (
match self { #(#examples_int_arms),* },
match self { #(#examples_dev_arms),* },
match self { #(#examples_pub_arms),* },
),
};
if !primary.is_empty() {
primary
} else if !fallback1.is_empty() {
fallback1
} else {
fallback2
}
}
/// Get tags
pub const fn tags(&self) -> &'static [&'static str] {
match self {
#(#tags_arms),*
}
}
}
}
}
fn generate_documented_trait_impl(&self, enum_name: &Ident) -> proc_macro2::TokenStream {
// Generate ComponentIdDocumented trait implementation
// Aggregates role-based fields, prioritizing: pub > dev > int
let docs_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
// Aggregate docs: prefer pub, fallback to dev, then int
let docs = v
.metadata
.as_ref()
.and_then(|m| {
m.docs_pub
.as_ref()
.or(m.docs_dev.as_ref())
.or(m.docs_int.as_ref())
})
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
quote! { Self::#name => #docs }
})
.collect();
let examples_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
// Aggregate examples: prefer pub, fallback to dev, then int
let examples = v
.metadata
.as_ref()
.and_then(|m| {
m.examples_pub
.as_ref()
.or(m.examples_dev.as_ref())
.or(m.examples_int.as_ref())
})
.map(|arr| quote! { &[#(#arr),*] as &[&str] })
.unwrap_or_else(|| quote! { &[] as &[&str] });
quote! { Self::#name => #examples }
})
.collect();
let tags_arms: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let tags = v
.metadata
.as_ref()
.and_then(|m| m.tags.as_ref())
.map(|arr| quote! { &[#(#arr),*] })
.unwrap_or_else(|| quote! { &[] });
quote! { Self::#name => #tags }
})
.collect();
quote! {
#[cfg(feature = "metadata")]
impl waddling_errors::ComponentIdDocumented for #enum_name {
fn description(&self) -> Option<&'static str> {
match self {
#(#docs_arms),*
}
}
fn examples(&self) -> &'static [&'static str] {
match self {
#(#examples_arms),*
}
}
fn tags(&self) -> &'static [&'static str] {
match self {
#(#tags_arms),*
}
}
}
}
}
fn generate_auto_registration(&self, enum_name: &Ident) -> proc_macro2::TokenStream {
// Generate unique const name for formats based on enum name
let formats_const_name = Ident::new(
&format!(
"__COMPONENT_FORMATS_{}",
enum_name.to_string().to_uppercase()
),
proc_macro2::Span::call_site(),
);
// Extract format strings if present
let format_strs: Vec<String> = if let Some(formats) = &self.auto_register_formats {
formats.iter().map(|f| f.to_string()).collect()
} else {
vec![]
};
let format_literals = format_strs.iter().map(|s| s.as_str());
// Generate auto-registration code for each component variant
let registrations: Vec<_> = self
.variants
.iter()
.map(|v| {
let name = &v.name;
let name_str = name.to_string();
// Extract metadata fields (aggregate role-based fields)
let description = v
.metadata
.as_ref()
.and_then(|m| {
m.docs_pub
.as_ref()
.or(m.docs_dev.as_ref())
.or(m.docs_int.as_ref())
})
.map(|lit| quote! { Some(#lit) })
.unwrap_or_else(|| quote! { None });
let examples = v
.metadata
.as_ref()
.and_then(|m| {
m.examples_pub
.as_ref()
.or(m.examples_dev.as_ref())
.or(m.examples_int.as_ref())
})
.map(|arr| quote! { &[#(#arr),*] })
.unwrap_or_else(|| quote! { &[] });
let tags = v
.metadata
.as_ref()
.and_then(|m| m.tags.as_ref())
.map(|arr| quote! { &[#(#arr),*] })
.unwrap_or_else(|| quote! { &[] });
let related = v
.metadata
.as_ref()
.and_then(|m| m.related.as_ref())
.map(|arr| quote! { &[#(#arr),*] })
.unwrap_or_else(|| quote! { &[] });
// Generate unique function name for this variant
let register_fn_name = Ident::new(
&format!(
"__register_component_{}_{}",
enum_name.to_string().to_lowercase(),
name_str.to_lowercase()
),
proc_macro2::Span::call_site(),
);
quote! {
#[cfg(all(feature = "auto-register", feature = "metadata"))]
#[::ctor::ctor]
fn #register_fn_name() {
::waddling_errors::registry::register_component(
#name_str,
#description,
#examples,
#tags,
#related,
#formats_const_name,
module_path!(),
env!("CARGO_PKG_NAME"),
);
}
}
})
.collect();
quote! {
// Generate static formats array
#[cfg(all(feature = "auto-register", feature = "metadata"))]
const #formats_const_name: &[&str] = &[#(#format_literals),*];
#(#registrations)*
}
}
}