csv-codegen 0.2.3

A Rust procedural macro that transforms CSV data into safe, zero-cost code. Generate match arms, loops, and nested queries directly from CSV files, ensuring type safety and deterministic code generation.
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
use insta::{assert_debug_snapshot, assert_snapshot};
use std::str::FromStr;

#[test]
fn test_simple() {
    fn handle_citrus(fruit_id: u16) -> &'static str {
        csv_codegen::csv_template!("fruits.csv", #each(category == "citrus") {
            match fruit_id {
                #each {
                    #({id}) => concat!("Found citrus: ", #("{name}")),
                }
                _ => "Not a citrus fruit",
            }
        })
    }
    assert_eq!(handle_citrus(5), "Not a citrus fruit");
    assert_eq!(handle_citrus(3), "Found citrus: Lime");
}

#[test]
fn test_subquery() {
    csv_codegen::csv_template!("products.csv", #each(active == true) {
        #[derive(Debug, PartialEq)]
        enum #Type({category}) {
            #each {
                #Type({name}),
            }
        }
        impl FromStr for #Type({category}) {
            type Err = ();
            fn from_str(string: &str) -> Result<Self, Self::Err> {
                match string {
                    #each {
                        #("{name}") => Ok(Self::#Type({name})),
                    }
                    _ => Err(()),
                }
            }
        }
    });
    let product: Power = "Phone Charger".parse().unwrap();
    assert_eq!(product, Power::PhoneCharger);
}

#[test]
fn i18n_example() {
    csv_codegen::csv_template!("i18n.csv", {
        enum Language {
            En,
            #each {
                #Type({language}),
            }
        }
    });

    macro_rules! format_i18n {
        ($language:expr, $format_str_en:literal @ $context:literal $($args:tt)*) => {
            csv_codegen::csv_template!("i18n.csv", #find(format_str_en == $format_str_en){
                match $language {
                    Language::En => format!(#("{format_str_en}") $($args)*),
                    #each {
                        Language::#Type({language}) => format!(#("{format_str}") $($args)*),
                    }
                }
            })
        };
        ($language:expr, $format_str_en:literal $($args:tt)*) => {
            format_i18n!($language, $format_str_en@"" $($args)*)
        };
    }

    assert_eq!(
        format_i18n!(Language::De, "Close {item}"@"verb_action", item = "#2"),
        "#2 schließen"
    );
    assert_eq!(
        format_i18n!(Language::Es, "File not found"),
        "Archivo no encontrado"
    );
    assert_eq!(
        format_i18n!(Language::En, "Save {count} items", count = 2),
        "Save 2 items"
    )
}

#[test]
fn test_categories_ordered() {
    csv_codegen::csv_template!("products.csv", #each {
        fn #ident({category})() -> Vec<&'static str> {
            vec!(
                #each {
                    #("{name}"),
                }
            )
        }
    });

    assert_debug_snapshot!(accessories(), @r###"
    [
        "Smart Watch",
        "Tablet Case",
    ]
    "###);

    assert_debug_snapshot!(computer_peripherals(), @r###"
    [
        "Gaming Mouse",
        "Keyboard",
        "Webcam",
    ]
    "###);
}

#[test]
fn test_prefix() {
    csv_codegen::csv_template!("products.csv", {
        fn get_price(name: &str) -> Option<f64> {
            match name {
                #each(price != ""){
                    #("{name}") => Some(#({price}_f64)),
                }
                _ => None,
            }
        }
    });

    assert_snapshot!(get_price("Ergonomic Chair").unwrap(), @"399.99");
}

#[test]
fn pivot() {
    csv_codegen::csv_template!("sales.csv", pivot("q1_sales"..="q4_sales", quarter, sales), #each {
        #[allow(unused)]
        struct #Type({product}Sales);
        impl #Type({product}Sales) {
            #each {
                #[allow(unused)]
                pub const #CONST({quarter}): u32 = #({sales}_u32);
            }
        }
    });
    assert_eq!(SmartWatchSales::Q_2_SALES, 180);
}

#[derive(Debug, Clone)]
pub struct HighQualityProduct {
    pub name: &'static str,
    pub quality_metrics: QualityMetrics,
    pub certification: CertificationLevel,
}

#[derive(Debug, Clone)]
pub struct QualityMetrics {
    pub defect_rate: f32,
    pub batch_size: u32,
    pub factory: &'static str,
    pub line: &'static str,
}

csv_codegen::csv_template!("quality_data.csv", {
    #[derive(Debug, Clone, PartialEq)]
    pub enum CertificationLevel {
        #each {
            #Type({certification_status}),
        }
    }
});

csv_codegen::csv_template!("quality_data.csv", #each {
    pub mod #ident({factory}_manufacturing) {
        use super::*;

        #each {
            pub struct #Type(Line{line}Quality) {
                pub line_identifier: &'static str,
                pub tier_one_products: Vec<HighQualityProduct>,
            }

            impl #Type(Line{line}Quality) {
                pub fn build() -> Self {
                    Self {
                        line_identifier: #("{line}"),
                        tier_one_products: vec![
                            #each(quality_tier == "tier_1"){
                                HighQualityProduct {
                                    name: #("{product}"),
                                    quality_metrics: QualityMetrics {
                                        defect_rate: #({defect_rate}_f32),
                                        batch_size: #({batch_size}_u32),
                                        factory: #("{factory}"),
                                        line: #("{line}"),
                                    },
                                    certification: CertificationLevel::#Type({certification_status}),
                                },
                            }
                        ],
                    }
                }
            }
        }
    }
});

#[test]
fn complex() {
    let department = university_hospital_medical::cardiac_system();
    assert_debug_snapshot!(department, @r###"
    Department {
        name: "cardiac",
        patients: [
            Patient {
                id: "p018",
                vitals: Vitals {
                    age: 66,
                    bp: 100,
                    hr: 109,
                    temp: 36.8,
                },
                assessment: FullLabs {
                    wbc: 6500,
                    creatinine: 1.7,
                    risk_score: 1,
                },
            },
            Patient {
                id: "p019",
                vitals: Vitals {
                    age: 54,
                    bp: 115,
                    hr: 94,
                    temp: 38.1,
                },
                assessment: VitalsOnly {
                    warning_score: 0,
                    infection_risk: Clinical {
                        fever: true,
                    },
                },
            },
        ],
    }
    "###)
}

// complex example using #else
csv_codegen::csv_template!("patient_data.csv", #each {
    pub mod #ident({hospital}_medical) {
        use super::*;

        #each {
            pub fn #ident({department}_system)() -> Department { Department {
                name: #("{department}"),
                patients: vec![
                    #each(age != "" && systolic_bp != "" && heart_rate != ""){
                        Patient {
                            id: #("{patient_id}"),
                            vitals: Vitals {
                                age: #({age}_u8),
                                bp: #({systolic_bp}_u16),
                                hr: #({heart_rate}_u16),
                                temp: #({temperature}_f32),
                            },
                            assessment: #find(white_cell_count != "" && creatinine != ""){
                                Assessment::FullLabs {
                                    wbc: #({white_cell_count}_u32),
                                    creatinine: #({creatinine}_f32),
                                    risk_score: calculate_risk(#({systolic_bp}_u16), #({creatinine}_f32)),
                                }
                            }
                            #else{
                                Assessment::VitalsOnly {
                                    warning_score: calculate_warning(
                                        #({systolic_bp}_u16),
                                        #({heart_rate}_u16)
                                    ),
                                    infection_risk: #find(white_cell_count != ""){
                                        InfectionRisk::Lab(#({white_cell_count}_u32))
                                    }
                                    #else{
                                        InfectionRisk::Clinical {
                                            fever: #({temperature}_f32) > 38.0,
                                        }
                                    },
                                }
                            },
                        },
                    }
                ],
            }}
        }
    }
});

#[derive(Debug)]
pub struct Department {
    pub name: &'static str,
    pub patients: Vec<Patient>,
}

#[derive(Debug, Clone)]
pub struct Patient {
    pub id: &'static str,
    pub vitals: Vitals,
    pub assessment: Assessment,
}

#[derive(Debug, Clone)]
pub struct Vitals {
    pub age: u8,
    pub bp: u16,
    pub hr: u16,
    pub temp: f32,
}

#[derive(Debug, Clone)]
pub enum Assessment {
    FullLabs {
        wbc: u32,
        creatinine: f32,
        risk_score: u8,
    },
    VitalsOnly {
        warning_score: u8,
        infection_risk: InfectionRisk,
    },
}

#[derive(Debug, Clone)]
pub enum InfectionRisk {
    Lab(u32),
    Clinical {
        fever: bool,
        // dept_factor: f32,
    },
}

fn calculate_risk(bp: u16, creatinine: f32) -> u8 {
    let bp_score = if bp < 90 {
        3
    } else if bp < 100 {
        1
    } else {
        0
    };
    let renal_score = if creatinine >= 2.0 {
        2
    } else if creatinine >= 1.2 {
        1
    } else {
        0
    };
    bp_score + renal_score
}

fn calculate_warning(bp: u16, hr: u16) -> u8 {
    let mut score = 0;
    if bp <= 90 {
        score += 3;
    } else if bp <= 100 {
        score += 1;
    }
    if hr >= 131 {
        score += 3;
    } else if hr >= 111 {
        score += 2;
    }
    score
}

// Event handling system data structures
#[derive(Debug, Clone, PartialEq)]
pub struct EventConfig {
    pub event_id: &'static str,
    pub timeout_ms: u32,
    pub retry_policy: RetryPolicy,
    pub handlers: Vec<HandlerConfig>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum RetryPolicy {
    None,
    Limited { max_attempts: u8, backoff_ms: u32 },
}

#[derive(Debug, Clone, PartialEq)]
pub struct HandlerConfig {
    pub name: &'static str,
    pub priority: EventPriority,
    pub conditions: Option<Condition>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
    pub field: &'static str,
    pub operator: ConditionOp,
    pub value: &'static str,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ConditionOp {
    Equals,
    Contains,
}

// Generate event system from CSV
csv_codegen::csv_template!("events.csv", {
    #[derive(Debug, Clone, PartialEq)]
    pub enum EventType {
        #each {
            #Type({event_type}),
        }
    }

    #[derive(Debug, Clone, PartialEq)]
    pub enum EventPriority {
        #each {
            #Type({priority}),
        }
    }
});

csv_codegen::csv_template!("events.csv", #each {
    pub mod #ident({service}_events) {
        use super::*;

        pub struct #Type({service}EventHandler) {
            pub service_name: &'static str,
            pub default_timeout: u32,
        }

        impl #Type({service}EventHandler) {
            pub fn handle_event(&self, event_type: EventType) -> Option<EventConfig> {
                match event_type {
                    #each {
                        EventType::#Type({event_type}) => Some(EventConfig {
                            event_id: #("{event_id}"),
                            timeout_ms: #find(timeout_override != ""){
                                #({timeout_override}_u32)
                            } #else {
                                self.default_timeout
                            },
                            retry_policy: #find(max_retries != ""){
                                RetryPolicy::Limited {
                                    max_attempts: #({max_retries}_u8),
                                    backoff_ms: #find(backoff_ms != ""){
                                        #({backoff_ms}_u32)
                                    } #else {
                                        1000
                                    },
                                }
                            } #else {
                                RetryPolicy::None
                            },
                            handlers: vec![
                                #each(handler_1 != ""){
                                    HandlerConfig {
                                        name: #("{handler_1}"),
                                        priority: EventPriority::#Type({priority}),
                                        conditions: #find(condition_field != "" && condition_value != ""){
                                            Some(Condition {
                                                field: #("{condition_field}"),
                                                operator: #find(condition_operator == "equals"){
                                                    ConditionOp::Equals
                                                } #else {
                                                    ConditionOp::Contains
                                                },
                                                value: #("{condition_value}"),
                                            })
                                        } #else {
                                            None
                                        },
                                    },
                                }
                                #each(handler_2 != ""){
                                    HandlerConfig {
                                        name: #("{handler_2}"),
                                        priority: EventPriority::#Type({priority}),
                                        conditions: None,
                                    },
                                }
                            ],
                        }),
                    }
                    _ => None,
                }
            }

            pub const SERVICE_METRICS: &'static [(&'static str, u32)] = &[
                #each(avg_processing_time != ""){
                    (#("{event_type}"), #({avg_processing_time}_u32)),
                }
            ];
        }
    }
});

#[test]
fn test_event_driven_system() {
    // Test payment service handler
    let payment_handler = payment_events::PaymentEventHandler {
        service_name: "payment",
        default_timeout: 3000,
    };

    let signup_config = payment_handler.handle_event(EventType::UserSignup).unwrap();
    assert_eq!(signup_config.event_id, "usr_001");
    assert_eq!(signup_config.timeout_ms, 5000); // overridden
    assert_eq!(signup_config.handlers.len(), 2);
    assert_eq!(signup_config.handlers[0].name, "validate_email");
    assert_eq!(signup_config.handlers[0].priority, EventPriority::High);

    // Test condition handling
    if let Some(condition) = &signup_config.handlers[0].conditions {
        assert_eq!(condition.field, "email");
        assert_eq!(condition.operator, ConditionOp::Contains);
        assert_eq!(condition.value, "@company.com");
    }

    // Test retry policy
    match signup_config.retry_policy {
        RetryPolicy::Limited {
            max_attempts,
            backoff_ms,
        } => {
            assert_eq!(max_attempts, 3);
            assert_eq!(backoff_ms, 2000);
        }
        _ => panic!("Expected Limited retry policy"),
    }

    // Test notification service with defaults
    let notification_handler = notification_events::NotificationEventHandler {
        service_name: "notification",
        default_timeout: 10000,
    };

    let email_config = notification_handler
        .handle_event(EventType::EmailSent)
        .unwrap();
    assert_eq!(email_config.timeout_ms, 10000); // uses default
    assert_eq!(email_config.handlers[0].conditions, None); // no condition

    // Test service metrics
    let metrics = payment_events::PaymentEventHandler::SERVICE_METRICS;
    assert!(metrics.len() >= 2);
    assert!(metrics.iter().any(|(event, _)| *event == "UserSignup"));
}

#[test]
fn test_implicit_multiple_groups_error() {
    // This test verifies that using implicit {} syntax with multiple groups
    // produces a helpful error message
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/implicit_multiple_groups.rs");
}

#[test]
fn test_find_requires_condition_error() {
    // This test verifies that #find without a condition produces an error
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/find_no_condition.rs");
}

#[test]
fn test_find_multiple_rows_error() {
    // This test verifies that #find with multiple matching rows produces
    // a helpful error message with row details
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/find_multiple_rows.rs");
}

#[test]
fn test_having_directive_with_iteration() {
    // Test #having with nested #each - shows all employees in departments with cleared staff
    let depts: &[(&str, &str, &[&str])] = csv_codegen::csv_template!("departments.csv", {
        &[
            #each{
                (
                    #("{department}_team"), #having(union_rep == true){#("{name}")}, &[
                        #each{ #("{name}"), }
                    ]
                ),
            }
        ]
    });

    assert_debug_snapshot!(depts, @r#"
    [
        (
            "engineering_team",
            "Frank",
            [
                "Eve",
                "Frank",
            ],
        ),
        (
            "security_team",
            "Alice",
            [
                "Alice",
                "Bob",
            ],
        ),
    ]
    "#);
}

#[test]
fn test_having_with_else_error() {
    // This test verifies that #having with #else produces an error
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/having_with_else.rs");
}

#[test]
fn test_template_syntax_error() {
    // This test verifies that template syntax errors produce helpful span information
    // The error should point to the specific location in the template, not the entire macro
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/template_syntax_error.rs");
}

#[test]
fn test_non_exhaustive_match() {
    // This test verifies that non-exhaustive pattern errors in match expressions
    // with #each generated arms produce helpful span information
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile_fail/non_exhaustive_match.rs");
}

#[test]
fn test_multiple_having_conditions_working() {
    // This test verifies that 2 #having conditions in same #each work correctly
    // when one doesn't match - it should silently filter (return empty) rather than error
    // security department: has union_rep=true (Alice) but no employee_id == "emp006"
    // engineering department: has union_rep=true (Frank) and employee_id == "emp005" (Eve)
    let result = csv_codegen::csv_template!("departments.csv", #each {
        (
            #("{department}"),
            #having(union_rep == true){#("{name}")},
            #having(employee_id == "emp005"){#("{name}")},
        )
    });

    // Should only contain the engineering department where both conditions match:
    // - has union_rep=true (Frank)
    // - has employee_id == "emp005" (Eve)
    // Other groups are filtered out when one #having condition doesn't match
    assert_debug_snapshot!(result, @r#"
    (
        "engineering",
        "Frank",
        "Eve",
    )
    "#);
}