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
//! Procedural macros for waddling-errors
//!
//! This crate provides convenient macros for defining error code components,
//! primaries, and sequences with rich metadata support.
//!
//! # Macros
//!
//! - `component!` - Define component enums with automatic ComponentId impl
//! - `primary!` - Define primary enums with automatic PrimaryId impl
//! - `sequence!` - Define sequence constants with metadata
//!
//! # Examples
//!
//! ```ignore
//! use waddling_errors_macros::{component, primary, sequence};
//!
//! component! {
//! Auth,
//! Database {
//! docs: "Database operations",
//! tags: ["backend"],
//! },
//! }
//!
//! primary! {
//! Token,
//! Connection {
//! docs: "Connection errors",
//! },
//! }
//!
//! sequence! {
//! MISSING(001) {
//! description: "Item not found",
//! hints: ["Check if item exists"],
//! },
//! }
//! ```
use TokenStream;
/// Define component enums with automatic ComponentId trait implementation.
///
/// # WDP Naming Convention
///
/// Per WDP specification, component names SHOULD use **PascalCase**:
/// - ✅ `Auth`, `Database`, `ApiGateway`, `TokenValidator`
/// - ❌ `AUTH`, `DATABASE`, `API_GATEWAY` (non-standard)
///
/// Error codes follow the format: `E.Component.Primary.SEQUENCE`
/// - Example: `E.Auth.Token.EXPIRED` not `E.AUTH.TOKEN.EXPIRED`
///
/// # Metadata Fields
///
/// Supports all metadata fields in any order:
/// - `description` - Documentation string
/// - `introduced` - Version introduced
/// - `deprecated` - Deprecation notice
/// - `examples` - Array of example error codes
/// - `tags` - Array of category tags
///
/// # Examples
///
/// ```ignore
/// component! {
/// Auth, // Simple: "Auth"
/// Database { // With metadata
/// description: "Database operations",
/// introduced: "1.0.0",
/// tags: ["backend", "storage"],
/// },
/// }
///
/// // Generated code implements ComponentIdDocumented trait:
/// let desc = Component::Database.description(); // Trait method
/// let tags = Component::Database.tags();
/// ```
/// Define primary enums with automatic PrimaryId trait implementation.
///
/// # WDP Naming Convention
///
/// Per WDP specification, primary names SHOULD use **PascalCase**:
/// - ✅ `Token`, `Connection`, `Validation`, `RateLimit`
/// - ❌ `TOKEN`, `CONNECTION`, `VALIDATION` (non-standard)
///
/// Error codes follow the format: `E.Component.Primary.SEQUENCE`
/// - Example: `E.Database.Connection.TIMEOUT` not `E.DATABASE.CONNECTION.TIMEOUT`
///
/// # Metadata Fields
///
/// Supports all metadata fields in any order:
/// - `description` - Documentation string
/// - `introduced` - Version introduced
/// - `deprecated` - Deprecation notice
/// - `examples` - Array of example error codes
/// - `related` - Array of related primary codes
///
/// # Examples
///
/// ```ignore
/// primary! {
/// Token, // Simple: "Token"
/// Connection { // With metadata
/// description: "Connection errors",
/// related: ["Timeout", "Pool"],
/// },
/// }
///
/// // Generated code implements PrimaryIdDocumented trait:
/// let desc = Primary::Connection.description(); // Trait method
/// let related = Primary::Connection.related();
/// ```
/// Define sequence constants with rich metadata.
///
/// Supports all 5 metadata fields in any order:
/// - `description` - Human-readable description
/// - `typical_severity` - Typical severity level
/// - `hints` - Array of helpful hints
/// - `related` - Array of related sequences
/// - `introduced` - Version introduced
///
/// # Examples
///
/// ```ignore
/// sequence! {
/// MISSING(001), // Simple
/// CUSTOM(042) { // With metadata
/// description: "Custom logic error",
/// hints: ["Check business rules", "Verify input"],
/// related: ["043", "044"],
/// introduced: "1.2.0",
/// },
/// }
/// ```
/// Define complete diagnostic metadata with full 4-part error codes.
///
/// **This macro generates THREE constants**:
/// 1. `E_COMPONENT_PRIMARY_SEQUENCE` - Runtime metadata (always present)
/// 2. `E_COMPONENT_PRIMARY_SEQUENCE_DOCS` - Compile-time docs (with `metadata` feature)
/// 3. `E_COMPONENT_PRIMARY_SEQUENCE_COMPLETE` - Combined (with `metadata` feature)
///
/// # 4-Part Code Format
///
/// `Severity.Component.Primary.Sequence`
///
/// # Visibility Markers
///
/// Fields can have visibility markers to control where they're included:
/// - `'C` - Compile-time only (documentation generation, not in binary)
/// - `'R` - Runtime only (in production binary, not in docs)
/// - `'RC` or `'CR` - Both (default for most fields)
///
/// **Mnemonic**: `'CR` = Compile + Runtime (both contexts)
///
/// # Supported Fields (in any order)
///
/// **Core fields (always present):**
/// - `message` (required) - Message template with `{{field}}` placeholders
/// - `fields` (optional) - Array of non-PII field names used in message (referenced as `{{field}}`)
/// - `pii` (optional) - Array of PII field names (referenced as `{{pii/field}}` in message)
/// - `severity` (optional) - Override the severity from the code
///
/// **Fields with visibility markers:**
/// - `description ['C|'R|'RC|'CR]` - Human-readable description
/// - `hints ['C|'R|'RC|'CR]` - Array of helpful hints
/// - `role ['R|'RC|'CR]` - Role-based visibility
/// - `tags ['R]` - Categorization tags (runtime only)
/// - `related_codes ['R]` - Related error codes (runtime only)
/// - `code_snippet ['C]` - Code examples (compile-time only)
/// - `docs_url ['C]` - Documentation URL (compile-time only)
/// - `introduced ['C]` - Version introduced (compile-time only)
/// - `deprecated ['C]` - Deprecation notice (compile-time only)
///
/// # Examples
///
/// **Basic usage (defaults to 'RC - both contexts):**
/// ```ignore
/// diag! {
/// Error.Auth.Token.MISSING: {
/// message: "Token '{{token}}' not found",
/// fields: [token],
/// description: "API token missing", // Available in both
/// hints: ["Check your credentials"], // Available in both
/// },
/// }
/// ```
///
/// **With PII fields:**
/// ```ignore
/// diag! {
/// Error.Auth.Login.FAILED: {
/// message: "Login failed for {{pii/email}} at {{timestamp}}",
/// fields: [timestamp], // Non-PII: goes to `f` in wire protocol
/// pii: [email], // PII: goes to `pii.data` in wire protocol
/// description: "Authentication failed",
/// },
/// }
/// ```
///
/// **Advanced usage with visibility markers:**
/// ```ignore
/// diag! {
/// Error.Auth.Token.MISSING: {
/// message: "Token '{{token}}' not found",
/// fields: [token],
///
/// // Verbose docs for compile-time
/// description 'C: "Detailed explanation for documentation...",
///
/// // Short message for runtime
/// description 'R: "Token missing",
///
/// // Different hints for different audiences
/// hints 'C: ["For developers: Check auth flow", "See RFC 6750"],
/// hints 'R: ["Include Authorization header", "Verify API key"],
/// hints 'CR: ["Contact support if needed"], // 'RC also works
///
/// // Runtime categorization
/// role 'R: "Public",
/// tags: ["auth", "security"],
///
/// // Compile-time documentation
/// code_snippet: {
/// wrong: "fetch(url)",
/// correct: "fetch(url, { headers: { 'Authorization': 'Bearer <token>' } })",
/// },
/// docs_url: "https://docs.example.com/auth",
/// introduced: "1.0.0",
/// },
/// }
/// ```
///
/// # Generated Code
///
/// This generates THREE constants:
///
/// ```ignore
/// // Always generated (no feature flags)
/// pub const E_AUTH_TOKEN_MISSING: DiagnosticRuntime = /* runtime metadata */;
///
/// // Only with metadata feature
/// #[cfg(feature = "metadata")]
/// pub const E_AUTH_TOKEN_MISSING_DOCS: DiagnosticDocs = /* compile-time docs */;
///
/// #[cfg(feature = "metadata")]
/// pub const E_AUTH_TOKEN_MISSING_COMPLETE: DiagnosticComplete = /* both */;
/// ```
///
/// Frameworks can use the runtime constant for error handling, and the complete
/// constant for documentation generation.
/// Attribute macro for automatic documentation generation
///
/// Wraps `diag!` and generates registration code for specified formats.
///
/// # Examples
///
/// ```ignore
/// #[doc_gen("json", "html")]
/// diag! {
/// E.Auth.Token.MISSING: {
/// message: "Token not found",
/// // ...
/// },
/// }
/// ```
///
/// This generates a `__doc_gen_registry` module with format tracking.
/// Generates documentation registration function for a diagnostic.
///
/// This macro creates a registration function that can be called to register
/// a diagnostic with a DocRegistry for documentation generation.
///
/// # Example
/// ```rust,ignore
/// // Define diagnostic
/// diag! {
/// E.Auth.Token.EXPIRED: {
/// message: "Token expired",
/// // ...
/// },
/// }
///
/// // Generate registration code
/// doc_gen_register! {
/// E.Auth.Token.EXPIRED => ["json", "html"]
/// }
///
/// // Later, use the generated function:
/// let mut registry = DocRegistry::new("myapp", "1.0.0");
/// register_e_auth_token_expired_complete_for_doc_gen(&mut registry);
/// ```
/// Mark modules or files as belonging to a specific component.
///
/// This attribute enables:
/// - **Discovery**: Find all files in a component via grep or IDE search
/// - **Navigation**: IDE integration for "jump to component" features
/// - **Documentation**: Auto-group errors by component in generated docs
/// - **Organization**: Track scattered components across different folders
///
/// # Syntax
///
/// ```ignore
/// #[in_component(ComponentName)]
/// ```
///
/// # Examples
///
/// **Marking a folder** (via mod.rs):
/// ```ignore
/// // src/auth/mod.rs
/// #[in_component(Auth)]
///
/// mod token;
/// mod session;
/// ```
///
/// **Marking scattered files**:
/// ```ignore
/// // src/api/middleware.rs
/// #[in_component(Auth)] // Auth logic here too!
///
/// use waddling_errors::diag;
/// // ... Auth-related errors ...
/// ```
///
/// **Finding all Auth components**:
/// ```bash
/// grep -r "#\[in_component(Auth)\]" src/
/// ```
///
/// # Metadata Generated
///
/// The macro creates a hidden module with:
/// - Component name constant
/// - Module path (for IDE integration)
/// - File path (for tooling)
/// - Marker trait (for discovery)
/// Configure module paths for waddling-errors definitions.
///
/// This macro sets up path aliases that `diag!` uses to resolve component,
/// primary, and sequence definitions. This enables flexible project structure
/// where definitions can be placed in any module.
///
/// **Must be called once at the crate root (lib.rs or main.rs).**
///
/// # Syntax
///
/// ```ignore
/// waddling_errors::setup! {
/// components = crate::my_components,
/// primaries = crate::error_primaries,
/// sequences = crate::my_sequences,
/// }
/// ```
///
/// # What it Generates
///
/// ```ignore
/// pub(crate) mod __wd_paths {
/// pub use crate::my_components as components;
/// pub use crate::error_primaries as primaries;
/// pub use crate::my_sequences as sequences;
/// }
/// ```
///
/// # Why Use This
///
/// Without `setup!`, `diag!` expects definitions at fixed paths:
/// - `crate::components::*`
/// - `crate::primaries::*`
/// - `crate::sequences::*`
///
/// With `setup!`, you can place definitions anywhere and `diag!` will find them.
///
/// # Example Project Structure
///
/// ```ignore
/// // src/lib.rs
/// waddling_errors::setup! {
/// components = crate::errors::components,
/// primaries = crate::errors::primaries,
/// sequences = crate::errors::sequences,
/// }
///
/// mod errors {
/// pub mod components { /* component! definitions */ }
/// pub mod primaries { /* primary! definitions */ }
/// pub mod sequences { /* sequence! definitions */ }
/// }
///
/// mod api {
/// // diag! here works - finds definitions via __wd_paths
/// diag! { E.Api.Auth.001: { ... } }
/// }
/// ```
///
/// # Partial Configuration
///
/// You can specify only some paths - others will use defaults:
///
/// ```ignore
/// waddling_errors::setup! {
/// sequences = crate::my_sequences,
/// // components defaults to crate::components
/// // primaries defaults to crate::primaries
/// }
/// ```
///
/// # No Collision Between Crates
///
/// Each crate has its own `__wd_paths` module (via `crate::`), so a library
/// using waddling-errors won't collide with an application using it too.
/// Register a component location without attaching to a module.
///
/// This is a standalone macro that registers where a component's code lives,
/// without requiring an attribute on a module. It's more flexible than
/// `#[in_component]` and supports:
///
/// - **Multiple components per file** - Register several component locations
/// - **File-level usage** - No need to wrap code in a module
/// - **Folder markers** - Use in `mod.rs` to mark entire folders
/// - **Role-based security** - Control visibility in documentation
///
/// # Syntax
///
/// ```ignore
/// component_location!(ComponentName); // Default: Internal (secure)
/// component_location!(ComponentName, role = public); // Public: visible to everyone
/// component_location!(ComponentName, role = developer); // Developer: devs + internal
/// component_location!(ComponentName, role = internal); // Internal: team only (explicit)
/// ```
///
/// # Examples
///
/// **Single component location:**
/// ```ignore
/// // src/auth/jwt.rs
/// use waddling_errors_macros::component_location;
///
/// component_location!(Auth); // Defaults to internal role
///
/// // ... your JWT code and diag! definitions ...
/// ```
///
/// **Multiple components in same file:**
/// ```ignore
/// // src/shared/crypto.rs - shared between Auth and Crypto components
/// component_location!(Auth, role = internal);
/// component_location!(Crypto, role = developer);
///
/// // ... shared cryptographic utilities ...
/// ```
///
/// **Public documentation example:**
/// ```ignore
/// // examples/auth_usage.rs
/// component_location!(Auth, role = public);
///
/// // ... example code for public documentation ...
/// ```
///
/// **Folder marker (in mod.rs):**
/// ```ignore
/// // src/database/mod.rs
/// component_location!(Database);
///
/// pub mod connection;
/// pub mod queries;
/// pub mod migrations;
/// ```
///
/// # Generated Code
///
/// For `component_location!(Auth, role = public)` the macro generates:
///
/// ```ignore
/// pub mod __component_loc_auth {
/// pub const COMPONENT: &str = "Auth"; // Preserves case to match component!
/// pub const FILE: &str = "src/myfile.rs"; // file!() path
/// pub const MODULE_PATH: &str = "mymod"; // module_path!()
/// pub const ROLE: Option<Role> = Some(Role::Public);
///
/// #[cfg(feature = "metadata")]
/// pub fn register(registry: &mut DocRegistry) {
/// registry.register_component_location_with_role(COMPONENT, FILE, ROLE);
/// }
/// }
/// ```
///
/// # Accessing Generated Constants
///
/// Access constants via the generated marker module `__component_loc_<name>`:
///
/// ```ignore
/// component_location!(Auth, role = public);
/// component_location!(Crypto, role = developer);
///
/// fn main() {
/// // Access constants (preserves original case to match component! registration)
/// assert_eq!(__component_loc_auth::COMPONENT, "Auth");
/// assert_eq!(__component_loc_crypto::COMPONENT, "Crypto");
///
/// // Check file paths
/// println!("Auth location: {}", __component_loc_auth::FILE);
/// }
/// ```
///
/// # Registration
///
/// With `auto-register` feature, locations are registered automatically via `ctor`.
/// Manual registration is also supported:
///
/// ```ignore
/// let mut registry = DocRegistry::new("myapp", "1.0.0");
/// __component_loc_auth::register(&mut registry);
/// __component_loc_crypto::register(&mut registry);
/// ```
///
/// # Why Use This Over `#[in_component]`?
///
/// | Feature | `#[in_component]` | `component_location!` |
/// |---------|------------------|----------------------|
/// | Attach to module | ✅ Required | ❌ Not needed |
/// | Multiple per file | ❌ Awkward | ✅ Easy |
/// | File-level use | ❌ Needs wrapper | ✅ Direct |
/// | Non-module items | ⚠️ Creates sibling mod | ✅ Clean |
///
/// Use `component_location!` when you want to mark locations without
/// restructuring your code around modules.