Skip to main content

odk_cli/generate/
python.rs

1//! Python model generation.
2//!
3//! Emits a `models.py` of stdlib dataclasses with JSON round-tripping, one
4//! dataclass per model and one `Literal` alias per string union.
5//!
6//! # Why dataclasses rather than pydantic
7//!
8//! Generated code inherits its dependencies onto every consumer. A schema
9//! describing a file format (the motivating case is a DAW project document)
10//! wants to be loadable in a notebook, a build script, or a CI job without
11//! pulling a validation framework in first. Dataclasses are stdlib, and
12//! `from_dict`/`to_dict` cover the round trip that matters.
13//!
14//! The cost is that this validates nothing beyond shape: an out-of-range value
15//! that the JSON Schema would reject is preserved as-is. Constraints in the IR
16//! are emitted as comments so they are visible, not enforced.
17//!
18//! # Ordering
19//!
20//! Definitions are emitted in dependency order where possible, and forward
21//! references fall back to `from __future__ import annotations`, which makes
22//! every annotation lazy and cycles harmless.
23
24use std::collections::BTreeMap;
25
26use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};
27
28/// Generate Python models for a schema.
29pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
30    let mut output = BTreeMap::new();
31
32    if schema.models.is_empty() && schema.unions.is_empty() {
33        return output;
34    }
35
36    output.insert("models.py".to_string(), generate_models(schema));
37    output
38}
39
40fn generate_models(schema: &CompiledSchema) -> String {
41    let mut out = String::new();
42
43    out.push_str(&format!(
44        "\"\"\"{} models.\n\nGenerated by ODK. Do not edit by hand.\n\"\"\"\n\n",
45        schema.name
46    ));
47    // lazy annotations so models can reference each other in any order
48    out.push_str("from __future__ import annotations\n\n");
49    out.push_str("from dataclasses import dataclass, field, fields, is_dataclass\n");
50    out.push_str("from functools import lru_cache\n");
51    out.push_str(
52        "from typing import Any, Literal, Optional, Union, get_args, get_origin, get_type_hints\n\n\n",
53    );
54
55    for union in &schema.unions {
56        let variants: Vec<String> = union
57            .variants
58            .iter()
59            .map(|v| format!("\"{}\"", escape(&v.name)))
60            .collect();
61
62        if let Some(desc) = &union.description {
63            out.push_str(&format!("# {}\n", one_line(desc)));
64        }
65        out.push_str(&format!(
66            "{} = Literal[{}]\n\n",
67            union.name,
68            variants.join(", ")
69        ));
70    }
71
72    if !schema.unions.is_empty() {
73        out.push('\n');
74    }
75
76    for model in &schema.models {
77        out.push_str(&dataclass(model));
78        out.push('\n');
79    }
80
81    out.push_str(DECODE_HELPERS);
82    out
83}
84
85fn dataclass(model: &odk_schema::CompiledModel) -> String {
86    let mut out = String::new();
87
88    out.push_str("@dataclass\n");
89    out.push_str(&format!("class {}:\n", model.name));
90
91    if let Some(desc) = &model.description {
92        out.push_str(&format!("    \"\"\"{}\"\"\"\n\n", one_line(desc)));
93    }
94
95    if model.fields.is_empty() {
96        out.push_str("    pass\n");
97        return out;
98    }
99
100    // Required fields must precede defaulted ones, or the dataclass is invalid
101    let (required, optional): (Vec<&CompiledField>, Vec<&CompiledField>) =
102        model.fields.iter().partition(|f| f.optional != Some(true));
103
104    for f in required.iter().chain(optional.iter()) {
105        let is_optional = f.optional == Some(true);
106        let annotation = if is_optional {
107            format!("Optional[{}]", type_to_py(&f.field_type))
108        } else {
109            type_to_py(&f.field_type)
110        };
111
112        if let Some(desc) = &f.description {
113            out.push_str(&format!("    # {}\n", one_line(desc)));
114        }
115        if let Some(note) = constraint_note(f) {
116            out.push_str(&format!("    # {note}\n"));
117        }
118
119        let name = py_name(&f.name);
120        // a JSON key that is not a Python identifier is carried in metadata so
121        // the decoder can still find it
122        let metadata = if name == f.name {
123            String::new()
124        } else {
125            format!(", metadata={{\"json\": \"{}\"}}", escape(&f.name))
126        };
127
128        if is_optional {
129            out.push_str(&format!(
130                "    {name}: {annotation} = field(default=None{metadata})\n"
131            ));
132        } else if metadata.is_empty() {
133            out.push_str(&format!("    {name}: {annotation}\n"));
134        } else {
135            out.push_str(&format!(
136                "    {name}: {annotation} = field({})\n",
137                &metadata[2..]
138            ));
139        }
140    }
141
142    out
143}
144
145/// Map an IR type onto a Python annotation.
146fn type_to_py(t: &CompiledType) -> String {
147    match t {
148        CompiledType::Scalar { name } => scalar_to_py(name).to_string(),
149        CompiledType::Array { items, .. } => format!("list[{}]", type_to_py(items)),
150        CompiledType::Ref { name } => name.clone(),
151        CompiledType::Literal { value } => match value {
152            LiteralValue::String(s) => format!("Literal[\"{}\"]", escape(s)),
153            LiteralValue::Number(n) => format!("Literal[{n}]"),
154            LiteralValue::Bool(b) => format!("Literal[{}]", if *b { "True" } else { "False" }),
155        },
156        CompiledType::Union { variants } => {
157            let parts: Vec<String> = variants.iter().map(type_to_py).collect();
158            format!("Union[{}]", parts.join(", "))
159        }
160        // an inline object has no name to reference, so it stays a plain mapping
161        CompiledType::Object { .. } => "dict[str, Any]".to_string(),
162    }
163}
164
165fn scalar_to_py(s: &ScalarType) -> &'static str {
166    match s {
167        ScalarType::String
168        | ScalarType::Date
169        | ScalarType::Datetime
170        | ScalarType::UtcDateTime
171        | ScalarType::OffsetDateTime
172        | ScalarType::PlainDate
173        | ScalarType::PlainTime
174        | ScalarType::Duration
175        | ScalarType::Url => "str",
176        ScalarType::Int32 | ScalarType::Int64 => "int",
177        ScalarType::Float32 | ScalarType::Float64 => "float",
178        ScalarType::Boolean => "bool",
179        ScalarType::Bytes => "bytes",
180        ScalarType::Unknown => "Any",
181    }
182}
183
184/// Render a field's constraints as a human-readable note.
185fn constraint_note(f: &CompiledField) -> Option<String> {
186    let c = f.constraints.as_ref()?;
187    let mut parts = Vec::new();
188
189    if let Some(v) = c.min_length {
190        parts.push(format!("minLength {v}"));
191    }
192    if let Some(v) = c.max_length {
193        parts.push(format!("maxLength {v}"));
194    }
195    if let Some(v) = c.min_value {
196        parts.push(format!("minimum {v}"));
197    }
198    if let Some(v) = c.max_value {
199        parts.push(format!("maximum {v}"));
200    }
201    if let Some(v) = &c.pattern {
202        parts.push(format!("pattern {v}"));
203    }
204    if let Some(v) = &c.format {
205        parts.push(format!("format {v}"));
206    }
207    if let Some(v) = c.multiple_of {
208        parts.push(format!("multipleOf {v}"));
209    }
210
211    if parts.is_empty() {
212        None
213    } else {
214        // not enforced: dataclasses validate nothing, so this is documentation
215        Some(format!("constraints: {}", parts.join(", ")))
216    }
217}
218
219/// Python keywords that cannot be used as field names.
220const KEYWORDS: &[&str] = &[
221    "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",
222    "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",
223    "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",
224    "with", "yield",
225];
226
227/// Make a JSON property name safe as a Python attribute.
228fn py_name(name: &str) -> String {
229    let cleaned: String = name
230        .chars()
231        .map(|c| {
232            if c.is_alphanumeric() || c == '_' {
233                c
234            } else {
235                '_'
236            }
237        })
238        .collect();
239
240    let cleaned = if cleaned.chars().next().is_some_and(char::is_numeric) {
241        format!("_{cleaned}")
242    } else {
243        cleaned
244    };
245
246    if KEYWORDS.contains(&cleaned.as_str()) {
247        format!("{cleaned}_")
248    } else {
249        cleaned
250    }
251}
252
253fn escape(s: &str) -> String {
254    s.replace('\\', "\\\\").replace('"', "\\\"")
255}
256
257/// Collapse a description to a single line so it cannot break out of a comment.
258fn one_line(s: &str) -> String {
259    s.replace(['\n', '\r'], " ").trim().to_string()
260}
261
262/// Decoding helpers appended to every generated module.
263const DECODE_HELPERS: &str = r#"
264def _json_key(f) -> str:
265    """JSON key for a dataclass field, honoring a remapped name."""
266    return f.metadata.get("json", f.name)
267
268
269@lru_cache(maxsize=None)
270def _hints(cls) -> dict[str, Any]:
271    """Resolved annotations for a dataclass.
272
273    `from __future__ import annotations` makes every annotation a string, so
274    `field.type` is the text "Track", not the class. Resolving through
275    get_type_hints is what lets nested models be rebuilt rather than left as
276    dicts.
277    """
278    return get_type_hints(cls)
279
280
281def _decode(value: Any, annotation: Any) -> Any:
282    """Rebuild nested dataclasses from plain JSON values.
283
284    Unknown or unannotated shapes pass through untouched, which keeps forward
285    compatibility cheap: a document carrying fields this build has never heard
286    of still loads.
287    """
288    if is_dataclass(annotation) and isinstance(value, dict):
289        return from_dict(annotation, value)
290
291    origin = get_origin(annotation)
292
293    if origin is list and isinstance(value, list):
294        (item_type,) = get_args(annotation) or (Any,)
295        return [_decode(v, item_type) for v in value]
296
297    if origin is Union:
298        args = [a for a in get_args(annotation) if a is not type(None)]
299        # Optional[T] is the overwhelmingly common case, and T can itself be a
300        # list or a model, so decode through it rather than only unwrapping
301        # dataclass members
302        if len(args) == 1:
303            return _decode(value, args[0])
304        for arg in args:
305            if is_dataclass(arg) and isinstance(value, dict):
306                return from_dict(arg, value)
307        return value
308
309    return value
310
311
312def from_dict(cls, data: dict[str, Any]):
313    """Build a dataclass instance from parsed JSON."""
314    hints = _hints(cls)
315    kwargs = {}
316    for f in fields(cls):
317        key = _json_key(f)
318        if key in data:
319            kwargs[f.name] = _decode(data[key], hints.get(f.name, Any))
320    return cls(**kwargs)
321
322
323def to_dict(obj: Any) -> Any:
324    """Convert a dataclass instance back to plain JSON values.
325
326    Fields left as None are omitted rather than emitted as null, so an
327    optional-by-absence schema round-trips to the same document it came from.
328    """
329    if is_dataclass(obj):
330        out: dict[str, Any] = {}
331        for f in fields(obj):
332            value = getattr(obj, f.name)
333            if value is None:
334                continue
335            out[_json_key(f)] = to_dict(value)
336        return out
337
338    if isinstance(obj, list):
339        return [to_dict(v) for v in obj]
340
341    return obj
342"#;
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use odk_schema::{CompiledModel, CompiledUnion, CompiledUnionVariant, FieldConstraints};
348
349    fn scalar(name: ScalarType) -> CompiledType {
350        CompiledType::Scalar { name }
351    }
352
353    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
354        let mut schema = CompiledSchema::new("Test");
355        for m in models {
356            schema.add_model(m);
357        }
358        schema
359    }
360
361    fn render(schema: &CompiledSchema) -> String {
362        generate(schema)
363            .get("models.py")
364            .expect("models.py emitted")
365            .clone()
366    }
367
368    #[test]
369    fn an_empty_schema_emits_nothing() {
370        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
371    }
372
373    #[test]
374    fn a_model_becomes_a_dataclass() {
375        let mut model = CompiledModel::new("Track").with_description("A track");
376        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));
377
378        let out = render(&schema_with(vec![model]));
379
380        assert!(out.contains("@dataclass\nclass Track:"));
381        assert!(out.contains("\"\"\"A track\"\"\""));
382        assert!(out.contains("    id: str\n"));
383    }
384
385    #[test]
386    fn scalars_map_to_python_types() {
387        let mut model = CompiledModel::new("M");
388        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
389        model.add_field(CompiledField::new("i", scalar(ScalarType::Int64)));
390        model.add_field(CompiledField::new("f", scalar(ScalarType::Float64)));
391        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
392        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
393        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));
394
395        let out = render(&schema_with(vec![model]));
396
397        assert!(out.contains("s: str"));
398        assert!(out.contains("i: int"));
399        assert!(out.contains("f: float"));
400        assert!(out.contains("b: bool"));
401        assert!(out.contains("u: Any"));
402        assert!(out.contains("t: str"));
403    }
404
405    #[test]
406    fn optional_fields_default_to_none_and_sort_after_required_ones() {
407        let mut model = CompiledModel::new("M");
408        model.add_field(CompiledField::new("maybe", scalar(ScalarType::String)).optional());
409        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
410
411        let out = render(&schema_with(vec![model]));
412        let must = out.find("must:").expect("required field");
413        let maybe = out.find("maybe:").expect("optional field");
414
415        assert!(must < maybe, "required fields must come first");
416        assert!(out.contains("maybe: Optional[str] = field(default=None)"));
417    }
418
419    #[test]
420    fn arrays_and_refs_nest() {
421        let mut model = CompiledModel::new("M");
422        model.add_field(CompiledField::new(
423            "tracks",
424            CompiledType::Array {
425                items: Box::new(CompiledType::Ref {
426                    name: "Track".to_string(),
427                }),
428                length: None,
429            },
430        ));
431
432        assert!(render(&schema_with(vec![model])).contains("tracks: list[Track]"));
433    }
434
435    #[test]
436    fn a_union_becomes_a_literal_alias() {
437        let mut schema = CompiledSchema::new("Test");
438        schema.add_union(CompiledUnion {
439            name: "TrackType".to_string(),
440            variants: ["audio", "midi"]
441                .iter()
442                .map(|v| CompiledUnionVariant {
443                    name: (*v).to_string(),
444                    variant_type: None,
445                })
446                .collect(),
447            tag: None,
448            rename_all: None,
449            description: None,
450            extensions: odk_schema::Extensions::default(),
451            source: None,
452        });
453        schema.add_model(CompiledModel::new("M"));
454
455        assert!(render(&schema).contains("TrackType = Literal[\"audio\", \"midi\"]"));
456    }
457
458    #[test]
459    fn python_keywords_and_odd_characters_are_renamed_with_a_json_mapping() {
460        let mut model = CompiledModel::new("M");
461        model.add_field(CompiledField::new("class", scalar(ScalarType::String)));
462        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));
463
464        let out = render(&schema_with(vec![model]));
465
466        assert!(out.contains("class_: str = field(metadata={\"json\": \"class\"})"));
467        assert!(out.contains("kebab_case: str = field(metadata={\"json\": \"kebab-case\"})"));
468    }
469
470    #[test]
471    fn constraints_are_emitted_as_comments_not_validation() {
472        let mut model = CompiledModel::new("M");
473        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
474        f.constraints = Some(FieldConstraints {
475            min_length: None,
476            max_length: None,
477            min_value: Some(20.0),
478            max_value: Some(300.0),
479            pattern: None,
480            format: None,
481            multiple_of: None,
482        });
483        model.add_field(f);
484
485        let out = render(&schema_with(vec![model]));
486        assert!(out.contains("# constraints: minimum 20, maximum 300"));
487    }
488
489    #[test]
490    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
491        let mut model = CompiledModel::new("M");
492        let mut f = CompiledField::new("a", scalar(ScalarType::String));
493        f.description = Some("line one\nline two".to_string());
494        model.add_field(f);
495
496        let out = render(&schema_with(vec![model]));
497        assert!(out.contains("# line one line two"));
498    }
499
500    #[test]
501    fn an_empty_model_is_still_valid_python() {
502        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
503        assert!(out.contains("class Empty:\n    pass"));
504    }
505
506    #[test]
507    fn round_trip_helpers_are_included() {
508        let mut model = CompiledModel::new("M");
509        model.add_field(CompiledField::new("a", scalar(ScalarType::String)));
510
511        let out = render(&schema_with(vec![model]));
512
513        assert!(out.contains("def from_dict("));
514        assert!(out.contains("def to_dict("));
515        assert!(out.contains("from __future__ import annotations"));
516        // lazy annotations are strings, so the decoder has to resolve them or
517        // nested models come back as plain dicts
518        assert!(out.contains("get_type_hints"));
519    }
520}