use std::collections::BTreeMap;
use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};
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
}
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
}
fn enum_def(union: &odk_schema::CompiledUnion) -> String {
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 {
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
}
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), "");
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
}
pub(crate) fn unsupported_recursion(schema: &CompiledSchema) -> Option<String> {
let mut edges: BTreeMap<String, Vec<String>> = BTreeMap::new();
for model in &schema.models {
let mut targets = Vec::new();
for f in &model.fields {
collect_sized_refs(&f.field_type, &mut targets);
}
edges.insert(model.name.clone(), targets);
}
for union in &schema.unions {
let mut targets = Vec::new();
for v in &union.variants {
match &v.variant_type {
Some(CompiledType::Object { fields }) => {
for f in fields {
if matches!(&f.field_type, CompiledType::Ref { name } if name == &union.name)
{
continue;
}
collect_sized_refs(&f.field_type, &mut targets);
}
}
Some(CompiledType::Ref { name }) if name != &union.name => {
targets.push(name.clone());
}
Some(CompiledType::Ref { .. }) | None => {}
Some(other) => collect_sized_refs(other, &mut targets),
}
}
edges.insert(union.name.clone(), targets);
}
let mut state: BTreeMap<String, u8> = edges.keys().map(|k| (k.clone(), 0u8)).collect();
for start in edges.keys() {
if state.get(start).copied().unwrap_or(0) == 0
&& let Some(cycle) = dfs_cycle(start, &edges, &mut state, &mut Vec::new())
{
return Some(format!(
"the Rust target cannot emit the recursive type cycle {}: the references are \
inline, so the type is infinitely sized and the generated Rust will not \
compile. ODK boxes a direct self-reference inside a tagged union, but not a \
cycle through other types. Break the cycle with a list field, or generate \
these types with -t typescript.",
cycle.join(" -> ")
));
}
}
None
}
fn collect_sized_refs(t: &CompiledType, out: &mut Vec<String>) {
match t {
CompiledType::Ref { name } => out.push(name.clone()),
CompiledType::Array {
items,
length: Some(_),
} => collect_sized_refs(items, out),
_ => {}
}
}
fn dfs_cycle(
node: &str,
edges: &BTreeMap<String, Vec<String>>,
state: &mut BTreeMap<String, u8>,
stack: &mut Vec<String>,
) -> Option<Vec<String>> {
state.insert(node.to_string(), 1);
stack.push(node.to_string());
if let Some(neighbours) = edges.get(node) {
for n in neighbours {
match state.get(n).copied().unwrap_or(0) {
1 => {
let at = stack.iter().position(|s| s == n).unwrap_or(0);
let mut cycle = stack[at..].to_vec();
cycle.push(n.clone());
return Some(cycle);
}
0 => {
if let Some(cycle) = dfs_cycle(n, edges, state, stack) {
return Some(cycle);
}
}
_ => {}
}
}
}
stack.pop();
state.insert(node.to_string(), 2);
None
}
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"));
}
let ident = dedup(&mut used, &field_ident(&f.name), "_");
let is_optional = f.optional == Some(true);
let mut serde_parts: Vec<String> = Vec::new();
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
}
fn type_to_rust(t: &CompiledType) -> String {
match t {
CompiledType::Scalar { name } => scalar_to_rust(name).to_string(),
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(),
},
CompiledType::Union { .. } => "serde_json::Value".to_string(),
CompiledType::Object { .. } => "serde_json::Value".to_string(),
}
}
fn scalar_to_rust(s: &ScalarType) -> &'static str {
match s {
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 | ScalarType::Safeint => "i64",
ScalarType::Float32 => "f32",
ScalarType::Float64 => "f64",
ScalarType::Boolean => "bool",
ScalarType::Unknown => "serde_json::Value",
}
}
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 {
Some(format!("constraints: {}", parts.join(", ")))
}
}
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",
];
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
}
}
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;
}
}
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('"', "\\\"")
}
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);
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}");
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 {"));
assert!(
out.contains("child: Box<OpNode>"),
"recursive ref not boxed:\n{out}"
);
assert!(out.contains("Union {"));
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);
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]));
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 {}"));
}
fn tagged(name: &str, variant: &str, fields: Vec<CompiledField>) -> CompiledUnion {
CompiledUnion {
name: name.to_string(),
tag: Some("kind".to_string()),
rename_all: None,
variants: vec![CompiledUnionVariant {
name: variant.to_string(),
variant_type: Some(CompiledType::Object { fields }),
}],
description: None,
extensions: odk_schema::Extensions::default(),
source: None,
}
}
#[test]
fn self_recursion_is_not_flagged_because_the_emitter_boxes_it() {
let mut schema = CompiledSchema::new("Geo");
schema.add_union(tagged(
"OpNode",
"translate",
vec![CompiledField::new(
"child",
CompiledType::reference("OpNode"),
)],
));
assert!(unsupported_recursion(&schema).is_none());
}
#[test]
fn a_vec_reference_breaks_a_cycle_and_is_not_flagged() {
let mut schema = CompiledSchema::new("G");
schema.add_union(tagged(
"A",
"a",
vec![CompiledField::new("b", CompiledType::reference("B"))],
));
schema.add_union(tagged(
"B",
"b",
vec![CompiledField::new(
"a",
CompiledType::array(CompiledType::reference("A")),
)],
));
assert!(unsupported_recursion(&schema).is_none());
}
#[test]
fn mutual_recursion_through_direct_refs_is_flagged() {
let mut schema = CompiledSchema::new("G");
schema.add_union(tagged(
"A",
"a",
vec![CompiledField::new("b", CompiledType::reference("B"))],
));
schema.add_union(tagged(
"B",
"b",
vec![CompiledField::new("a", CompiledType::reference("A"))],
));
let msg = unsupported_recursion(&schema).expect("mutual recursion should be flagged");
assert!(msg.contains('A') && msg.contains('B'), "message: {msg}");
}
#[test]
fn a_self_referential_model_field_is_flagged() {
let mut model = CompiledModel::new("Category");
model.add_field(CompiledField::new(
"parent",
CompiledType::reference("Category"),
));
assert!(unsupported_recursion(&schema_with(vec![model])).is_some());
}
#[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,"));
}
}