waddling-errors-macros 0.7.3

Procedural macros for structured error codes with compile-time validation and taxonomy enforcement
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
//! no_std WASM Compatibility Example - Macros Edition
//!
//! This example demonstrates the build-time vs runtime separation:
//!
//! ## Build Time (std environment - developer's machine)
//! - Macros run and generate code
//! - Documentation generation happens (HTML/JSON)
//! - Auto-registration occurs
//! - File I/O for outputs
//!
//! ## Runtime (no_std environment - embedded/WASM/etc)
//! - Generated diagnostic constants work without std
//! - No heap allocations
//! - Zero-cost abstractions
//! - Perfect for constrained environments
//!
//! ## Key Insight
//! Procedural macros ALWAYS run in std (at compile time), but the CODE THEY
//! GENERATE can be no_std compatible. Your embedded crate can be `#![no_std]`
//! even though macros ran with std at build time!
//!
//! ## Build Commands
//!
//! ```bash
//! # Regular build (demonstrates no_std-compatible generated code)
//! cargo run --example no_std_wasm --features metadata
//!
//! # For actual WASM no_std target (user's crate would be #![no_std])
//! cargo build --example no_std_wasm --target wasm32-unknown-unknown --no-default-features --features metadata
//! ```

// Primaries intentionally use CamelCase to match E.Component.Primary.SEQUENCE format
#![allow(non_upper_case_globals)]

// Compile-time feature check with helpful error message
#[cfg(not(feature = "metadata"))]
compile_error!(
    "\n\n\
    โŒ This example requires the 'metadata' feature!\n\
    \n\
    The diag! macro generates DiagnosticRuntime structs that include\n\
    role-gated fields (hints_runtime_gated, hints_both_gated, etc.)\n\
    which are only compiled when the 'metadata' feature is enabled.\n\
    \n\
    Run this example with:\n\
    \n\
    cargo run --example no_std_wasm --features metadata\n\
    \n\
    Or use --all-features to enable everything:\n\
    \n\
    cargo run --example no_std_wasm --all-features\n\
    "
);

#[cfg(feature = "metadata")]
use waddling_errors::{Code, Severity};
#[cfg(feature = "metadata")]
use waddling_errors_macros::{diag, setup};

// ============================================================================
// Macros run at BUILD TIME (with std on developer's machine)
// But they GENERATE no_std compatible code that runs at RUNTIME
// ============================================================================

#[cfg(feature = "metadata")]
pub mod components {
    use waddling_errors_macros::component;

    component! {
        pub enum Component {
            Sensor {
                docs: "Sensor reading and monitoring",
                tags: ["hardware", "io"],
            },

            Actuator {
                docs: "Actuator control and feedback",
                tags: ["hardware", "control"],
            },

            Network {
                docs: "Network communication",
                tags: ["Network", "communication"],
            },

            Storage {
                docs: "Data persistence",
                tags: ["Storage", "persistence"],
            },
        }
    }

    pub use Component::*;
}

#[cfg(feature = "metadata")]
pub mod primaries {
    use waddling_errors_macros::primary;

    primary! {
        pub enum Primary {
            Timeout {
                description: "Operation timed out",
                tags: ["Timeout", "async"],
            },

            Invalid {
                description: "Invalid data or state",
                tags: ["validation"],
            },

            NotFound {
                description: "Resource not found",
                tags: ["missing"],
            },

            Corrupted {
                description: "Data corruption detected",
                tags: ["integrity"],
            },
        }
    }

    pub use Primary::*;
}

// Sequences generate const u16 values (no_std compatible at runtime)
#[cfg(feature = "metadata")]
pub mod sequences {
    use waddling_errors_macros::sequence;

    sequence! {
        MISSING(1) {
            description: "Sensor reading missing",
            typical_severity: "Error",
            hints: ["Check sensor connection"],
        },

        INVALID(2) {
            description: "Sensor reading invalid",
            typical_severity: "Error",
            hints: ["Validate sensor data"],
        },

        TIMEOUT(3) {
            description: "Sensor read timeout",
            typical_severity: "Error",
            hints: ["Increase timeout value"],
        },

        CALIBRATION(4) {
            description: "Sensor calibration error",
            typical_severity: "Warning",
            hints: ["Run calibration procedure"],
        },
    }
}

// Empty stubs for non-feature case\n#[cfg(not(feature = \"metadata\"))]\npub mod components {}\n#[cfg(not(feature = \"metadata\"))]\npub mod primaries {}\n#[cfg(not(feature = \"metadata\"))]\npub mod sequences {}

// Setup paths for diag! macro to find sequences
// (default mode now requires sequence validation)
#[cfg(feature = "metadata")]
setup! {
    components = crate::components,
    primaries = crate::primaries,
    sequences = crate::sequences,
}

// ============================================================================
// Define Diagnostics using diag! macro
// The macro generates DiagnosticRuntime constants (no_std compatible)
// ============================================================================

// Sensor diagnostics
#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    E.Sensor.Timeout.TIMEOUT: {
        message: "Sensor read operation timed out after waiting",
        hints: ["Increase timeout duration", "Check sensor connection"],
        tags: ["hardware", "Timeout"],
    },
}

#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    E.Sensor.Invalid.INVALID: {
        message: "Sensor returned invalid data",
        hints: ["Check sensor calibration", "Verify sensor is operational"],
        tags: ["hardware", "validation"],
    },
}

#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    W.Sensor.Timeout.MISSING: {
        message: "Sensor data is missing but operation can continue",
        hints: ["Sensor may be disconnected"],
        tags: ["hardware", "warning"],
    },
}

// Network diagnostics
#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    C.Network.Timeout.TIMEOUT: {
        message: "Network connection timeout - critical service unavailable",
        hints: ["Check network connectivity", "Verify service is running"],
        tags: ["Network", "critical"],
    },
}

// Storage diagnostics
#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    E.Storage.Corrupted.CALIBRATION: {
        message: "Storage data corruption detected",
        hints: ["Run data integrity check", "Restore from backup"],
        tags: ["Storage", "integrity"],
    },
}

// ============================================================================
// The generated code above is RUNTIME no_std compatible!
// Even though the macros ran with std at compile time
// ============================================================================

/// Test that macro-generated types work as expected
#[cfg(feature = "metadata")]
fn test_macro_generated_types() {
    use crate::components::Component;
    use crate::primaries::Primary;
    use waddling_errors::{ComponentId, PrimaryId};

    // Component enum generated by macro
    assert_eq!(Component::Sensor.as_str(), "Sensor");
    assert_eq!(Component::Actuator.as_str(), "Actuator");
    assert_eq!(Component::Network.as_str(), "Network");
    assert_eq!(Component::Storage.as_str(), "Storage");

    // Primary enum generated by macro
    assert_eq!(Primary::Timeout.as_str(), "Timeout");
    assert_eq!(Primary::Invalid.as_str(), "Invalid");
    assert_eq!(Primary::NotFound.as_str(), "NotFound");
    assert_eq!(Primary::Corrupted.as_str(), "Corrupted");

    // Sequence constants generated by macro
    assert_eq!(sequences::MISSING, 1);
    assert_eq!(sequences::INVALID, 2);
    assert_eq!(sequences::TIMEOUT, 3);
    assert_eq!(sequences::CALIBRATION, 4);
}

/// Test creating error codes with macro-generated types
#[cfg(feature = "metadata")]
fn test_error_codes_with_macros() {
    use crate::components::Component;
    use crate::primaries::Primary;
    use waddling_errors::{Code, error, warning};

    // These Code structs work in no_std environments!
    let sensor_err: Code<Component, Primary> =
        error(Component::Sensor, Primary::Timeout, sequences::TIMEOUT);
    assert_eq!(sensor_err.code(), "E.Sensor.Timeout.003");
    assert_eq!(sensor_err.severity(), Severity::Error);
    assert_eq!(sensor_err.sequence(), 3);

    let sensor_warn: Code<Component, Primary> =
        warning(Component::Sensor, Primary::Invalid, sequences::INVALID);
    assert_eq!(sensor_warn.code(), "W.Sensor.Invalid.002");
    assert_eq!(sensor_warn.severity(), Severity::Warning);
}

/// Test diag! macro generated diagnostics (the main feature!)
#[cfg(feature = "metadata")]
fn test_diagnostic_constants() {
    // Diagnostics are generated as DiagnosticRuntime constants
    // These work in no_std environments!

    // Check runtime fields
    assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.code, "E.Sensor.Timeout.TIMEOUT");
    assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.severity, Severity::Error);
    assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.component, "Sensor");
    assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.primary, "Timeout");
    assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.sequence, "TIMEOUT");
    // Note: sequence_value is managed internally by diag! macro
    assert_eq!(
        E_SENSOR_TIMEOUT_TIMEOUT.message,
        "Sensor read operation timed out after waiting"
    );

    // Note: The hints: field in diag! has default visibility 'CR (Both)
    // which populates hints_both_gated (compile-time and runtime)
    #[cfg(feature = "metadata")]
    {
        // hints_both_gated contains ("hint_text", "Role") tuples
        assert!(!E_SENSOR_TIMEOUT_TIMEOUT.hints_both_gated.is_empty());
        assert_eq!(
            E_SENSOR_TIMEOUT_TIMEOUT.hints_both_gated[0].0,
            "Increase timeout duration"
        );
    }

    // Check tags are available at runtime via tags_gated (modern approach)
    // Note: tags field is deprecated, use tags_gated which includes role info
    #[cfg(feature = "metadata")]
    {
        assert!(!E_SENSOR_TIMEOUT_TIMEOUT.tags_gated.is_empty());
        assert_eq!(E_SENSOR_TIMEOUT_TIMEOUT.tags_gated[0].0, "hardware");
    }

    // Test another diagnostic
    assert_eq!(E_SENSOR_INVALID_INVALID.code, "E.Sensor.Invalid.INVALID");
    assert_eq!(E_SENSOR_INVALID_INVALID.severity, Severity::Error);

    // Test warning
    assert_eq!(W_SENSOR_TIMEOUT_MISSING.code, "W.Sensor.Timeout.MISSING");
    assert_eq!(W_SENSOR_TIMEOUT_MISSING.severity, Severity::Warning);

    // Test critical
    assert_eq!(C_NETWORK_TIMEOUT_TIMEOUT.code, "C.Network.Timeout.TIMEOUT");
    assert_eq!(C_NETWORK_TIMEOUT_TIMEOUT.severity, Severity::Critical);
}

/// Test that generated types have proper traits
#[cfg(feature = "metadata")]
fn test_trait_implementations() {
    use crate::components::Component;
    use crate::primaries::Primary;

    // Clone
    let comp1 = Component::Sensor;
    let comp2 = comp1;
    assert_eq!(comp1, comp2);

    // Copy
    let prim1 = Primary::Timeout;
    let prim2 = prim1;
    assert_eq!(prim1, prim2);

    // PartialEq
    assert_ne!(Component::Network, Component::Storage);

    // Debug is available (core::fmt::Debug doesn't need std)
    let _debug = format!("{:?}", Component::Sensor);
}

/// Demonstrate Result type usage (works in no_std)
#[cfg(feature = "metadata")]
fn simulate_sensor_read() -> Result<u32, Code<components::Component, primaries::Primary>> {
    use crate::components::Component;
    use crate::primaries::Primary;
    use waddling_errors::error;

    // Simulate a timeout error
    Err(error(
        Component::Sensor,
        Primary::Timeout,
        sequences::TIMEOUT,
    ))
}

#[cfg(feature = "metadata")]
fn test_result_handling() {
    use crate::components::Component;
    use crate::primaries::Primary;

    match simulate_sensor_read() {
        Ok(value) => println!("   Sensor value: {}", value),
        Err(code) => {
            assert_eq!(code.component(), Component::Sensor);
            assert_eq!(code.primary(), Primary::Timeout);
            assert_eq!(code.code(), "E.Sensor.Timeout.003");
            println!("   โœ“ Result handling with macro-generated types");
        }
    }
}

#[cfg(feature = "metadata")]
fn main() {
    println!("๐Ÿฆ† waddling-errors-macros: Build-time std, Runtime no_std");
    println!("===========================================================\n");

    println!("๐Ÿ’ก KEY CONCEPT:");
    println!("   โ€ข Macros run at BUILD TIME with std (on your dev machine)");
    println!("   โ€ข Generated code runs at RUNTIME in no_std (embedded/WASM)");
    println!("   โ€ข This is how serde, embedded-hal, and many crates work!\n");

    println!("๐Ÿ”ง What Happens at BUILD TIME (std environment):");
    println!("   โœ“ component! macro expands to enum + ComponentId impl");
    println!("   โœ“ primary! macro expands to enum + PrimaryId impl");
    println!("   โœ“ sequence! macro expands to const u16 values");
    println!("   โœ“ Doc generation (HTML/JSON) if doc-gen feature enabled");
    println!("   โœ“ Auto-registration if auto-register feature enabled");
    println!("   โœ“ All macro expansion happens with std available\n");

    println!("๐Ÿš€ What Happens at RUNTIME (no_std compatible):");
    println!("   โœ“ Generated enums and consts (zero cost)");
    println!("   โœ“ ComponentId and PrimaryId trait impls");
    println!("   โœ“ Code<Component, Primary> error codes");
    println!("   โœ“ No heap allocations");
    println!("   โœ“ No std dependency");
    println!("   โœ“ Works in embedded/WASM/bare metal\n");

    println!("๐Ÿ“‹ Running tests with macro-generated code:\n");

    test_macro_generated_types();
    println!("   โœ“ Macro-generated Component and Primary enums");
    println!("   โœ“ Macro-generated sequence constants");

    test_error_codes_with_macros();
    println!("   โœ“ Error codes with macro types");

    test_diagnostic_constants();
    println!("   โœ“ Diagnostic constants from diag! macro");

    test_trait_implementations();
    println!("   โœ“ Clone, Copy, PartialEq, Debug traits");

    test_result_handling();

    println!("\n๐ŸŽฏ Generated Code Structure:");
    println!("   component! {{ Sensor {{ ... }} }}");
    println!("   โ†“ EXPANDS TO (at compile time):");
    println!("   #[derive(Debug, Copy, Clone, PartialEq, Eq)]");
    println!("   pub enum Component {{ Sensor, ... }}");
    println!("   impl ComponentId for Component {{ ... }}");
    println!("   โ†“ RESULT (no_std compatible at runtime!)");

    println!("\n   diag! {{ E.Sensor.Timeout.TIMEOUT: {{ message: \"...\", ... }}, }}");
    println!("   โ†“ EXPANDS TO (at compile time):");
    println!("   pub const E_SENSOR_TIMEOUT_TIMEOUT: DiagnosticRuntime = ...");
    println!("   โ†“ RESULT (no_std compatible DiagnosticRuntime constant!)");

    println!("\nโœจ Macros You Can Use:");
    println!("   component!  - Generate Component enum (no_std output)");
    println!("   primary!    - Generate Primary enum (no_std output)");
    println!("   sequence!   - Generate const u16 values (no_std output)");
    println!("   diag!       - Generate DiagnosticRuntime constants (no_std output)");

    println!("\n๐Ÿ“ฆ For Embedded/WASM Deployment:");
    println!("   1. Use macros in your crate (they run at build time with std)");
    println!("   2. Mark your crate #![no_std] for runtime");
    println!("   3. Generated code works without std!");
    println!("   4. Optional: Enable doc-gen at build time for documentation");

    println!("\n๐Ÿ”ฌ Example User Crate Pattern:");
    println!("   // user_embedded_crate/src/lib.rs");
    println!("   #![no_std]  // Runtime is no_std!");
    println!("   ");
    println!("   use waddling_errors_macros::{{component, primary}};");
    println!("   ");
    println!("   // Macros run at build time (with std)");
    println!("   component! {{ Motor {{ value: \"MOTOR\", ... }} }}");
    println!("   ");
    println!("   // Generated code works in no_std at runtime!");
    println!("   fn read_motor() -> Result<u32, Code<Component, Primary>> {{ ... }}");

    println!("\n๐Ÿ“Š Build vs Runtime Separation:");
    println!("   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”");
    println!("   โ”‚ BUILD TIME (std on dev machine)             โ”‚");
    println!("   โ”‚ โ€ข Macros expand                             โ”‚");
    println!("   โ”‚ โ€ข Doc generation (optional)                 โ”‚");
    println!("   โ”‚ โ€ข Code generation                           โ”‚");
    println!("   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜");
    println!("                        โ†“");
    println!("   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”");
    println!("   โ”‚ RUNTIME (no_std on target device)           โ”‚");
    println!("   โ”‚ โ€ข Generated enums and consts                โ”‚");
    println!("   โ”‚ โ€ข Error codes (zero cost)                   โ”‚");
    println!("   โ”‚ โ€ข No heap, no std                           โ”‚");
    println!("   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜");

    println!("\nโœ… All tests passed!");
    println!("   Macro-generated code is fully no_std compatible at runtime!");

    println!("\n๐Ÿงช WASM Testing:");
    println!("   To actually test in WASM environment:");
    println!("   1. cargo build --example no_std_wasm --target wasm32-unknown-unknown");
    println!("   2. Use wasm-bindgen to create JS bindings");
    println!("   3. Run in browser or Node.js");
    println!("   ");
    println!("   Or for WASI (WASM with minimal system interface):");
    println!("   cargo build --example no_std_wasm --target wasm32-wasi");
    println!("   wasmtime target/wasm32-wasi/debug/examples/no_std_wasm.wasm");
}

// ============================================================================
// WASM-specific entry point for testing in actual WASM environment
// ============================================================================

#[cfg(all(target_family = "wasm", feature = "metadata"))]
#[unsafe(no_mangle)]
pub extern "C" fn run_tests() -> i32 {
    // Run all tests without println (not available in bare WASM)
    test_macro_generated_types();
    test_error_codes_with_macros();
    test_diagnostic_constants();
    test_trait_implementations();

    // Return 0 for success
    0
}

// Dummy main when feature not enabled
#[cfg(not(feature = "metadata"))]
fn main() {}