Skip to main content

openapi_nexus/generators/python/httpx/
emit_models.rs

1//! Model emission for IR schemas (Python dataclasses/enums/aliases).
2//!
3//! Uses sigil-stitch high-level APIs (TypeSpec, FieldSpec, FunSpec, TypeName,
4//! sigil_quote!) for structured code generation with automatic import tracking.
5//! Each schema produces one `.py` file via `FileSpec`.
6
7use crate::codegen::traits::file_writer::FileInfo;
8use crate::ir::types::{
9    IrEnum, IrEnumValueType, IrIntersection, IrObject, IrPrimitive, IrProperty, IrSchema,
10    IrSchemaKind, IrSpec, IrTaggedUnion, IrTypeExpr, IrUnion, TaggingStyle,
11};
12use heck::{ToPascalCase, ToSnakeCase};
13use sigil_stitch::code_block::CodeBlock;
14use sigil_stitch::lang::python::Python;
15use sigil_stitch::prelude::*;
16
17/// Generate every model file from the IR.
18pub fn generate_model_files(ir: &IrSpec, header: &str) -> Result<Vec<FileInfo>, String> {
19    let mut files = Vec::new();
20    for (_name, schema) in &ir.schemas {
21        let body = emit_model_body(schema, ir).ok_or_else(|| {
22            format!(
23                "unsupported schema kind for {}: {:?}",
24                schema.name, schema.kind
25            )
26        })?;
27        let stem = schema.name.to_snake_case();
28        let filename = format!("{stem}.py");
29        let mut content = String::with_capacity(header.len() + body.len());
30        content.push_str(header);
31        content.push_str(&body);
32        files.push(FileInfo::model(filename, content));
33    }
34    Ok(files)
35}
36
37fn emit_model_body(schema: &IrSchema, ir: &IrSpec) -> Option<String> {
38    let file_spec = match &schema.kind {
39        IrSchemaKind::Object(obj) => emit_object(schema, obj, ir),
40        IrSchemaKind::Enum(en) => emit_enum(schema, en),
41        IrSchemaKind::Alias(expr) => emit_alias(schema, expr),
42        IrSchemaKind::Union(u) => emit_union(schema, u),
43        IrSchemaKind::Intersection(i) => emit_intersection(schema, i, ir),
44        IrSchemaKind::TaggedUnion(tu) => emit_tagged_union(schema, tu),
45    }?;
46    file_spec.render(100).ok()
47}
48
49pub fn future_annotations_header() -> CodeBlock {
50    CodeBlock::of("from __future__ import annotations", ()).expect("static header")
51}
52
53// ---------------------------------------------------------------------------
54// Object -> @dataclass
55// ---------------------------------------------------------------------------
56
57fn emit_object(schema: &IrSchema, obj: &IrObject, ir: &IrSpec) -> Option<FileSpec> {
58    let name = schema.name.to_pascal_case();
59
60    let mut file =
61        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
62
63    if needs_typing_literal_in_props(&obj.properties) {
64        file = file.add_import(ImportSpec::named("typing", "Literal"));
65    }
66
67    let dataclass_tn = TypeName::importable("dataclasses", "dataclass");
68    let mut cls = TypeSpec::builder(&name, TypeKind::Class)
69        .annotate(AnnotationSpec::importable(dataclass_tn));
70
71    if let Some(doc) = &schema.description {
72        cls = cls.doc(&format!("{}.", escape_docstring(doc)));
73    }
74
75    let mut required: Vec<(&String, &IrProperty)> = Vec::new();
76    let mut optional: Vec<(&String, &IrProperty)> = Vec::new();
77    for (json_name, prop) in &obj.properties {
78        if prop.required && !prop.nullable {
79            required.push((json_name, prop));
80        } else {
81            optional.push((json_name, prop));
82        }
83    }
84
85    let all_fields: Vec<(&String, &IrProperty)> =
86        required.iter().chain(optional.iter()).copied().collect();
87
88    if all_fields.is_empty() {
89        cls = cls.extra_member(CodeBlock::of("pass", ()).expect("pass"));
90    } else {
91        for (_json_name, prop) in &required {
92            let field_name = python_field_name(&prop.name);
93            let type_name = python_type_name(&prop.type_expr);
94            cls = cls.add_field(
95                FieldSpec::builder(&field_name, type_name)
96                    .build()
97                    .expect("required field"),
98            );
99        }
100        for (_json_name, prop) in &optional {
101            let field_name = python_field_name(&prop.name);
102            let type_name = python_type_name(&prop.type_expr);
103            cls = cls.add_field(
104                FieldSpec::builder(&field_name, TypeName::optional(type_name))
105                    .initializer(CodeBlock::of("None", ()).expect("None init"))
106                    .build()
107                    .expect("optional field"),
108            );
109        }
110
111        cls = cls.add_method(build_to_dict_method(&all_fields, ir, &obj.properties));
112        cls = cls.add_method(build_from_dict_method(
113            &name,
114            &all_fields,
115            ir,
116            &obj.properties,
117        ));
118    }
119
120    file = file.add_type(cls.build().ok()?);
121    file.build().ok()
122}
123
124fn build_to_dict_method(
125    all_fields: &[(&String, &IrProperty)],
126    ir: &IrSpec,
127    properties: &indexmap::IndexMap<String, IrProperty>,
128) -> FunSpec {
129    let self_param = ParameterSpec::of("self", TypeName::primitive(""));
130    let return_type = TypeName::generic(
131        TypeName::primitive("dict"),
132        vec![TypeName::primitive("str"), TypeName::primitive("object")],
133    );
134
135    let mut body = CodeBlock::builder();
136    body.add_statement("result: dict[str, object] = {}", ());
137    for (json_name, prop) in all_fields {
138        let field_name = python_field_name(&prop.name);
139        let to_expr = render_to_dict_expr(&format!("self.{field_name}"), json_name, ir, properties);
140        if prop.required && !prop.nullable {
141            body.add_statement(&format!("result[\"{json_name}\"] = {to_expr}"), ());
142        } else {
143            body.add_statement(&format!("if self.{field_name} is not None:%>"), ());
144            body.add_statement(&format!("result[\"{json_name}\"] = {to_expr}%<"), ());
145        }
146    }
147    body.add_statement("return result", ());
148
149    FunSpec::builder("to_dict")
150        .add_param(self_param)
151        .returns(return_type)
152        .body(body.build().expect("to_dict body"))
153        .build()
154        .expect("to_dict method")
155}
156
157fn build_from_dict_method(
158    class_name: &str,
159    all_fields: &[(&String, &IrProperty)],
160    ir: &IrSpec,
161    properties: &indexmap::IndexMap<String, IrProperty>,
162) -> FunSpec {
163    let cls_param = ParameterSpec::of("cls", TypeName::primitive(""));
164    let data_param = ParameterSpec::of(
165        "data",
166        TypeName::generic(
167            TypeName::primitive("dict"),
168            vec![TypeName::primitive("str"), TypeName::primitive("object")],
169        ),
170    );
171
172    let mut body = CodeBlock::builder();
173    body.add_statement("return cls(%>", ());
174    for (json_name, prop) in all_fields {
175        let field_name = python_field_name(&prop.name);
176        let is_required = prop.required && !prop.nullable;
177        let expr = if is_required {
178            render_from_dict_expr(json_name, ir, properties)
179        } else {
180            render_from_dict_optional_expr(json_name, ir, properties)
181        };
182        if let Some(comment_start) = expr.find("  #") {
183            let (value_part, comment_part) = expr.split_at(comment_start);
184            body.add_statement(&format!("{field_name}={value_part},{comment_part}"), ());
185        } else {
186            body.add_statement(&format!("{field_name}={expr},"), ());
187        }
188    }
189    body.add("%<", ());
190    body.add_statement(")", ());
191
192    FunSpec::builder("from_dict")
193        .annotation(CodeBlock::of("@classmethod", ()).expect("classmethod"))
194        .add_param(cls_param)
195        .add_param(data_param)
196        .returns(TypeName::primitive(class_name))
197        .body(body.build().expect("from_dict body"))
198        .build()
199        .expect("from_dict method")
200}
201
202// ---------------------------------------------------------------------------
203// Enum -> class(str, Enum) or class(int, Enum)
204// ---------------------------------------------------------------------------
205
206fn emit_enum(schema: &IrSchema, en: &IrEnum) -> Option<FileSpec> {
207    if en.value_type == IrEnumValueType::Mixed {
208        return emit_type_alias_raw(schema, "object");
209    }
210
211    let name = schema.name.to_pascal_case();
212    let base = match en.value_type {
213        IrEnumValueType::String => TypeName::primitive("str"),
214        IrEnumValueType::Integer | IrEnumValueType::Number => TypeName::primitive("int"),
215        IrEnumValueType::Mixed => unreachable!(),
216    };
217
218    let mut ts = TypeSpec::builder(&name, TypeKind::Enum)
219        .extends(base)
220        .extends(TypeName::importable("enum", "Enum"));
221
222    if let Some(doc) = &schema.description {
223        ts = ts.doc(&format!("{}.", escape_docstring(doc)));
224    }
225
226    for v in &en.values {
227        let (member_name, value_code) = match en.value_type {
228            IrEnumValueType::String => {
229                let s = v.value.as_str()?;
230                (
231                    python_enum_member_name(s),
232                    format!("\"{}\"", escape_python_string(s)),
233                )
234            }
235            IrEnumValueType::Integer | IrEnumValueType::Number => {
236                let n = v
237                    .value
238                    .as_i64()
239                    .or_else(|| v.value.as_f64().map(|f| f as i64))?;
240                (format!("N{n}").replace('-', "NEG"), format!("{n}"))
241            }
242            IrEnumValueType::Mixed => unreachable!(),
243        };
244        ts = ts.add_variant(
245            EnumVariantSpec::builder(&member_name)
246                .value(CodeBlock::of(&value_code, ()).expect("enum value"))
247                .build()
248                .expect("enum variant"),
249        );
250    }
251
252    let file = FileSpec::builder_with("model.py", Python::new())
253        .header(future_annotations_header())
254        .add_type(ts.build().ok()?);
255    file.build().ok()
256}
257
258// ---------------------------------------------------------------------------
259// Alias -> type X = Y (PEP 695)
260// ---------------------------------------------------------------------------
261
262fn emit_alias(schema: &IrSchema, expr: &IrTypeExpr) -> Option<FileSpec> {
263    let name = schema.name.to_pascal_case();
264    let rhs_type = python_type_name(expr);
265
266    let type_alias = sigil_quote!(Python {
267        type $N(name.as_str()) = $T(rhs_type);
268    })
269    .ok()?;
270
271    let mut file =
272        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
273    if needs_typing_literal(expr) {
274        file = file.add_import(ImportSpec::named("typing", "Literal"));
275    }
276    if let Some(doc) = &schema.description {
277        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
278    }
279    file = file.add_code(type_alias);
280    file.build().ok()
281}
282
283fn emit_type_alias_raw(schema: &IrSchema, rhs: &str) -> Option<FileSpec> {
284    let name = schema.name.to_pascal_case();
285
286    let type_alias = sigil_quote!(Python {
287        type $N(name.as_str()) = $L(rhs);
288    })
289    .ok()?;
290
291    let mut file =
292        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
293    if let Some(doc) = &schema.description {
294        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
295    }
296    file = file.add_code(type_alias);
297    file.build().ok()
298}
299
300// ---------------------------------------------------------------------------
301// Union -> type X = A | B | C
302// ---------------------------------------------------------------------------
303
304fn emit_union(schema: &IrSchema, u: &IrUnion) -> Option<FileSpec> {
305    let name = schema.name.to_pascal_case();
306
307    let mut members: Vec<TypeName> = u.members.iter().map(python_type_name).collect();
308    if u.nullable {
309        members.push(TypeName::primitive("None"));
310    }
311    let union_ty = if members.is_empty() {
312        TypeName::importable("typing", "Any")
313    } else {
314        TypeName::union(members)
315    };
316
317    let type_alias = sigil_quote!(Python {
318        type $N(name.as_str()) = $T(union_ty);
319    })
320    .ok()?;
321
322    let mut file =
323        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
324    if needs_typing_literal_in_exprs(&u.members) {
325        file = file.add_import(ImportSpec::named("typing", "Literal"));
326    }
327    if let Some(doc) = &schema.description {
328        file = file.add_raw(&format!("# {}\n", escape_docstring(doc)));
329    }
330    file = file.add_code(type_alias);
331    file.build().ok()
332}
333
334// ---------------------------------------------------------------------------
335// Intersection -> merged @dataclass
336// ---------------------------------------------------------------------------
337
338fn emit_intersection(schema: &IrSchema, inter: &IrIntersection, ir: &IrSpec) -> Option<FileSpec> {
339    let mut all_props: indexmap::IndexMap<String, IrProperty> = indexmap::IndexMap::new();
340    for member in &inter.members {
341        if let IrTypeExpr::Named(ref_name) = member
342            && let Some(s) = ir.schemas.get(ref_name.as_str())
343            && let IrSchemaKind::Object(obj) = &s.kind
344        {
345            for (k, v) in &obj.properties {
346                all_props.entry(k.clone()).or_insert_with(|| v.clone());
347            }
348        }
349    }
350
351    if all_props.is_empty() {
352        return emit_intersection_as_alias(schema, inter);
353    }
354
355    emit_intersection_as_dataclass(schema, &all_props)
356}
357
358fn emit_intersection_as_alias(schema: &IrSchema, inter: &IrIntersection) -> Option<FileSpec> {
359    let name = schema.name.to_pascal_case();
360    let members: Vec<TypeName> = inter.members.iter().map(python_type_name).collect();
361    let union_ty = if members.is_empty() {
362        TypeName::importable("typing", "Any")
363    } else {
364        TypeName::union(members)
365    };
366
367    let type_alias = sigil_quote!(Python {
368        type $N(name.as_str()) = $T(union_ty);
369    })
370    .ok()?;
371
372    let mut file =
373        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
374    if needs_typing_literal_in_exprs(&inter.members) {
375        file = file.add_import(ImportSpec::named("typing", "Literal"));
376    }
377    file = file.add_code(type_alias);
378    file.build().ok()
379}
380
381fn emit_intersection_as_dataclass(
382    schema: &IrSchema,
383    all_props: &indexmap::IndexMap<String, IrProperty>,
384) -> Option<FileSpec> {
385    let name = schema.name.to_pascal_case();
386
387    let mut file =
388        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
389
390    if needs_typing_literal_in_props(all_props) {
391        file = file.add_import(ImportSpec::named("typing", "Literal"));
392    }
393
394    let dataclass_tn = TypeName::importable("dataclasses", "dataclass");
395    let mut cls = TypeSpec::builder(&name, TypeKind::Class)
396        .annotate(AnnotationSpec::importable(dataclass_tn));
397
398    if let Some(doc) = &schema.description {
399        cls = cls.doc(&format!("{}.", escape_docstring(doc)));
400    }
401
402    let mut required: Vec<(&String, &IrProperty)> = Vec::new();
403    let mut optional: Vec<(&String, &IrProperty)> = Vec::new();
404    for (json_name, prop) in all_props {
405        if prop.required && !prop.nullable {
406            required.push((json_name, prop));
407        } else {
408            optional.push((json_name, prop));
409        }
410    }
411
412    if required.is_empty() && optional.is_empty() {
413        cls = cls.extra_member(CodeBlock::of("pass", ()).expect("pass"));
414    } else {
415        for (_json_name, prop) in &required {
416            let field_name = python_field_name(&prop.name);
417            let type_name = python_type_name(&prop.type_expr);
418            cls = cls.add_field(
419                FieldSpec::builder(&field_name, type_name)
420                    .build()
421                    .expect("required field"),
422            );
423        }
424        for (_json_name, prop) in &optional {
425            let field_name = python_field_name(&prop.name);
426            let type_name = python_type_name(&prop.type_expr);
427            cls = cls.add_field(
428                FieldSpec::builder(&field_name, TypeName::optional(type_name))
429                    .initializer(CodeBlock::of("None", ()).expect("None init"))
430                    .build()
431                    .expect("optional field"),
432            );
433        }
434    }
435
436    file = file.add_type(cls.build().ok()?);
437    file.build().ok()
438}
439
440// ---------------------------------------------------------------------------
441// TaggedUnion -> type X = A | B | C
442// ---------------------------------------------------------------------------
443
444fn emit_tagged_union(schema: &IrSchema, tu: &IrTaggedUnion) -> Option<FileSpec> {
445    let name = schema.name.to_pascal_case();
446
447    let members: Vec<TypeName> = tu
448        .variants
449        .iter()
450        .map(|v| python_type_name(&v.content_type))
451        .collect();
452
453    let union_ty = if members.is_empty() {
454        TypeName::importable("typing", "Any")
455    } else {
456        TypeName::union(members)
457    };
458
459    let type_alias = sigil_quote!(Python {
460        type $N(name.as_str()) = $T(union_ty);
461    })
462    .ok()?;
463
464    let hint = match &tu.tagging {
465        TaggingStyle::Internal => {
466            format!("Discriminator: {} (internal).", tu.discriminator_field)
467        }
468        TaggingStyle::Adjacent { content_field } => format!(
469            "Discriminator: {} / content: {} (adjacent).",
470            tu.discriminator_field, content_field
471        ),
472        TaggingStyle::External => "Discriminator: variant key (external).".to_string(),
473    };
474
475    let doc = match &schema.description {
476        Some(desc) => format!("{desc}\n\n{hint}"),
477        None => hint,
478    };
479
480    let mut file =
481        FileSpec::builder_with("model.py", Python::new()).header(future_annotations_header());
482    let exprs: Vec<&IrTypeExpr> = tu.variants.iter().map(|v| &v.content_type).collect();
483    if exprs.iter().any(|e| needs_typing_literal(e)) {
484        file = file.add_import(ImportSpec::named("typing", "Literal"));
485    }
486    let mut doc_block = String::new();
487    for line in doc.lines() {
488        doc_block.push_str(&format!("# {line}\n"));
489    }
490    file = file.add_raw(&doc_block);
491    file = file.add_code(type_alias);
492    file.build().ok()
493}
494
495// ---------------------------------------------------------------------------
496// Type mapping
497// ---------------------------------------------------------------------------
498
499/// Map an IR type expression to a sigil-stitch TypeName with auto-import tracking.
500pub fn python_type_name(expr: &IrTypeExpr) -> TypeName {
501    match expr {
502        IrTypeExpr::Named(name) => {
503            let py_name = name.to_pascal_case();
504            let module = format!(".{}", name.to_snake_case());
505            TypeName::importable(&module, &py_name)
506        }
507        IrTypeExpr::Primitive(p) => python_primitive_type_name(p),
508        IrTypeExpr::StringLiteral(s) => {
509            let lit = format!("Literal[\"{}\"]", escape_python_string(s));
510            TypeName::raw(&lit)
511        }
512        IrTypeExpr::StringEnum(values) => {
513            let members: Vec<String> = values
514                .iter()
515                .map(|v| format!("\"{}\"", escape_python_string(v)))
516                .collect();
517            let lit = format!("Literal[{}]", members.join(", "));
518            TypeName::raw(&lit)
519        }
520        IrTypeExpr::Array(inner) => {
521            TypeName::generic(TypeName::primitive("list"), vec![python_type_name(inner)])
522        }
523        IrTypeExpr::Map(inner) => TypeName::generic(
524            TypeName::primitive("dict"),
525            vec![TypeName::primitive("str"), python_type_name(inner)],
526        ),
527        IrTypeExpr::Union(members) => {
528            if members.is_empty() {
529                TypeName::importable("typing", "Any")
530            } else {
531                TypeName::union(members.iter().map(python_type_name).collect())
532            }
533        }
534        IrTypeExpr::Nullable(inner) => TypeName::optional(python_type_name(inner)),
535        IrTypeExpr::Any => TypeName::importable("typing", "Any"),
536    }
537}
538
539/// Like `python_type_name` but Named types import from `..models.{snake}` (for API files).
540pub fn api_type_name(expr: &IrTypeExpr) -> TypeName {
541    match expr {
542        IrTypeExpr::Named(name) => {
543            let py_name = name.to_pascal_case();
544            let module = format!("..models.{}", name.to_snake_case());
545            TypeName::importable(&module, &py_name)
546        }
547        IrTypeExpr::Array(inner) => {
548            TypeName::generic(TypeName::primitive("list"), vec![api_type_name(inner)])
549        }
550        IrTypeExpr::Map(inner) => TypeName::generic(
551            TypeName::primitive("dict"),
552            vec![TypeName::primitive("str"), api_type_name(inner)],
553        ),
554        IrTypeExpr::Union(members) => {
555            if members.is_empty() {
556                TypeName::importable("typing", "Any")
557            } else {
558                TypeName::union(members.iter().map(api_type_name).collect())
559            }
560        }
561        IrTypeExpr::Nullable(inner) => TypeName::optional(api_type_name(inner)),
562        _ => python_type_name(expr),
563    }
564}
565
566fn python_primitive_type_name(p: &IrPrimitive) -> TypeName {
567    match p {
568        IrPrimitive::String | IrPrimitive::StringWithFormat(_) => TypeName::primitive("str"),
569        IrPrimitive::Integer | IrPrimitive::IntegerWithFormat(_) => TypeName::primitive("int"),
570        IrPrimitive::Number | IrPrimitive::NumberWithFormat(_) => TypeName::primitive("float"),
571        IrPrimitive::Boolean => TypeName::primitive("bool"),
572        IrPrimitive::Binary => TypeName::primitive("bytes"),
573        IrPrimitive::Date => TypeName::importable("datetime", "date"),
574        IrPrimitive::DateTime => TypeName::importable("datetime", "datetime"),
575        IrPrimitive::Uuid => TypeName::importable("uuid", "UUID"),
576    }
577}
578
579/// Map an IR type expression to a Python type string (for serialization helpers).
580pub fn python_type_str(expr: &IrTypeExpr) -> String {
581    match expr {
582        IrTypeExpr::Named(name) => name.to_pascal_case(),
583        IrTypeExpr::Primitive(p) => python_primitive(p).to_string(),
584        IrTypeExpr::StringLiteral(s) => {
585            format!("Literal[\"{}\"]", escape_python_string(s))
586        }
587        IrTypeExpr::StringEnum(values) => {
588            let members: Vec<String> = values
589                .iter()
590                .map(|v| format!("\"{}\"", escape_python_string(v)))
591                .collect();
592            format!("Literal[{}]", members.join(", "))
593        }
594        IrTypeExpr::Array(inner) => {
595            let inner_ty = python_type_str(inner);
596            format!("list[{inner_ty}]")
597        }
598        IrTypeExpr::Map(inner) => {
599            let inner_ty = python_type_str(inner);
600            format!("dict[str, {inner_ty}]")
601        }
602        IrTypeExpr::Union(members) => {
603            let parts: Vec<String> = members.iter().map(python_type_str).collect();
604            if parts.is_empty() {
605                "Any".to_string()
606            } else {
607                parts.join(" | ")
608            }
609        }
610        IrTypeExpr::Nullable(inner) => {
611            let inner_ty = python_type_str(inner);
612            format!("{inner_ty} | None")
613        }
614        IrTypeExpr::Any => "Any".to_string(),
615    }
616}
617
618fn python_primitive(p: &IrPrimitive) -> &'static str {
619    match p {
620        IrPrimitive::String | IrPrimitive::StringWithFormat(_) => "str",
621        IrPrimitive::Integer | IrPrimitive::IntegerWithFormat(_) => "int",
622        IrPrimitive::Number | IrPrimitive::NumberWithFormat(_) => "float",
623        IrPrimitive::Boolean => "bool",
624        IrPrimitive::Binary => "bytes",
625        IrPrimitive::Date => "datetime.date",
626        IrPrimitive::DateTime => "datetime.datetime",
627        IrPrimitive::Uuid => "uuid.UUID",
628    }
629}
630
631fn needs_typing_literal(expr: &IrTypeExpr) -> bool {
632    match expr {
633        IrTypeExpr::StringLiteral(_) | IrTypeExpr::StringEnum(_) => true,
634        IrTypeExpr::Array(inner) | IrTypeExpr::Map(inner) | IrTypeExpr::Nullable(inner) => {
635            needs_typing_literal(inner)
636        }
637        IrTypeExpr::Union(members) => members.iter().any(needs_typing_literal),
638        _ => false,
639    }
640}
641
642fn needs_typing_literal_in_props(props: &indexmap::IndexMap<String, IrProperty>) -> bool {
643    props.values().any(|p| needs_typing_literal(&p.type_expr))
644}
645
646fn needs_typing_literal_in_exprs(exprs: &[IrTypeExpr]) -> bool {
647    exprs.iter().any(needs_typing_literal)
648}
649
650// ---------------------------------------------------------------------------
651// Serialization helpers
652// ---------------------------------------------------------------------------
653
654fn render_to_dict_expr(
655    value_expr: &str,
656    json_name: &str,
657    ir: &IrSpec,
658    properties: &indexmap::IndexMap<String, IrProperty>,
659) -> String {
660    let prop = properties.get(json_name);
661    let type_expr = prop.map(|p| &p.type_expr);
662    match type_expr {
663        Some(IrTypeExpr::Named(ref_name)) => {
664            if is_object_schema(ref_name, ir) {
665                format!("{value_expr}.to_dict()")
666            } else {
667                value_expr.to_string()
668            }
669        }
670        Some(IrTypeExpr::Array(inner)) => {
671            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
672                && is_object_schema(ref_name, ir)
673            {
674                return format!("[item.to_dict() for item in {value_expr}]");
675            }
676            value_expr.to_string()
677        }
678        Some(IrTypeExpr::Nullable(inner)) => {
679            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
680                && is_object_schema(ref_name, ir)
681            {
682                return format!("{value_expr}.to_dict() if {value_expr} is not None else None");
683            }
684            value_expr.to_string()
685        }
686        _ => value_expr.to_string(),
687    }
688}
689
690fn render_from_dict_expr(
691    json_name: &str,
692    ir: &IrSpec,
693    properties: &indexmap::IndexMap<String, IrProperty>,
694) -> String {
695    let prop = properties.get(json_name);
696    let type_expr = prop.map(|p| &p.type_expr);
697    let accessor = format!("data[\"{json_name}\"]");
698    match type_expr {
699        Some(IrTypeExpr::Named(ref_name)) => {
700            if is_object_schema(ref_name, ir) {
701                let py_name = ref_name.to_pascal_case();
702                format!("{py_name}.from_dict({accessor})  # type: ignore[arg-type]")
703            } else {
704                format!("{accessor}  # type: ignore[assignment]")
705            }
706        }
707        Some(IrTypeExpr::Array(inner)) => {
708            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
709                && is_object_schema(ref_name, ir)
710            {
711                let py_name = ref_name.to_pascal_case();
712                return format!(
713                    "[{py_name}.from_dict(item) for item in {accessor}]  # type: ignore[union-attr]"
714                );
715            }
716            format!("{accessor}  # type: ignore[assignment]")
717        }
718        _ => format!("{accessor}  # type: ignore[assignment]"),
719    }
720}
721
722fn render_from_dict_optional_expr(
723    json_name: &str,
724    ir: &IrSpec,
725    properties: &indexmap::IndexMap<String, IrProperty>,
726) -> String {
727    let prop = properties.get(json_name);
728    let type_expr = prop.map(|p| &p.type_expr);
729    let raw_type = type_expr.map(|t| match t {
730        IrTypeExpr::Nullable(inner) => inner.as_ref(),
731        _ => t,
732    });
733    let accessor = format!("data.get(\"{json_name}\")");
734    match raw_type {
735        Some(IrTypeExpr::Named(ref_name)) => {
736            if is_object_schema(ref_name, ir) {
737                let py_name = ref_name.to_pascal_case();
738                format!(
739                    "{py_name}.from_dict({accessor}) if {accessor} is not None else None  # type: ignore[arg-type]"
740                )
741            } else {
742                format!("{accessor}  # type: ignore[assignment]")
743            }
744        }
745        Some(IrTypeExpr::Array(inner)) => {
746            if let IrTypeExpr::Named(ref_name) = inner.as_ref()
747                && is_object_schema(ref_name, ir)
748            {
749                let py_name = ref_name.to_pascal_case();
750                return format!(
751                    "[{py_name}.from_dict(item) for item in {accessor}] if {accessor} is not None else None  # type: ignore[union-attr]"
752                );
753            }
754            format!("{accessor}  # type: ignore[assignment]")
755        }
756        _ => format!("{accessor}  # type: ignore[assignment]"),
757    }
758}
759
760pub fn is_object_schema(name: &str, ir: &IrSpec) -> bool {
761    ir.schemas
762        .get(name)
763        .is_some_and(|s| matches!(s.kind, IrSchemaKind::Object(_)))
764}
765
766// ---------------------------------------------------------------------------
767// Helpers
768// ---------------------------------------------------------------------------
769
770pub fn python_field_name(name: &str) -> String {
771    let snake = name.to_snake_case();
772    if snake.is_empty() {
773        return "field_".to_string();
774    }
775    match snake.as_str() {
776        "and" | "as" | "assert" | "async" | "await" | "break" | "class" | "continue" | "def"
777        | "del" | "elif" | "else" | "except" | "finally" | "for" | "from" | "global" | "if"
778        | "import" | "in" | "is" | "lambda" | "nonlocal" | "not" | "or" | "pass" | "raise"
779        | "return" | "try" | "while" | "with" | "yield" | "type" => {
780            format!("{snake}_")
781        }
782        _ => snake,
783    }
784}
785
786fn python_enum_member_name(value: &str) -> String {
787    let upper = value
788        .to_uppercase()
789        .replace(|c: char| !c.is_alphanumeric(), "_");
790    if upper.is_empty() {
791        return "EMPTY".to_string();
792    }
793    if upper.starts_with(|c: char| c.is_ascii_digit()) {
794        return format!("N{upper}");
795    }
796    upper
797}
798
799fn escape_python_string(s: &str) -> String {
800    s.replace('\\', "\\\\").replace('"', "\\\"")
801}
802
803fn escape_docstring(s: &str) -> String {
804    s.replace("\"\"\"", "\\\"\\\"\\\"")
805        .lines()
806        .next()
807        .unwrap_or("")
808        .to_string()
809}