Skip to main content

odk_cli/generate/
rust.rs

1//! Rust model generation.
2//!
3//! Emits a `models.rs` of plain structs with serde derives, one `pub struct`
4//! per model and one `pub enum` per string union.
5//!
6//! # Why plain structs with serde
7//!
8//! Generated code inherits its shape onto every consumer. A schema describing
9//! a file format (the motivating case is a DAW project document) wants to
10//! describe the JSON it reads with the ecosystem's standard round trip and no
11//! framework in front of it. `serde::Serialize`/`Deserialize` derives cover
12//! that, and nothing beyond serde is pulled in.
13//!
14//! The cost is that this validates nothing beyond shape: an out-of-range value
15//! that the JSON Schema would reject still deserializes. Constraints in the IR
16//! are emitted as comments so they are visible, not enforced.
17
18use std::collections::BTreeMap;
19
20use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};
21
22/// Generate Rust models for a schema.
23pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
24    let mut output = BTreeMap::new();
25
26    if schema.models.is_empty() && schema.unions.is_empty() {
27        return output;
28    }
29
30    output.insert("models.rs".to_string(), generate_models(schema));
31    output
32}
33
34/// Derive line applied to every generated struct and enum.
35const DERIVE: &str = "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]";
36
37fn generate_models(schema: &CompiledSchema) -> String {
38    let mut out = String::new();
39
40    out.push_str(&format!(
41        "// {} 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",
42        schema.name
43    ));
44
45    for union in &schema.unions {
46        out.push_str(&enum_def(union));
47        out.push('\n');
48    }
49
50    for model in &schema.models {
51        out.push_str(&struct_def(model));
52        out.push('\n');
53    }
54
55    out
56}
57
58/// Render a string union as a Rust enum.
59///
60/// Variant names come from JSON string values that are not required to be
61/// valid Rust identifiers, so each variant is emitted as a PascalCase
62/// identifier carrying a serde rename back to its exact wire string.
63fn enum_def(union: &odk_schema::CompiledUnion) -> String {
64    // a discriminator tag marks a data-carrying (internally-tagged) union; its
65    // variants carry payloads and it emits as a serde-tagged enum
66    if union.tag.is_some() {
67        return tagged_enum_def(union);
68    }
69
70    let mut out = String::new();
71
72    if let Some(desc) = &union.description {
73        out.push_str(&format!("// {}\n", one_line(desc)));
74    }
75
76    out.push_str(DERIVE);
77    out.push('\n');
78
79    if union.variants.is_empty() {
80        out.push_str(&format!("pub enum {} {{}}\n", union.name));
81        return out;
82    }
83
84    out.push_str(&format!("pub enum {} {{\n", union.name));
85    let mut used: Vec<String> = Vec::new();
86    for v in &union.variants {
87        // two wire values can PascalCase to the same identifier, so the ident
88        // is disambiguated per enum while the rename keeps the exact wire value
89        let ident = dedup(&mut used, &pascal_case(&v.name), "");
90        out.push_str(&format!("    #[serde(rename = \"{}\")]\n", escape(&v.name)));
91        out.push_str(&format!("    {ident},\n"));
92    }
93    out.push_str("}\n");
94    out
95}
96
97/// Render a data-carrying union as a serde internally-tagged enum.
98///
99/// The discriminator key becomes `#[serde(tag = "...")]`; an object variant
100/// becomes a struct variant, a ref variant a newtype variant. A direct
101/// reference back to the enum is boxed so the type stays finite; a reference
102/// inside a `Vec` is left unboxed, since the `Vec` is already indirection.
103fn tagged_enum_def(union: &odk_schema::CompiledUnion) -> String {
104    let mut out = String::new();
105
106    if let Some(desc) = &union.description {
107        out.push_str(&format!("// {}\n", one_line(desc)));
108    }
109
110    out.push_str(DERIVE);
111    out.push('\n');
112
113    let mut attr_parts = vec![format!(
114        "tag = \"{}\"",
115        escape(union.tag.as_deref().unwrap_or(""))
116    )];
117    if let Some(rule) = &union.rename_all {
118        attr_parts.push(format!("rename_all = \"{}\"", escape(rule)));
119    }
120    out.push_str(&format!("#[serde({})]\n", attr_parts.join(", ")));
121
122    if union.variants.is_empty() {
123        out.push_str(&format!("pub enum {} {{}}\n", union.name));
124        return out;
125    }
126
127    out.push_str(&format!("pub enum {} {{\n", union.name));
128    let mut used: Vec<String> = Vec::new();
129    for v in &union.variants {
130        let ident = dedup(&mut used, &pascal_case(&v.name), "");
131        // with a container rename_all the wire tag is derived from the ident, so
132        // a per-variant rename is only needed when there is no such rule
133        if union.rename_all.is_none() && ident != v.name {
134            out.push_str(&format!("    #[serde(rename = \"{}\")]\n", escape(&v.name)));
135        }
136        match &v.variant_type {
137            Some(CompiledType::Object { fields }) => {
138                out.push_str(&format!("    {ident} {{\n"));
139                let mut fused: Vec<String> = Vec::new();
140                for f in fields {
141                    let fident = dedup(&mut fused, &field_ident(&f.name), "_");
142                    let is_optional = f.optional == Some(true);
143                    let mut serde_parts: Vec<String> = Vec::new();
144                    if fident != f.name {
145                        serde_parts.push(format!("rename = \"{}\"", escape(&f.name)));
146                    }
147                    if is_optional {
148                        serde_parts.push("skip_serializing_if = \"Option::is_none\"".to_string());
149                        serde_parts.push("default".to_string());
150                    }
151                    if !serde_parts.is_empty() {
152                        out.push_str(&format!("        #[serde({})]\n", serde_parts.join(", ")));
153                    }
154                    let ty = variant_field_type(&f.field_type, &union.name);
155                    let ty = if is_optional {
156                        format!("Option<{ty}>")
157                    } else {
158                        ty
159                    };
160                    out.push_str(&format!("        {fident}: {ty},\n"));
161                }
162                out.push_str("    },\n");
163            }
164            Some(CompiledType::Ref { name }) => {
165                let ty = variant_field_type(&CompiledType::Ref { name: name.clone() }, &union.name);
166                out.push_str(&format!("    {ident}({ty}),\n"));
167            }
168            Some(other) => {
169                out.push_str(&format!("    {ident}({}),\n", type_to_rust(other)));
170            }
171            None => {
172                out.push_str(&format!("    {ident},\n"));
173            }
174        }
175    }
176    out.push_str("}\n");
177    out
178}
179
180/// Detect a reference cycle the emitter's self-reference boxing does not break,
181/// i.e. mutual recursion (`A -> B -> A`) or a self-referential model field. Such
182/// a type is infinitely sized and the generated Rust would not compile, so this
183/// reports it up front with a clear message instead of emitting code that fails
184/// at the consumer's `cargo build`. Returns `None` when the Rust is finite.
185///
186/// The emitter boxes exactly one case: a direct reference back to a tagged
187/// union inside that union's own variant. Every other inline reference (a model
188/// field, a non-self reference, a fixed-length array of references) propagates
189/// size, while a `Vec` (variable-length array) is heap indirection that breaks a
190/// cycle. The graph below mirrors that so a flagged cycle is a real compile
191/// failure, never a false positive on code that would build.
192pub(crate) fn unsupported_recursion(schema: &CompiledSchema) -> Option<String> {
193    let mut edges: BTreeMap<String, Vec<String>> = BTreeMap::new();
194
195    for model in &schema.models {
196        let mut targets = Vec::new();
197        for f in &model.fields {
198            // a struct field is never boxed, so a direct self-reference counts
199            collect_sized_refs(&f.field_type, &mut targets);
200        }
201        edges.insert(model.name.clone(), targets);
202    }
203
204    for union in &schema.unions {
205        let mut targets = Vec::new();
206        for v in &union.variants {
207            match &v.variant_type {
208                Some(CompiledType::Object { fields }) => {
209                    for f in fields {
210                        // a direct self-reference field is boxed by the emitter
211                        if matches!(&f.field_type, CompiledType::Ref { name } if name == &union.name)
212                        {
213                            continue;
214                        }
215                        collect_sized_refs(&f.field_type, &mut targets);
216                    }
217                }
218                // a newtype self-reference payload is boxed by the emitter
219                Some(CompiledType::Ref { name }) if name != &union.name => {
220                    targets.push(name.clone());
221                }
222                Some(CompiledType::Ref { .. }) | None => {}
223                Some(other) => collect_sized_refs(other, &mut targets),
224            }
225        }
226        edges.insert(union.name.clone(), targets);
227    }
228
229    let mut state: BTreeMap<String, u8> = edges.keys().map(|k| (k.clone(), 0u8)).collect();
230    for start in edges.keys() {
231        if state.get(start).copied().unwrap_or(0) == 0
232            && let Some(cycle) = dfs_cycle(start, &edges, &mut state, &mut Vec::new())
233        {
234            return Some(format!(
235                "the Rust target cannot emit the recursive type cycle {}: the references are \
236                 inline, so the type is infinitely sized and the generated Rust will not \
237                 compile. ODK boxes a direct self-reference inside a tagged union, but not a \
238                 cycle through other types. Break the cycle with a list field, or generate \
239                 these types with -t typescript.",
240                cycle.join(" -> ")
241            ));
242        }
243    }
244    None
245}
246
247/// Collect the names a type inlines without heap indirection: a direct
248/// reference, or a fixed-length array of such (a `Vec` is omitted, since it is
249/// heap-allocated and breaks a size cycle).
250fn collect_sized_refs(t: &CompiledType, out: &mut Vec<String>) {
251    match t {
252        CompiledType::Ref { name } => out.push(name.clone()),
253        CompiledType::Array {
254            items,
255            length: Some(_),
256        } => collect_sized_refs(items, out),
257        _ => {}
258    }
259}
260
261/// Three-colour DFS that returns the first cycle found as the path of names that
262/// closes it (`[A, B, A]`), or `None` if the subgraph from `node` is acyclic.
263fn dfs_cycle(
264    node: &str,
265    edges: &BTreeMap<String, Vec<String>>,
266    state: &mut BTreeMap<String, u8>,
267    stack: &mut Vec<String>,
268) -> Option<Vec<String>> {
269    state.insert(node.to_string(), 1);
270    stack.push(node.to_string());
271    if let Some(neighbours) = edges.get(node) {
272        for n in neighbours {
273            match state.get(n).copied().unwrap_or(0) {
274                1 => {
275                    let at = stack.iter().position(|s| s == n).unwrap_or(0);
276                    let mut cycle = stack[at..].to_vec();
277                    cycle.push(n.clone());
278                    return Some(cycle);
279                }
280                0 => {
281                    if let Some(cycle) = dfs_cycle(n, edges, state, stack) {
282                        return Some(cycle);
283                    }
284                }
285                _ => {}
286            }
287        }
288    }
289    stack.pop();
290    state.insert(node.to_string(), 2);
291    None
292}
293
294/// Map a field type inside an enum variant, boxing a direct self-reference so
295/// the recursive enum has a finite size (a reference nested in a `Vec` or other
296/// container does not need boxing).
297fn variant_field_type(t: &CompiledType, self_name: &str) -> String {
298    match t {
299        CompiledType::Ref { name } if name == self_name => format!("Box<{name}>"),
300        _ => type_to_rust(t),
301    }
302}
303
304fn struct_def(model: &odk_schema::CompiledModel) -> String {
305    let mut out = String::new();
306
307    if let Some(desc) = &model.description {
308        out.push_str(&format!("// {}\n", one_line(desc)));
309    }
310
311    out.push_str(DERIVE);
312    out.push('\n');
313
314    if model.fields.is_empty() {
315        out.push_str(&format!("pub struct {} {{}}\n", model.name));
316        return out;
317    }
318
319    out.push_str(&format!("pub struct {} {{\n", model.name));
320
321    let mut used: Vec<String> = Vec::new();
322    for f in &model.fields {
323        if let Some(desc) = &f.description {
324            out.push_str(&format!("    // {}\n", one_line(desc)));
325        }
326        if let Some(note) = constraint_note(f) {
327            out.push_str(&format!("    // {note}\n"));
328        }
329
330        // two wire names can sanitize to the same ident, so the ident is
331        // disambiguated per struct while the rename keeps the exact wire name
332        let ident = dedup(&mut used, &field_ident(&f.name), "_");
333        let is_optional = f.optional == Some(true);
334
335        let mut serde_parts: Vec<String> = Vec::new();
336        // a JSON key that is not a clean Rust identifier is preserved on the
337        // wire through a serde rename
338        if ident != f.name {
339            serde_parts.push(format!("rename = \"{}\"", escape(&f.name)));
340        }
341        if is_optional {
342            serde_parts.push("skip_serializing_if = \"Option::is_none\"".to_string());
343            serde_parts.push("default".to_string());
344        }
345        if !serde_parts.is_empty() {
346            out.push_str(&format!("    #[serde({})]\n", serde_parts.join(", ")));
347        }
348
349        let ty = type_to_rust(&f.field_type);
350        let ty = if is_optional {
351            format!("Option<{ty}>")
352        } else {
353            ty
354        };
355        out.push_str(&format!("    pub {ident}: {ty},\n"));
356    }
357
358    out.push_str("}\n");
359    out
360}
361
362/// Map an IR type onto a Rust type.
363fn type_to_rust(t: &CompiledType) -> String {
364    match t {
365        CompiledType::Scalar { name } => scalar_to_rust(name).to_string(),
366        // a fixed length encodes a compile-time size as a Rust array; otherwise
367        // it is a variable-length Vec
368        CompiledType::Array {
369            items,
370            length: Some(n),
371        } => format!("[{}; {}]", type_to_rust(items), n),
372        CompiledType::Array {
373            items,
374            length: None,
375        } => {
376            format!("Vec<{}>", type_to_rust(items))
377        }
378        CompiledType::Ref { name } => name.clone(),
379        CompiledType::Literal { value } => match value {
380            LiteralValue::String(_) => "String".to_string(),
381            LiteralValue::Number(_) => "f64".to_string(),
382            LiteralValue::Bool(_) => "bool".to_string(),
383        },
384        // Rust has no anonymous union type, so an inline union falls back to an
385        // untyped JSON value
386        CompiledType::Union { .. } => "serde_json::Value".to_string(),
387        // an inline object has no name to reference, so it stays an untyped
388        // JSON value
389        CompiledType::Object { .. } => "serde_json::Value".to_string(),
390    }
391}
392
393fn scalar_to_rust(s: &ScalarType) -> &'static str {
394    match s {
395        // every string-shaped scalar, including bytes, maps to String to match
396        // the JSON wire shape the schema describes
397        ScalarType::String
398        | ScalarType::Date
399        | ScalarType::Datetime
400        | ScalarType::UtcDateTime
401        | ScalarType::OffsetDateTime
402        | ScalarType::PlainDate
403        | ScalarType::PlainTime
404        | ScalarType::Duration
405        | ScalarType::Bytes
406        | ScalarType::Url => "String",
407        ScalarType::Int32 => "i32",
408        ScalarType::Int64 | ScalarType::Safeint => "i64",
409        ScalarType::Float32 => "f32",
410        ScalarType::Float64 => "f64",
411        ScalarType::Boolean => "bool",
412        ScalarType::Unknown => "serde_json::Value",
413    }
414}
415
416/// Render a field's constraints as a human-readable note.
417fn constraint_note(f: &CompiledField) -> Option<String> {
418    let c = f.constraints.as_ref()?;
419    let mut parts = Vec::new();
420
421    if let Some(v) = c.min_length {
422        parts.push(format!("minLength {v}"));
423    }
424    if let Some(v) = c.max_length {
425        parts.push(format!("maxLength {v}"));
426    }
427    if let Some(v) = c.min_value {
428        parts.push(format!("minimum {v}"));
429    }
430    if let Some(v) = c.max_value {
431        parts.push(format!("maximum {v}"));
432    }
433    if let Some(v) = &c.pattern {
434        parts.push(format!("pattern {v}"));
435    }
436    if let Some(v) = &c.format {
437        parts.push(format!("format {v}"));
438    }
439    if let Some(v) = c.multiple_of {
440        parts.push(format!("multipleOf {v}"));
441    }
442
443    if parts.is_empty() {
444        None
445    } else {
446        // not enforced: the derives validate nothing, so this is documentation
447        Some(format!("constraints: {}", parts.join(", ")))
448    }
449}
450
451/// Rust keywords (strict and reserved) that cannot be used as a bare field
452/// identifier.
453const KEYWORDS: &[&str] = &[
454    "as", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn",
455    "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
456    "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
457    "use", "where", "while", "async", "await", "abstract", "become", "box", "do", "final", "gen",
458    "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
459];
460
461/// Make a JSON property name safe as a Rust struct field identifier.
462///
463/// Non-identifier characters become underscores, a leading digit is prefixed,
464/// and a keyword gets a trailing underscore. Where the result differs from the
465/// original the caller restores the wire name with a serde rename.
466fn field_ident(name: &str) -> String {
467    let mut cleaned: String = name
468        .chars()
469        .map(|c| {
470            if c.is_ascii_alphanumeric() || c == '_' {
471                c
472            } else {
473                '_'
474            }
475        })
476        .collect();
477
478    if cleaned.is_empty() || cleaned.chars().next().is_some_and(|c| c.is_ascii_digit()) {
479        cleaned = format!("_{cleaned}");
480    }
481
482    if KEYWORDS.contains(&cleaned.as_str()) {
483        format!("{cleaned}_")
484    } else {
485        cleaned
486    }
487}
488
489/// Return an identifier unique within a scope, tracking the ones already taken.
490///
491/// Sanitizing or PascalCasing distinct wire strings can collapse them onto the
492/// same Rust identifier, which rustc rejects as a duplicate variant or field.
493/// A numeric suffix is appended (joined by `sep`, empty for PascalCase variants
494/// and `_` for snake_case fields) until the identifier is free. Processing in
495/// the caller's existing order keeps the result deterministic.
496fn dedup(used: &mut Vec<String>, candidate: &str, sep: &str) -> String {
497    if !used.iter().any(|u| u == candidate) {
498        used.push(candidate.to_string());
499        return candidate.to_string();
500    }
501
502    let mut n = 2;
503    loop {
504        let next = format!("{candidate}{sep}{n}");
505        if !used.iter().any(|u| u == &next) {
506            used.push(next.clone());
507            return next;
508        }
509        n += 1;
510    }
511}
512
513/// Convert an arbitrary wire string into a PascalCase Rust identifier.
514fn pascal_case(name: &str) -> String {
515    let mut out = String::new();
516    let mut upper_next = true;
517
518    for c in name.chars() {
519        if c.is_ascii_alphanumeric() {
520            if upper_next {
521                out.extend(c.to_uppercase());
522            } else {
523                out.push(c);
524            }
525            upper_next = false;
526        } else {
527            upper_next = true;
528        }
529    }
530
531    if out.is_empty() || out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
532        format!("Variant{out}")
533    } else {
534        out
535    }
536}
537
538fn escape(s: &str) -> String {
539    s.replace('\\', "\\\\").replace('"', "\\\"")
540}
541
542/// Collapse a description to a single line so it cannot break out of a comment.
543fn one_line(s: &str) -> String {
544    s.replace(['\n', '\r'], " ").trim().to_string()
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use odk_schema::{CompiledModel, CompiledUnion, CompiledUnionVariant, FieldConstraints};
551
552    fn scalar(name: ScalarType) -> CompiledType {
553        CompiledType::Scalar { name }
554    }
555
556    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
557        let mut schema = CompiledSchema::new("Test");
558        for m in models {
559            schema.add_model(m);
560        }
561        schema
562    }
563
564    fn render(schema: &CompiledSchema) -> String {
565        generate(schema)
566            .get("models.rs")
567            .expect("models.rs emitted")
568            .clone()
569    }
570
571    #[test]
572    fn an_empty_schema_emits_nothing() {
573        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
574    }
575
576    #[test]
577    fn a_model_becomes_a_struct() {
578        let mut model = CompiledModel::new("Track").with_description("A track");
579        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));
580
581        let out = render(&schema_with(vec![model]));
582
583        assert!(out.contains("#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]"));
584        assert!(out.contains("pub struct Track {"));
585        assert!(out.contains("// A track"));
586        assert!(out.contains("    pub id: String,\n"));
587    }
588
589    #[test]
590    fn scalars_map_to_rust_types() {
591        let mut model = CompiledModel::new("M");
592        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
593        model.add_field(CompiledField::new("i32v", scalar(ScalarType::Int32)));
594        model.add_field(CompiledField::new("i64v", scalar(ScalarType::Int64)));
595        model.add_field(CompiledField::new("f32v", scalar(ScalarType::Float32)));
596        model.add_field(CompiledField::new("f64v", scalar(ScalarType::Float64)));
597        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
598        model.add_field(CompiledField::new("by", scalar(ScalarType::Bytes)));
599        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
600        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));
601
602        let out = render(&schema_with(vec![model]));
603
604        assert!(out.contains("pub s: String,"));
605        assert!(out.contains("pub i32v: i32,"));
606        assert!(out.contains("pub i64v: i64,"));
607        assert!(out.contains("pub f32v: f32,"));
608        assert!(out.contains("pub f64v: f64,"));
609        assert!(out.contains("pub b: bool,"));
610        assert!(out.contains("pub by: String,"));
611        assert!(out.contains("pub u: serde_json::Value,"));
612        assert!(out.contains("pub t: String,"));
613    }
614
615    #[test]
616    fn optional_fields_become_option_and_are_skipped_when_none() {
617        let mut model = CompiledModel::new("M");
618        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
619        model.add_field(CompiledField::new("maybe", scalar(ScalarType::Int64)).optional());
620
621        let out = render(&schema_with(vec![model]));
622
623        assert!(out.contains("pub must: String,"));
624        assert!(out.contains("#[serde(skip_serializing_if = \"Option::is_none\", default)]"));
625        assert!(out.contains("pub maybe: Option<i64>,"));
626    }
627
628    #[test]
629    fn arrays_and_refs_nest() {
630        let mut model = CompiledModel::new("M");
631        model.add_field(CompiledField::new(
632            "tracks",
633            CompiledType::Array {
634                items: Box::new(CompiledType::Ref {
635                    name: "Track".to_string(),
636                }),
637                length: None,
638            },
639        ));
640
641        assert!(render(&schema_with(vec![model])).contains("pub tracks: Vec<Track>,"));
642    }
643
644    #[test]
645    fn a_union_becomes_an_enum_with_per_variant_renames() {
646        let mut schema = CompiledSchema::new("Test");
647        schema.add_union(CompiledUnion {
648            name: "TrackType".to_string(),
649            variants: ["audio", "midi"]
650                .iter()
651                .map(|v| CompiledUnionVariant {
652                    name: (*v).to_string(),
653                    variant_type: None,
654                })
655                .collect(),
656            tag: None,
657            rename_all: None,
658            description: None,
659            extensions: odk_schema::Extensions::default(),
660            source: None,
661        });
662        schema.add_model(CompiledModel::new("M"));
663
664        let out = render(&schema);
665
666        assert!(out.contains("pub enum TrackType {"));
667        assert!(out.contains("    #[serde(rename = \"audio\")]\n    Audio,"));
668        assert!(out.contains("    #[serde(rename = \"midi\")]\n    Midi,"));
669    }
670
671    #[test]
672    fn a_data_carrying_union_becomes_an_internally_tagged_enum() {
673        fn obj(fields: Vec<CompiledField>) -> CompiledType {
674            CompiledType::Object { fields }
675        }
676        let vec3 = || CompiledType::fixed_array(scalar(ScalarType::Float64), 3);
677
678        let mut schema = CompiledSchema::new("Geo");
679        schema.add_union(CompiledUnion {
680            name: "OpNode".to_string(),
681            tag: Some("op".to_string()),
682            rename_all: Some("lowercase".to_string()),
683            variants: vec![
684                CompiledUnionVariant {
685                    name: "cube".to_string(),
686                    variant_type: Some(obj(vec![
687                        CompiledField::new("size", vec3()),
688                        CompiledField::new("center", scalar(ScalarType::Boolean)),
689                    ])),
690                },
691                CompiledUnionVariant {
692                    name: "translate".to_string(),
693                    variant_type: Some(obj(vec![
694                        CompiledField::new("v", vec3()),
695                        CompiledField::new("child", CompiledType::reference("OpNode")),
696                    ])),
697                },
698                CompiledUnionVariant {
699                    name: "union".to_string(),
700                    variant_type: Some(obj(vec![CompiledField::new(
701                        "children",
702                        CompiledType::array(CompiledType::reference("OpNode")),
703                    )])),
704                },
705            ],
706            description: None,
707            extensions: odk_schema::Extensions::default(),
708            source: None,
709        });
710        schema.add_model(CompiledModel::new("M"));
711
712        let out = render(&schema);
713
714        // container is an internally-tagged enum
715        assert!(
716            out.contains("#[serde(tag = \"op\", rename_all = \"lowercase\")]"),
717            "missing container tag attr:\n{out}"
718        );
719        assert!(out.contains("pub enum OpNode {"), "not an enum:\n{out}");
720        // data-carrying struct variants
721        assert!(out.contains("Cube {"), "missing Cube variant:\n{out}");
722        assert!(
723            out.contains("size: [f64; 3]"),
724            "fixed-length array wrong:\n{out}"
725        );
726        assert!(out.contains("center: bool"));
727        assert!(out.contains("Translate {"));
728        // self-recursion is boxed so the type is finite
729        assert!(
730            out.contains("child: Box<OpNode>"),
731            "recursive ref not boxed:\n{out}"
732        );
733        assert!(out.contains("Union {"));
734        // a Vec is already indirection, so it is not boxed
735        assert!(
736            out.contains("children: Vec<OpNode>"),
737            "vec recursion wrong:\n{out}"
738        );
739    }
740
741    #[test]
742    fn enum_variants_that_pascalcase_to_the_same_ident_are_disambiguated() {
743        let mut schema = CompiledSchema::new("Test");
744        schema.add_union(CompiledUnion {
745            name: "Kind".to_string(),
746            variants: ["foo-bar", "foo_bar", "audio", "Audio"]
747                .iter()
748                .map(|v| CompiledUnionVariant {
749                    name: (*v).to_string(),
750                    variant_type: None,
751                })
752                .collect(),
753            tag: None,
754            rename_all: None,
755            description: None,
756            extensions: odk_schema::Extensions::default(),
757            source: None,
758        });
759        schema.add_model(CompiledModel::new("M"));
760
761        let out = render(&schema);
762
763        // four distinct variant idents, deterministically disambiguated, each
764        // still paired with a rename back to its exact wire value
765        assert!(out.contains("#[serde(rename = \"foo-bar\")]\n    FooBar,\n"));
766        assert!(out.contains("#[serde(rename = \"foo_bar\")]\n    FooBar2,\n"));
767        assert!(out.contains("#[serde(rename = \"audio\")]\n    Audio,\n"));
768        assert!(out.contains("#[serde(rename = \"Audio\")]\n    Audio2,\n"));
769    }
770
771    #[test]
772    fn struct_fields_that_sanitize_to_the_same_ident_are_disambiguated() {
773        let mut model = CompiledModel::new("M");
774        model.add_field(CompiledField::new("foo-bar", scalar(ScalarType::String)));
775        model.add_field(CompiledField::new("foo_bar", scalar(ScalarType::String)));
776
777        let out = render(&schema_with(vec![model]));
778
779        // two distinct field idents, each carrying a rename to its wire name
780        assert!(out.contains("#[serde(rename = \"foo-bar\")]\n    pub foo_bar: String,\n"));
781        assert!(out.contains("#[serde(rename = \"foo_bar\")]\n    pub foo_bar_2: String,\n"));
782    }
783
784    #[test]
785    fn reserved_keyword_field_names_are_renamed() {
786        let mut model = CompiledModel::new("M");
787        model.add_field(CompiledField::new("type", scalar(ScalarType::String)));
788
789        let out = render(&schema_with(vec![model]));
790
791        assert!(out.contains("#[serde(rename = \"type\")]"));
792        assert!(out.contains("pub type_: String,"));
793    }
794
795    #[test]
796    fn non_identifier_field_names_are_sanitized_and_renamed() {
797        let mut model = CompiledModel::new("M");
798        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));
799
800        let out = render(&schema_with(vec![model]));
801
802        assert!(out.contains("#[serde(rename = \"kebab-case\")]"));
803        assert!(out.contains("pub kebab_case: String,"));
804    }
805
806    #[test]
807    fn constraints_are_emitted_as_comments_not_validation() {
808        let mut model = CompiledModel::new("M");
809        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
810        f.constraints = Some(FieldConstraints {
811            min_length: None,
812            max_length: None,
813            min_value: Some(20.0),
814            max_value: Some(300.0),
815            pattern: None,
816            format: None,
817            multiple_of: None,
818        });
819        model.add_field(f);
820
821        let out = render(&schema_with(vec![model]));
822        assert!(out.contains("// constraints: minimum 20, maximum 300"));
823    }
824
825    #[test]
826    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
827        let mut model = CompiledModel::new("M");
828        let mut f = CompiledField::new("a", scalar(ScalarType::String));
829        f.description = Some("line one\nline two".to_string());
830        model.add_field(f);
831
832        let out = render(&schema_with(vec![model]));
833        assert!(out.contains("// line one line two"));
834    }
835
836    #[test]
837    fn an_empty_model_is_still_valid_rust() {
838        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
839        assert!(out.contains("pub struct Empty {}"));
840    }
841
842    // Build a tagged union whose single variant is an object carrying the given
843    // fields, used to exercise the recursion detector.
844    fn tagged(name: &str, variant: &str, fields: Vec<CompiledField>) -> CompiledUnion {
845        CompiledUnion {
846            name: name.to_string(),
847            tag: Some("kind".to_string()),
848            rename_all: None,
849            variants: vec![CompiledUnionVariant {
850                name: variant.to_string(),
851                variant_type: Some(CompiledType::Object { fields }),
852            }],
853            description: None,
854            extensions: odk_schema::Extensions::default(),
855            source: None,
856        }
857    }
858
859    #[test]
860    fn self_recursion_is_not_flagged_because_the_emitter_boxes_it() {
861        // OpNode { translate { child: OpNode } } -> child is boxed, so finite
862        let mut schema = CompiledSchema::new("Geo");
863        schema.add_union(tagged(
864            "OpNode",
865            "translate",
866            vec![CompiledField::new(
867                "child",
868                CompiledType::reference("OpNode"),
869            )],
870        ));
871        assert!(unsupported_recursion(&schema).is_none());
872    }
873
874    #[test]
875    fn a_vec_reference_breaks_a_cycle_and_is_not_flagged() {
876        // A { a { b: B } }, B { b { a: [A] as a list } } -> the Vec is heap
877        // indirection, so the cycle is finite
878        let mut schema = CompiledSchema::new("G");
879        schema.add_union(tagged(
880            "A",
881            "a",
882            vec![CompiledField::new("b", CompiledType::reference("B"))],
883        ));
884        schema.add_union(tagged(
885            "B",
886            "b",
887            vec![CompiledField::new(
888                "a",
889                CompiledType::array(CompiledType::reference("A")),
890            )],
891        ));
892        assert!(unsupported_recursion(&schema).is_none());
893    }
894
895    #[test]
896    fn mutual_recursion_through_direct_refs_is_flagged() {
897        // A { a { b: B } }, B { b { a: A } } -> neither ref is a self-reference,
898        // so neither is boxed; the type is infinitely sized and will not compile
899        let mut schema = CompiledSchema::new("G");
900        schema.add_union(tagged(
901            "A",
902            "a",
903            vec![CompiledField::new("b", CompiledType::reference("B"))],
904        ));
905        schema.add_union(tagged(
906            "B",
907            "b",
908            vec![CompiledField::new("a", CompiledType::reference("A"))],
909        ));
910        let msg = unsupported_recursion(&schema).expect("mutual recursion should be flagged");
911        assert!(msg.contains('A') && msg.contains('B'), "message: {msg}");
912    }
913
914    #[test]
915    fn a_self_referential_model_field_is_flagged() {
916        // Category { parent: Category } -> a struct field is never boxed, so this
917        // is infinitely sized Rust today
918        let mut model = CompiledModel::new("Category");
919        model.add_field(CompiledField::new(
920            "parent",
921            CompiledType::reference("Category"),
922        ));
923        assert!(unsupported_recursion(&schema_with(vec![model])).is_some());
924    }
925
926    #[test]
927    fn a_literal_scalar_renders_as_its_base_type() {
928        let mut model = CompiledModel::new("M");
929        model.add_field(CompiledField::new(
930            "kind",
931            CompiledType::Literal {
932                value: LiteralValue::String("audio".to_string()),
933            },
934        ));
935
936        assert!(render(&schema_with(vec![model])).contains("pub kind: String,"));
937    }
938}