odk-cli 0.1.0

ODK CLI - Unified schema compilation from TypeScript, WASM, or JSON to multiple targets
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
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
//! Rust model generation.
//!
//! Emits a `models.rs` of plain structs with serde derives, one `pub struct`
//! per model and one `pub enum` per string union.
//!
//! # Why plain structs with serde
//!
//! Generated code inherits its shape onto every consumer. A schema describing
//! a file format (the motivating case is a DAW project document) wants to
//! describe the JSON it reads with the ecosystem's standard round trip and no
//! framework in front of it. `serde::Serialize`/`Deserialize` derives cover
//! that, and nothing beyond serde is pulled in.
//!
//! The cost is that this validates nothing beyond shape: an out-of-range value
//! that the JSON Schema would reject still deserializes. Constraints in the IR
//! are emitted as comments so they are visible, not enforced.

use std::collections::BTreeMap;

use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};

/// Generate Rust models for a schema.
pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
    let mut output = BTreeMap::new();

    if schema.models.is_empty() && schema.unions.is_empty() {
        return output;
    }

    output.insert("models.rs".to_string(), generate_models(schema));
    output
}

/// Derive line applied to every generated struct and enum.
const DERIVE: &str = "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]";

fn generate_models(schema: &CompiledSchema) -> String {
    let mut out = String::new();

    out.push_str(&format!(
        "// {} models.\n//\n// Generated by ODK. Do not edit by hand.\n//\n// Consuming this file requires the serde and serde_json crates.\n\n",
        schema.name
    ));

    for union in &schema.unions {
        out.push_str(&enum_def(union));
        out.push('\n');
    }

    for model in &schema.models {
        out.push_str(&struct_def(model));
        out.push('\n');
    }

    out
}

/// Render a string union as a Rust enum.
///
/// Variant names come from JSON string values that are not required to be
/// valid Rust identifiers, so each variant is emitted as a PascalCase
/// identifier carrying a serde rename back to its exact wire string.
fn enum_def(union: &odk_schema::CompiledUnion) -> String {
    // a discriminator tag marks a data-carrying (internally-tagged) union; its
    // variants carry payloads and it emits as a serde-tagged enum
    if union.tag.is_some() {
        return tagged_enum_def(union);
    }

    let mut out = String::new();

    if let Some(desc) = &union.description {
        out.push_str(&format!("// {}\n", one_line(desc)));
    }

    out.push_str(DERIVE);
    out.push('\n');

    if union.variants.is_empty() {
        out.push_str(&format!("pub enum {} {{}}\n", union.name));
        return out;
    }

    out.push_str(&format!("pub enum {} {{\n", union.name));
    let mut used: Vec<String> = Vec::new();
    for v in &union.variants {
        // two wire values can PascalCase to the same identifier, so the ident
        // is disambiguated per enum while the rename keeps the exact wire value
        let ident = dedup(&mut used, &pascal_case(&v.name), "");
        out.push_str(&format!("    #[serde(rename = \"{}\")]\n", escape(&v.name)));
        out.push_str(&format!("    {ident},\n"));
    }
    out.push_str("}\n");
    out
}

/// Render a data-carrying union as a serde internally-tagged enum.
///
/// The discriminator key becomes `#[serde(tag = "...")]`; an object variant
/// becomes a struct variant, a ref variant a newtype variant. A direct
/// reference back to the enum is boxed so the type stays finite; a reference
/// inside a `Vec` is left unboxed, since the `Vec` is already indirection.
fn tagged_enum_def(union: &odk_schema::CompiledUnion) -> String {
    let mut out = String::new();

    if let Some(desc) = &union.description {
        out.push_str(&format!("// {}\n", one_line(desc)));
    }

    out.push_str(DERIVE);
    out.push('\n');

    let mut attr_parts = vec![format!(
        "tag = \"{}\"",
        escape(union.tag.as_deref().unwrap_or(""))
    )];
    if let Some(rule) = &union.rename_all {
        attr_parts.push(format!("rename_all = \"{}\"", escape(rule)));
    }
    out.push_str(&format!("#[serde({})]\n", attr_parts.join(", ")));

    if union.variants.is_empty() {
        out.push_str(&format!("pub enum {} {{}}\n", union.name));
        return out;
    }

    out.push_str(&format!("pub enum {} {{\n", union.name));
    let mut used: Vec<String> = Vec::new();
    for v in &union.variants {
        let ident = dedup(&mut used, &pascal_case(&v.name), "");
        // with a container rename_all the wire tag is derived from the ident, so
        // a per-variant rename is only needed when there is no such rule
        if union.rename_all.is_none() && ident != v.name {
            out.push_str(&format!("    #[serde(rename = \"{}\")]\n", escape(&v.name)));
        }
        match &v.variant_type {
            Some(CompiledType::Object { fields }) => {
                out.push_str(&format!("    {ident} {{\n"));
                let mut fused: Vec<String> = Vec::new();
                for f in fields {
                    let fident = dedup(&mut fused, &field_ident(&f.name), "_");
                    let is_optional = f.optional == Some(true);
                    let mut serde_parts: Vec<String> = Vec::new();
                    if fident != f.name {
                        serde_parts.push(format!("rename = \"{}\"", escape(&f.name)));
                    }
                    if is_optional {
                        serde_parts.push("skip_serializing_if = \"Option::is_none\"".to_string());
                        serde_parts.push("default".to_string());
                    }
                    if !serde_parts.is_empty() {
                        out.push_str(&format!("        #[serde({})]\n", serde_parts.join(", ")));
                    }
                    let ty = variant_field_type(&f.field_type, &union.name);
                    let ty = if is_optional {
                        format!("Option<{ty}>")
                    } else {
                        ty
                    };
                    out.push_str(&format!("        {fident}: {ty},\n"));
                }
                out.push_str("    },\n");
            }
            Some(CompiledType::Ref { name }) => {
                let ty = variant_field_type(&CompiledType::Ref { name: name.clone() }, &union.name);
                out.push_str(&format!("    {ident}({ty}),\n"));
            }
            Some(other) => {
                out.push_str(&format!("    {ident}({}),\n", type_to_rust(other)));
            }
            None => {
                out.push_str(&format!("    {ident},\n"));
            }
        }
    }
    out.push_str("}\n");
    out
}

/// Map a field type inside an enum variant, boxing a direct self-reference so
/// the recursive enum has a finite size (a reference nested in a `Vec` or other
/// container does not need boxing).
fn variant_field_type(t: &CompiledType, self_name: &str) -> String {
    match t {
        CompiledType::Ref { name } if name == self_name => format!("Box<{name}>"),
        _ => type_to_rust(t),
    }
}

fn struct_def(model: &odk_schema::CompiledModel) -> String {
    let mut out = String::new();

    if let Some(desc) = &model.description {
        out.push_str(&format!("// {}\n", one_line(desc)));
    }

    out.push_str(DERIVE);
    out.push('\n');

    if model.fields.is_empty() {
        out.push_str(&format!("pub struct {} {{}}\n", model.name));
        return out;
    }

    out.push_str(&format!("pub struct {} {{\n", model.name));

    let mut used: Vec<String> = Vec::new();
    for f in &model.fields {
        if let Some(desc) = &f.description {
            out.push_str(&format!("    // {}\n", one_line(desc)));
        }
        if let Some(note) = constraint_note(f) {
            out.push_str(&format!("    // {note}\n"));
        }

        // two wire names can sanitize to the same ident, so the ident is
        // disambiguated per struct while the rename keeps the exact wire name
        let ident = dedup(&mut used, &field_ident(&f.name), "_");
        let is_optional = f.optional == Some(true);

        let mut serde_parts: Vec<String> = Vec::new();
        // a JSON key that is not a clean Rust identifier is preserved on the
        // wire through a serde rename
        if ident != f.name {
            serde_parts.push(format!("rename = \"{}\"", escape(&f.name)));
        }
        if is_optional {
            serde_parts.push("skip_serializing_if = \"Option::is_none\"".to_string());
            serde_parts.push("default".to_string());
        }
        if !serde_parts.is_empty() {
            out.push_str(&format!("    #[serde({})]\n", serde_parts.join(", ")));
        }

        let ty = type_to_rust(&f.field_type);
        let ty = if is_optional {
            format!("Option<{ty}>")
        } else {
            ty
        };
        out.push_str(&format!("    pub {ident}: {ty},\n"));
    }

    out.push_str("}\n");
    out
}

/// Map an IR type onto a Rust type.
fn type_to_rust(t: &CompiledType) -> String {
    match t {
        CompiledType::Scalar { name } => scalar_to_rust(name).to_string(),
        // a fixed length encodes a compile-time size as a Rust array; otherwise
        // it is a variable-length Vec
        CompiledType::Array {
            items,
            length: Some(n),
        } => format!("[{}; {}]", type_to_rust(items), n),
        CompiledType::Array {
            items,
            length: None,
        } => {
            format!("Vec<{}>", type_to_rust(items))
        }
        CompiledType::Ref { name } => name.clone(),
        CompiledType::Literal { value } => match value {
            LiteralValue::String(_) => "String".to_string(),
            LiteralValue::Number(_) => "f64".to_string(),
            LiteralValue::Bool(_) => "bool".to_string(),
        },
        // Rust has no anonymous union type, so an inline union falls back to an
        // untyped JSON value
        CompiledType::Union { .. } => "serde_json::Value".to_string(),
        // an inline object has no name to reference, so it stays an untyped
        // JSON value
        CompiledType::Object { .. } => "serde_json::Value".to_string(),
    }
}

fn scalar_to_rust(s: &ScalarType) -> &'static str {
    match s {
        // every string-shaped scalar, including bytes, maps to String to match
        // the JSON wire shape the schema describes
        ScalarType::String
        | ScalarType::Date
        | ScalarType::Datetime
        | ScalarType::UtcDateTime
        | ScalarType::OffsetDateTime
        | ScalarType::PlainDate
        | ScalarType::PlainTime
        | ScalarType::Duration
        | ScalarType::Bytes
        | ScalarType::Url => "String",
        ScalarType::Int32 => "i32",
        ScalarType::Int64 => "i64",
        ScalarType::Float32 => "f32",
        ScalarType::Float64 => "f64",
        ScalarType::Boolean => "bool",
        ScalarType::Unknown => "serde_json::Value",
    }
}

/// Render a field's constraints as a human-readable note.
fn constraint_note(f: &CompiledField) -> Option<String> {
    let c = f.constraints.as_ref()?;
    let mut parts = Vec::new();

    if let Some(v) = c.min_length {
        parts.push(format!("minLength {v}"));
    }
    if let Some(v) = c.max_length {
        parts.push(format!("maxLength {v}"));
    }
    if let Some(v) = c.min_value {
        parts.push(format!("minimum {v}"));
    }
    if let Some(v) = c.max_value {
        parts.push(format!("maximum {v}"));
    }
    if let Some(v) = &c.pattern {
        parts.push(format!("pattern {v}"));
    }
    if let Some(v) = &c.format {
        parts.push(format!("format {v}"));
    }
    if let Some(v) = c.multiple_of {
        parts.push(format!("multipleOf {v}"));
    }

    if parts.is_empty() {
        None
    } else {
        // not enforced: the derives validate nothing, so this is documentation
        Some(format!("constraints: {}", parts.join(", ")))
    }
}

/// Rust keywords (strict and reserved) that cannot be used as a bare field
/// identifier.
const KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn",
    "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
    "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
    "use", "where", "while", "async", "await", "abstract", "become", "box", "do", "final", "gen",
    "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
];

/// Make a JSON property name safe as a Rust struct field identifier.
///
/// Non-identifier characters become underscores, a leading digit is prefixed,
/// and a keyword gets a trailing underscore. Where the result differs from the
/// original the caller restores the wire name with a serde rename.
fn field_ident(name: &str) -> String {
    let mut cleaned: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();

    if cleaned.is_empty() || cleaned.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        cleaned = format!("_{cleaned}");
    }

    if KEYWORDS.contains(&cleaned.as_str()) {
        format!("{cleaned}_")
    } else {
        cleaned
    }
}

/// Return an identifier unique within a scope, tracking the ones already taken.
///
/// Sanitizing or PascalCasing distinct wire strings can collapse them onto the
/// same Rust identifier, which rustc rejects as a duplicate variant or field.
/// A numeric suffix is appended (joined by `sep`, empty for PascalCase variants
/// and `_` for snake_case fields) until the identifier is free. Processing in
/// the caller's existing order keeps the result deterministic.
fn dedup(used: &mut Vec<String>, candidate: &str, sep: &str) -> String {
    if !used.iter().any(|u| u == candidate) {
        used.push(candidate.to_string());
        return candidate.to_string();
    }

    let mut n = 2;
    loop {
        let next = format!("{candidate}{sep}{n}");
        if !used.iter().any(|u| u == &next) {
            used.push(next.clone());
            return next;
        }
        n += 1;
    }
}

/// Convert an arbitrary wire string into a PascalCase Rust identifier.
fn pascal_case(name: &str) -> String {
    let mut out = String::new();
    let mut upper_next = true;

    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            if upper_next {
                out.extend(c.to_uppercase());
            } else {
                out.push(c);
            }
            upper_next = false;
        } else {
            upper_next = true;
        }
    }

    if out.is_empty() || out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        format!("Variant{out}")
    } else {
        out
    }
}

fn escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Collapse a description to a single line so it cannot break out of a comment.
fn one_line(s: &str) -> String {
    s.replace(['\n', '\r'], " ").trim().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use odk_schema::{CompiledModel, CompiledUnion, CompiledUnionVariant, FieldConstraints};

    fn scalar(name: ScalarType) -> CompiledType {
        CompiledType::Scalar { name }
    }

    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
        let mut schema = CompiledSchema::new("Test");
        for m in models {
            schema.add_model(m);
        }
        schema
    }

    fn render(schema: &CompiledSchema) -> String {
        generate(schema)
            .get("models.rs")
            .expect("models.rs emitted")
            .clone()
    }

    #[test]
    fn an_empty_schema_emits_nothing() {
        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
    }

    #[test]
    fn a_model_becomes_a_struct() {
        let mut model = CompiledModel::new("Track").with_description("A track");
        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]"));
        assert!(out.contains("pub struct Track {"));
        assert!(out.contains("// A track"));
        assert!(out.contains("    pub id: String,\n"));
    }

    #[test]
    fn scalars_map_to_rust_types() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
        model.add_field(CompiledField::new("i32v", scalar(ScalarType::Int32)));
        model.add_field(CompiledField::new("i64v", scalar(ScalarType::Int64)));
        model.add_field(CompiledField::new("f32v", scalar(ScalarType::Float32)));
        model.add_field(CompiledField::new("f64v", scalar(ScalarType::Float64)));
        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
        model.add_field(CompiledField::new("by", scalar(ScalarType::Bytes)));
        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("pub s: String,"));
        assert!(out.contains("pub i32v: i32,"));
        assert!(out.contains("pub i64v: i64,"));
        assert!(out.contains("pub f32v: f32,"));
        assert!(out.contains("pub f64v: f64,"));
        assert!(out.contains("pub b: bool,"));
        assert!(out.contains("pub by: String,"));
        assert!(out.contains("pub u: serde_json::Value,"));
        assert!(out.contains("pub t: String,"));
    }

    #[test]
    fn optional_fields_become_option_and_are_skipped_when_none() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
        model.add_field(CompiledField::new("maybe", scalar(ScalarType::Int64)).optional());

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("pub must: String,"));
        assert!(out.contains("#[serde(skip_serializing_if = \"Option::is_none\", default)]"));
        assert!(out.contains("pub maybe: Option<i64>,"));
    }

    #[test]
    fn arrays_and_refs_nest() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new(
            "tracks",
            CompiledType::Array {
                items: Box::new(CompiledType::Ref {
                    name: "Track".to_string(),
                }),
                length: None,
            },
        ));

        assert!(render(&schema_with(vec![model])).contains("pub tracks: Vec<Track>,"));
    }

    #[test]
    fn a_union_becomes_an_enum_with_per_variant_renames() {
        let mut schema = CompiledSchema::new("Test");
        schema.add_union(CompiledUnion {
            name: "TrackType".to_string(),
            variants: ["audio", "midi"]
                .iter()
                .map(|v| CompiledUnionVariant {
                    name: (*v).to_string(),
                    variant_type: None,
                })
                .collect(),
            tag: None,
            rename_all: None,
            description: None,
            extensions: odk_schema::Extensions::default(),
            source: None,
        });
        schema.add_model(CompiledModel::new("M"));

        let out = render(&schema);

        assert!(out.contains("pub enum TrackType {"));
        assert!(out.contains("    #[serde(rename = \"audio\")]\n    Audio,"));
        assert!(out.contains("    #[serde(rename = \"midi\")]\n    Midi,"));
    }

    #[test]
    fn a_data_carrying_union_becomes_an_internally_tagged_enum() {
        fn obj(fields: Vec<CompiledField>) -> CompiledType {
            CompiledType::Object { fields }
        }
        let vec3 = || CompiledType::fixed_array(scalar(ScalarType::Float64), 3);

        let mut schema = CompiledSchema::new("Geo");
        schema.add_union(CompiledUnion {
            name: "OpNode".to_string(),
            tag: Some("op".to_string()),
            rename_all: Some("lowercase".to_string()),
            variants: vec![
                CompiledUnionVariant {
                    name: "cube".to_string(),
                    variant_type: Some(obj(vec![
                        CompiledField::new("size", vec3()),
                        CompiledField::new("center", scalar(ScalarType::Boolean)),
                    ])),
                },
                CompiledUnionVariant {
                    name: "translate".to_string(),
                    variant_type: Some(obj(vec![
                        CompiledField::new("v", vec3()),
                        CompiledField::new("child", CompiledType::reference("OpNode")),
                    ])),
                },
                CompiledUnionVariant {
                    name: "union".to_string(),
                    variant_type: Some(obj(vec![CompiledField::new(
                        "children",
                        CompiledType::array(CompiledType::reference("OpNode")),
                    )])),
                },
            ],
            description: None,
            extensions: odk_schema::Extensions::default(),
            source: None,
        });
        schema.add_model(CompiledModel::new("M"));

        let out = render(&schema);

        // container is an internally-tagged enum
        assert!(
            out.contains("#[serde(tag = \"op\", rename_all = \"lowercase\")]"),
            "missing container tag attr:\n{out}"
        );
        assert!(out.contains("pub enum OpNode {"), "not an enum:\n{out}");
        // data-carrying struct variants
        assert!(out.contains("Cube {"), "missing Cube variant:\n{out}");
        assert!(
            out.contains("size: [f64; 3]"),
            "fixed-length array wrong:\n{out}"
        );
        assert!(out.contains("center: bool"));
        assert!(out.contains("Translate {"));
        // self-recursion is boxed so the type is finite
        assert!(
            out.contains("child: Box<OpNode>"),
            "recursive ref not boxed:\n{out}"
        );
        assert!(out.contains("Union {"));
        // a Vec is already indirection, so it is not boxed
        assert!(
            out.contains("children: Vec<OpNode>"),
            "vec recursion wrong:\n{out}"
        );
    }

    #[test]
    fn enum_variants_that_pascalcase_to_the_same_ident_are_disambiguated() {
        let mut schema = CompiledSchema::new("Test");
        schema.add_union(CompiledUnion {
            name: "Kind".to_string(),
            variants: ["foo-bar", "foo_bar", "audio", "Audio"]
                .iter()
                .map(|v| CompiledUnionVariant {
                    name: (*v).to_string(),
                    variant_type: None,
                })
                .collect(),
            tag: None,
            rename_all: None,
            description: None,
            extensions: odk_schema::Extensions::default(),
            source: None,
        });
        schema.add_model(CompiledModel::new("M"));

        let out = render(&schema);

        // four distinct variant idents, deterministically disambiguated, each
        // still paired with a rename back to its exact wire value
        assert!(out.contains("#[serde(rename = \"foo-bar\")]\n    FooBar,\n"));
        assert!(out.contains("#[serde(rename = \"foo_bar\")]\n    FooBar2,\n"));
        assert!(out.contains("#[serde(rename = \"audio\")]\n    Audio,\n"));
        assert!(out.contains("#[serde(rename = \"Audio\")]\n    Audio2,\n"));
    }

    #[test]
    fn struct_fields_that_sanitize_to_the_same_ident_are_disambiguated() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("foo-bar", scalar(ScalarType::String)));
        model.add_field(CompiledField::new("foo_bar", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        // two distinct field idents, each carrying a rename to its wire name
        assert!(out.contains("#[serde(rename = \"foo-bar\")]\n    pub foo_bar: String,\n"));
        assert!(out.contains("#[serde(rename = \"foo_bar\")]\n    pub foo_bar_2: String,\n"));
    }

    #[test]
    fn reserved_keyword_field_names_are_renamed() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("type", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("#[serde(rename = \"type\")]"));
        assert!(out.contains("pub type_: String,"));
    }

    #[test]
    fn non_identifier_field_names_are_sanitized_and_renamed() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("#[serde(rename = \"kebab-case\")]"));
        assert!(out.contains("pub kebab_case: String,"));
    }

    #[test]
    fn constraints_are_emitted_as_comments_not_validation() {
        let mut model = CompiledModel::new("M");
        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
        f.constraints = Some(FieldConstraints {
            min_length: None,
            max_length: None,
            min_value: Some(20.0),
            max_value: Some(300.0),
            pattern: None,
            format: None,
            multiple_of: None,
        });
        model.add_field(f);

        let out = render(&schema_with(vec![model]));
        assert!(out.contains("// constraints: minimum 20, maximum 300"));
    }

    #[test]
    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
        let mut model = CompiledModel::new("M");
        let mut f = CompiledField::new("a", scalar(ScalarType::String));
        f.description = Some("line one\nline two".to_string());
        model.add_field(f);

        let out = render(&schema_with(vec![model]));
        assert!(out.contains("// line one line two"));
    }

    #[test]
    fn an_empty_model_is_still_valid_rust() {
        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
        assert!(out.contains("pub struct Empty {}"));
    }

    #[test]
    fn a_literal_scalar_renders_as_its_base_type() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new(
            "kind",
            CompiledType::Literal {
                value: LiteralValue::String("audio".to_string()),
            },
        ));

        assert!(render(&schema_with(vec![model])).contains("pub kind: String,"));
    }
}