1use std::collections::BTreeMap;
19
20use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};
21
22pub 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
34const 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
58fn enum_def(union: &odk_schema::CompiledUnion) -> String {
64 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 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
97fn 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 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
180fn variant_field_type(t: &CompiledType, self_name: &str) -> String {
184 match t {
185 CompiledType::Ref { name } if name == self_name => format!("Box<{name}>"),
186 _ => type_to_rust(t),
187 }
188}
189
190fn struct_def(model: &odk_schema::CompiledModel) -> String {
191 let mut out = String::new();
192
193 if let Some(desc) = &model.description {
194 out.push_str(&format!("// {}\n", one_line(desc)));
195 }
196
197 out.push_str(DERIVE);
198 out.push('\n');
199
200 if model.fields.is_empty() {
201 out.push_str(&format!("pub struct {} {{}}\n", model.name));
202 return out;
203 }
204
205 out.push_str(&format!("pub struct {} {{\n", model.name));
206
207 let mut used: Vec<String> = Vec::new();
208 for f in &model.fields {
209 if let Some(desc) = &f.description {
210 out.push_str(&format!(" // {}\n", one_line(desc)));
211 }
212 if let Some(note) = constraint_note(f) {
213 out.push_str(&format!(" // {note}\n"));
214 }
215
216 let ident = dedup(&mut used, &field_ident(&f.name), "_");
219 let is_optional = f.optional == Some(true);
220
221 let mut serde_parts: Vec<String> = Vec::new();
222 if ident != f.name {
225 serde_parts.push(format!("rename = \"{}\"", escape(&f.name)));
226 }
227 if is_optional {
228 serde_parts.push("skip_serializing_if = \"Option::is_none\"".to_string());
229 serde_parts.push("default".to_string());
230 }
231 if !serde_parts.is_empty() {
232 out.push_str(&format!(" #[serde({})]\n", serde_parts.join(", ")));
233 }
234
235 let ty = type_to_rust(&f.field_type);
236 let ty = if is_optional {
237 format!("Option<{ty}>")
238 } else {
239 ty
240 };
241 out.push_str(&format!(" pub {ident}: {ty},\n"));
242 }
243
244 out.push_str("}\n");
245 out
246}
247
248fn type_to_rust(t: &CompiledType) -> String {
250 match t {
251 CompiledType::Scalar { name } => scalar_to_rust(name).to_string(),
252 CompiledType::Array {
255 items,
256 length: Some(n),
257 } => format!("[{}; {}]", type_to_rust(items), n),
258 CompiledType::Array {
259 items,
260 length: None,
261 } => {
262 format!("Vec<{}>", type_to_rust(items))
263 }
264 CompiledType::Ref { name } => name.clone(),
265 CompiledType::Literal { value } => match value {
266 LiteralValue::String(_) => "String".to_string(),
267 LiteralValue::Number(_) => "f64".to_string(),
268 LiteralValue::Bool(_) => "bool".to_string(),
269 },
270 CompiledType::Union { .. } => "serde_json::Value".to_string(),
273 CompiledType::Object { .. } => "serde_json::Value".to_string(),
276 }
277}
278
279fn scalar_to_rust(s: &ScalarType) -> &'static str {
280 match s {
281 ScalarType::String
284 | ScalarType::Date
285 | ScalarType::Datetime
286 | ScalarType::UtcDateTime
287 | ScalarType::OffsetDateTime
288 | ScalarType::PlainDate
289 | ScalarType::PlainTime
290 | ScalarType::Duration
291 | ScalarType::Bytes
292 | ScalarType::Url => "String",
293 ScalarType::Int32 => "i32",
294 ScalarType::Int64 => "i64",
295 ScalarType::Float32 => "f32",
296 ScalarType::Float64 => "f64",
297 ScalarType::Boolean => "bool",
298 ScalarType::Unknown => "serde_json::Value",
299 }
300}
301
302fn constraint_note(f: &CompiledField) -> Option<String> {
304 let c = f.constraints.as_ref()?;
305 let mut parts = Vec::new();
306
307 if let Some(v) = c.min_length {
308 parts.push(format!("minLength {v}"));
309 }
310 if let Some(v) = c.max_length {
311 parts.push(format!("maxLength {v}"));
312 }
313 if let Some(v) = c.min_value {
314 parts.push(format!("minimum {v}"));
315 }
316 if let Some(v) = c.max_value {
317 parts.push(format!("maximum {v}"));
318 }
319 if let Some(v) = &c.pattern {
320 parts.push(format!("pattern {v}"));
321 }
322 if let Some(v) = &c.format {
323 parts.push(format!("format {v}"));
324 }
325 if let Some(v) = c.multiple_of {
326 parts.push(format!("multipleOf {v}"));
327 }
328
329 if parts.is_empty() {
330 None
331 } else {
332 Some(format!("constraints: {}", parts.join(", ")))
334 }
335}
336
337const KEYWORDS: &[&str] = &[
340 "as", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn",
341 "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
342 "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
343 "use", "where", "while", "async", "await", "abstract", "become", "box", "do", "final", "gen",
344 "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
345];
346
347fn field_ident(name: &str) -> String {
353 let mut cleaned: String = name
354 .chars()
355 .map(|c| {
356 if c.is_ascii_alphanumeric() || c == '_' {
357 c
358 } else {
359 '_'
360 }
361 })
362 .collect();
363
364 if cleaned.is_empty() || cleaned.chars().next().is_some_and(|c| c.is_ascii_digit()) {
365 cleaned = format!("_{cleaned}");
366 }
367
368 if KEYWORDS.contains(&cleaned.as_str()) {
369 format!("{cleaned}_")
370 } else {
371 cleaned
372 }
373}
374
375fn dedup(used: &mut Vec<String>, candidate: &str, sep: &str) -> String {
383 if !used.iter().any(|u| u == candidate) {
384 used.push(candidate.to_string());
385 return candidate.to_string();
386 }
387
388 let mut n = 2;
389 loop {
390 let next = format!("{candidate}{sep}{n}");
391 if !used.iter().any(|u| u == &next) {
392 used.push(next.clone());
393 return next;
394 }
395 n += 1;
396 }
397}
398
399fn pascal_case(name: &str) -> String {
401 let mut out = String::new();
402 let mut upper_next = true;
403
404 for c in name.chars() {
405 if c.is_ascii_alphanumeric() {
406 if upper_next {
407 out.extend(c.to_uppercase());
408 } else {
409 out.push(c);
410 }
411 upper_next = false;
412 } else {
413 upper_next = true;
414 }
415 }
416
417 if out.is_empty() || out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
418 format!("Variant{out}")
419 } else {
420 out
421 }
422}
423
424fn escape(s: &str) -> String {
425 s.replace('\\', "\\\\").replace('"', "\\\"")
426}
427
428fn one_line(s: &str) -> String {
430 s.replace(['\n', '\r'], " ").trim().to_string()
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436 use odk_schema::{CompiledModel, CompiledUnion, CompiledUnionVariant, FieldConstraints};
437
438 fn scalar(name: ScalarType) -> CompiledType {
439 CompiledType::Scalar { name }
440 }
441
442 fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
443 let mut schema = CompiledSchema::new("Test");
444 for m in models {
445 schema.add_model(m);
446 }
447 schema
448 }
449
450 fn render(schema: &CompiledSchema) -> String {
451 generate(schema)
452 .get("models.rs")
453 .expect("models.rs emitted")
454 .clone()
455 }
456
457 #[test]
458 fn an_empty_schema_emits_nothing() {
459 assert!(generate(&CompiledSchema::new("Empty")).is_empty());
460 }
461
462 #[test]
463 fn a_model_becomes_a_struct() {
464 let mut model = CompiledModel::new("Track").with_description("A track");
465 model.add_field(CompiledField::new("id", scalar(ScalarType::String)));
466
467 let out = render(&schema_with(vec![model]));
468
469 assert!(out.contains("#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]"));
470 assert!(out.contains("pub struct Track {"));
471 assert!(out.contains("// A track"));
472 assert!(out.contains(" pub id: String,\n"));
473 }
474
475 #[test]
476 fn scalars_map_to_rust_types() {
477 let mut model = CompiledModel::new("M");
478 model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
479 model.add_field(CompiledField::new("i32v", scalar(ScalarType::Int32)));
480 model.add_field(CompiledField::new("i64v", scalar(ScalarType::Int64)));
481 model.add_field(CompiledField::new("f32v", scalar(ScalarType::Float32)));
482 model.add_field(CompiledField::new("f64v", scalar(ScalarType::Float64)));
483 model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
484 model.add_field(CompiledField::new("by", scalar(ScalarType::Bytes)));
485 model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
486 model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));
487
488 let out = render(&schema_with(vec![model]));
489
490 assert!(out.contains("pub s: String,"));
491 assert!(out.contains("pub i32v: i32,"));
492 assert!(out.contains("pub i64v: i64,"));
493 assert!(out.contains("pub f32v: f32,"));
494 assert!(out.contains("pub f64v: f64,"));
495 assert!(out.contains("pub b: bool,"));
496 assert!(out.contains("pub by: String,"));
497 assert!(out.contains("pub u: serde_json::Value,"));
498 assert!(out.contains("pub t: String,"));
499 }
500
501 #[test]
502 fn optional_fields_become_option_and_are_skipped_when_none() {
503 let mut model = CompiledModel::new("M");
504 model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
505 model.add_field(CompiledField::new("maybe", scalar(ScalarType::Int64)).optional());
506
507 let out = render(&schema_with(vec![model]));
508
509 assert!(out.contains("pub must: String,"));
510 assert!(out.contains("#[serde(skip_serializing_if = \"Option::is_none\", default)]"));
511 assert!(out.contains("pub maybe: Option<i64>,"));
512 }
513
514 #[test]
515 fn arrays_and_refs_nest() {
516 let mut model = CompiledModel::new("M");
517 model.add_field(CompiledField::new(
518 "tracks",
519 CompiledType::Array {
520 items: Box::new(CompiledType::Ref {
521 name: "Track".to_string(),
522 }),
523 length: None,
524 },
525 ));
526
527 assert!(render(&schema_with(vec![model])).contains("pub tracks: Vec<Track>,"));
528 }
529
530 #[test]
531 fn a_union_becomes_an_enum_with_per_variant_renames() {
532 let mut schema = CompiledSchema::new("Test");
533 schema.add_union(CompiledUnion {
534 name: "TrackType".to_string(),
535 variants: ["audio", "midi"]
536 .iter()
537 .map(|v| CompiledUnionVariant {
538 name: (*v).to_string(),
539 variant_type: None,
540 })
541 .collect(),
542 tag: None,
543 rename_all: None,
544 description: None,
545 extensions: odk_schema::Extensions::default(),
546 source: None,
547 });
548 schema.add_model(CompiledModel::new("M"));
549
550 let out = render(&schema);
551
552 assert!(out.contains("pub enum TrackType {"));
553 assert!(out.contains(" #[serde(rename = \"audio\")]\n Audio,"));
554 assert!(out.contains(" #[serde(rename = \"midi\")]\n Midi,"));
555 }
556
557 #[test]
558 fn a_data_carrying_union_becomes_an_internally_tagged_enum() {
559 fn obj(fields: Vec<CompiledField>) -> CompiledType {
560 CompiledType::Object { fields }
561 }
562 let vec3 = || CompiledType::fixed_array(scalar(ScalarType::Float64), 3);
563
564 let mut schema = CompiledSchema::new("Geo");
565 schema.add_union(CompiledUnion {
566 name: "OpNode".to_string(),
567 tag: Some("op".to_string()),
568 rename_all: Some("lowercase".to_string()),
569 variants: vec![
570 CompiledUnionVariant {
571 name: "cube".to_string(),
572 variant_type: Some(obj(vec![
573 CompiledField::new("size", vec3()),
574 CompiledField::new("center", scalar(ScalarType::Boolean)),
575 ])),
576 },
577 CompiledUnionVariant {
578 name: "translate".to_string(),
579 variant_type: Some(obj(vec![
580 CompiledField::new("v", vec3()),
581 CompiledField::new("child", CompiledType::reference("OpNode")),
582 ])),
583 },
584 CompiledUnionVariant {
585 name: "union".to_string(),
586 variant_type: Some(obj(vec![CompiledField::new(
587 "children",
588 CompiledType::array(CompiledType::reference("OpNode")),
589 )])),
590 },
591 ],
592 description: None,
593 extensions: odk_schema::Extensions::default(),
594 source: None,
595 });
596 schema.add_model(CompiledModel::new("M"));
597
598 let out = render(&schema);
599
600 assert!(
602 out.contains("#[serde(tag = \"op\", rename_all = \"lowercase\")]"),
603 "missing container tag attr:\n{out}"
604 );
605 assert!(out.contains("pub enum OpNode {"), "not an enum:\n{out}");
606 assert!(out.contains("Cube {"), "missing Cube variant:\n{out}");
608 assert!(
609 out.contains("size: [f64; 3]"),
610 "fixed-length array wrong:\n{out}"
611 );
612 assert!(out.contains("center: bool"));
613 assert!(out.contains("Translate {"));
614 assert!(
616 out.contains("child: Box<OpNode>"),
617 "recursive ref not boxed:\n{out}"
618 );
619 assert!(out.contains("Union {"));
620 assert!(
622 out.contains("children: Vec<OpNode>"),
623 "vec recursion wrong:\n{out}"
624 );
625 }
626
627 #[test]
628 fn enum_variants_that_pascalcase_to_the_same_ident_are_disambiguated() {
629 let mut schema = CompiledSchema::new("Test");
630 schema.add_union(CompiledUnion {
631 name: "Kind".to_string(),
632 variants: ["foo-bar", "foo_bar", "audio", "Audio"]
633 .iter()
634 .map(|v| CompiledUnionVariant {
635 name: (*v).to_string(),
636 variant_type: None,
637 })
638 .collect(),
639 tag: None,
640 rename_all: None,
641 description: None,
642 extensions: odk_schema::Extensions::default(),
643 source: None,
644 });
645 schema.add_model(CompiledModel::new("M"));
646
647 let out = render(&schema);
648
649 assert!(out.contains("#[serde(rename = \"foo-bar\")]\n FooBar,\n"));
652 assert!(out.contains("#[serde(rename = \"foo_bar\")]\n FooBar2,\n"));
653 assert!(out.contains("#[serde(rename = \"audio\")]\n Audio,\n"));
654 assert!(out.contains("#[serde(rename = \"Audio\")]\n Audio2,\n"));
655 }
656
657 #[test]
658 fn struct_fields_that_sanitize_to_the_same_ident_are_disambiguated() {
659 let mut model = CompiledModel::new("M");
660 model.add_field(CompiledField::new("foo-bar", scalar(ScalarType::String)));
661 model.add_field(CompiledField::new("foo_bar", scalar(ScalarType::String)));
662
663 let out = render(&schema_with(vec![model]));
664
665 assert!(out.contains("#[serde(rename = \"foo-bar\")]\n pub foo_bar: String,\n"));
667 assert!(out.contains("#[serde(rename = \"foo_bar\")]\n pub foo_bar_2: String,\n"));
668 }
669
670 #[test]
671 fn reserved_keyword_field_names_are_renamed() {
672 let mut model = CompiledModel::new("M");
673 model.add_field(CompiledField::new("type", scalar(ScalarType::String)));
674
675 let out = render(&schema_with(vec![model]));
676
677 assert!(out.contains("#[serde(rename = \"type\")]"));
678 assert!(out.contains("pub type_: String,"));
679 }
680
681 #[test]
682 fn non_identifier_field_names_are_sanitized_and_renamed() {
683 let mut model = CompiledModel::new("M");
684 model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));
685
686 let out = render(&schema_with(vec![model]));
687
688 assert!(out.contains("#[serde(rename = \"kebab-case\")]"));
689 assert!(out.contains("pub kebab_case: String,"));
690 }
691
692 #[test]
693 fn constraints_are_emitted_as_comments_not_validation() {
694 let mut model = CompiledModel::new("M");
695 let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
696 f.constraints = Some(FieldConstraints {
697 min_length: None,
698 max_length: None,
699 min_value: Some(20.0),
700 max_value: Some(300.0),
701 pattern: None,
702 format: None,
703 multiple_of: None,
704 });
705 model.add_field(f);
706
707 let out = render(&schema_with(vec![model]));
708 assert!(out.contains("// constraints: minimum 20, maximum 300"));
709 }
710
711 #[test]
712 fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
713 let mut model = CompiledModel::new("M");
714 let mut f = CompiledField::new("a", scalar(ScalarType::String));
715 f.description = Some("line one\nline two".to_string());
716 model.add_field(f);
717
718 let out = render(&schema_with(vec![model]));
719 assert!(out.contains("// line one line two"));
720 }
721
722 #[test]
723 fn an_empty_model_is_still_valid_rust() {
724 let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
725 assert!(out.contains("pub struct Empty {}"));
726 }
727
728 #[test]
729 fn a_literal_scalar_renders_as_its_base_type() {
730 let mut model = CompiledModel::new("M");
731 model.add_field(CompiledField::new(
732 "kind",
733 CompiledType::Literal {
734 value: LiteralValue::String("audio".to_string()),
735 },
736 ));
737
738 assert!(render(&schema_with(vec![model])).contains("pub kind: String,"));
739 }
740}