cimoxide-gen 0.3.2

Code generator turning ENTSO-E CGMES RDF/SHACL schemas into typed Rust structs and SHACL validators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write as FmtWrite;
use std::fs;
use std::path::Path;

use crate::schema::model::*;

pub fn generate_rust(
    spec: &mut CimSpecification,
    output_dir: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    fs::create_dir_all(output_dir)?;

    set_lang_types(spec);
    let spec: &CimSpecification = &*spec;

    let mut module_ids: Vec<String> = Vec::new();

    // Structs
    for (id, t) in &spec.types {
        let mut code = render_struct(t);
        code.push_str(&render_from_block(spec, t));
        let file = output_dir.join(format!("{id}.rs"));
        fs::write(&file, code)?;
        module_ids.push(id.clone());
    }

    // Enums
    for (id, e) in &spec.enums {
        if e.values.is_empty() {
            continue;
        }
        let code = render_enum(e);
        let file = output_dir.join(format!("{id}.rs"));
        fs::write(&file, code)?;
        module_ids.push(id.clone());
    }

    // Type aliases (only non-Compound CIMDatatypes with a resolved primitive type)
    for (id, dt) in &spec.cim_datatypes {
        if dt.cim_stereotype == "Compound" || dt.lang_type.is_empty() {
            continue;
        }
        let code = render_type_alias(dt);
        let file = output_dir.join(format!("{id}.rs"));
        fs::write(&file, code)?;
        module_ids.push(id.clone());
    }

    // constants.rs
    fs::write(output_dir.join("constants.rs"), render_constants(spec))?;

    // registry.rs — type-name → from_block dispatch table
    fs::write(output_dir.join("registry.rs"), render_registry(spec))?;

    // profile_meta.rs — static profile membership tables
    fs::write(output_dir.join("profile_meta.rs"), render_profile_meta(spec))?;

    // lib.rs / mod.rs
    module_ids.sort();
    fs::write(output_dir.join("lib.rs"), render_lib(&module_ids))?;

    Ok(())
}

// --- type mapping -----------------------------------------------------------

fn map_lang_type(data_type: &str) -> &'static str {
    match data_type {
        DATA_TYPE_STRING | DATA_TYPE_DATE | DATA_TYPE_DATE_TIME | DATA_TYPE_MONTH_DAY | "URI" => {
            "String"
        }
        DATA_TYPE_BOOLEAN => "bool",
        DATA_TYPE_INTEGER => "i64",
        DATA_TYPE_FLOAT | DATA_TYPE_DECIMAL => "f64",
        _ => "String",
    }
}

fn set_lang_types(spec: &mut CimSpecification) {
    for dt in spec.cim_datatypes.values_mut() {
        dt.lang_type = map_lang_type(&dt.primitive_type).to_string();
    }
    for p in spec.primitive_types.values_mut() {
        p.lang_type = map_lang_type(&p.data_type).to_string();
    }
    for t in spec.types.values_mut() {
        for attr in &mut t.attributes {
            let base = map_lang_type(&attr.data_type);
            attr.lang_type = if attr.is_list && (attr.is_primitive || attr.is_cim_datatype) {
                format!("Vec<{base}>")
            } else {
                base.to_string()
            };
        }
    }
}

// --- renderers --------------------------------------------------------------

fn render_struct(t: &CimType) -> String {
    let mut s = String::new();
    if !t.comment.is_empty() {
        writeln!(s, "/// {}", t.comment).unwrap();
    }
    writeln!(s, "#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]").unwrap();
    writeln!(s, "pub struct {} {{", t.id).unwrap();

    if t.super_type.is_empty() {
        writeln!(s, "    pub id: String,").unwrap();
    } else {
        writeln!(s, "    #[serde(flatten)]").unwrap();
        writeln!(s, "    pub base: super::{},", t.super_type).unwrap();
    }

    for attr in t.attributes.iter().filter(|a| a.is_association_used) {
        if !attr.comment.is_empty() {
            writeln!(s, "    /// {}", attr.comment).unwrap();
        }
        let fname = sanitize_field(to_snake_case(&attr.label));
        let ftype = field_type(attr);
        if ftype.starts_with("Option<") {
            writeln!(s, "    #[serde(skip_serializing_if = \"Option::is_none\")]").unwrap();
        }
        writeln!(s, "    pub {fname}: {ftype},").unwrap();
    }

    writeln!(s, "}}").unwrap();
    s
}

fn field_type(attr: &CimAttribute) -> String {
    if attr.is_primitive || attr.is_cim_datatype {
        if !attr.is_list {
            match attr.lang_type.as_str() {
                "f64" => return "Option<f64>".to_string(),
                "i64" => return "Option<i64>".to_string(),
                "bool" => return "Option<bool>".to_string(),
                _ => {}
            }
        }
        attr.lang_type.clone()
    } else if attr.is_enum_value {
        format!("Option<super::base::UriRef>")
    } else if attr.is_list {
        "Vec<super::base::MridRef>".to_string()
    } else {
        "Option<super::base::MridRef>".to_string()
    }
}

fn render_enum(e: &CimEnum) -> String {
    let mut s = String::new();
    if !e.comment.is_empty() {
        writeln!(s, "/// {}", e.comment).unwrap();
    }
    writeln!(s, "#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]").unwrap();
    writeln!(s, "pub enum {} {{", e.id).unwrap();
    for v in &e.values {
        if !v.comment.is_empty() {
            writeln!(s, "    /// {}", v.comment).unwrap();
        }
        writeln!(s, "    {},", sanitize_variant(&v.label)).unwrap();
    }
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "impl {} {{", e.id).unwrap();
    writeln!(s, "    pub fn uri(&self) -> &'static str {{").unwrap();
    writeln!(s, "        match self {{").unwrap();
    let ns = if e.namespace.is_empty() {
        "http://iec.ch/TC57/CIM100".to_string()
    } else {
        e.namespace.trim_end_matches('#').to_string()
    };
    for v in &e.values {
        writeln!(
            s,
            "            {}::{} => \"{}#{}\",",
            e.id,
            sanitize_variant(&v.label),
            ns,
            v.id
        )
        .unwrap();
    }
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "}}").unwrap();
    s
}

fn render_type_alias(dt: &CimDatatype) -> String {
    let mut s = String::new();
    if !dt.comment.is_empty() {
        writeln!(s, "/// {}", dt.comment).unwrap();
    }
    writeln!(s, "pub type {} = {};", dt.id, dt.lang_type).unwrap();
    s
}

fn render_constants(spec: &CimSpecification) -> String {
    let mut s = String::new();
    writeln!(s, "pub const CIM_VERSION: &str = \"{}\";", spec.cgmes_version).unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "pub static CIM_NAMESPACES: &[(&str, &str)] = &["
    )
    .unwrap();
    let mut pairs: Vec<(&String, &String)> = spec.profile_namespaces.iter().collect();
    pairs.sort_by_key(|(k, _)| k.as_str());
    for (k, v) in pairs {
        writeln!(s, "    (\"{k}\", \"{v}\"),").unwrap();
    }
    writeln!(s, "];").unwrap();
    s
}

fn render_profile_meta(spec: &CimSpecification) -> String {
    let mut s = String::new();
    writeln!(s, "// Generated by cimgen — do not edit by hand.").unwrap();
    writeln!(s).unwrap();

    // TYPE_ORIGINS: sorted by type name
    writeln!(
        s,
        "/// `(type_name, origins)` — `origins[0]` is the primary (dominant) profile."
    )
    .unwrap();
    writeln!(
        s,
        "pub static TYPE_ORIGINS: &[(&str, &[&str])] = &["
    )
    .unwrap();
    let mut type_ids: Vec<&String> = spec.types.keys().collect();
    type_ids.sort();
    for id in type_ids {
        let t = &spec.types[id];
        if t.origins.is_empty() {
            continue;
        }
        let origins: Vec<String> = t.origins.iter().map(|o| format!("\"{o}\"")).collect();
        writeln!(s, "    (\"{id}\", &[{}]),", origins.join(", ")).unwrap();
    }
    writeln!(s, "];").unwrap();
    writeln!(s).unwrap();

    // ATTR_ORIGINS: collect all (attr_id → origins) from all types, dedup via BTreeMap
    // Same attr_id can appear in multiple type attribute lists (inherited attrs) — merge origins.
    let mut attr_map: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut type_ids2: Vec<&String> = spec.types.keys().collect();
    type_ids2.sort();
    for id in type_ids2 {
        let t = &spec.types[id];
        for attr in t.attributes.iter().filter(|a| a.is_association_used) {
            if attr.origins.is_empty() {
                continue;
            }
            let entry = attr_map.entry(attr.id.clone()).or_default();
            for o in &attr.origins {
                if !entry.contains(o) {
                    entry.push(o.clone());
                }
            }
        }
    }
    writeln!(
        s,
        "/// `(attr_id, origins)` — `origins[0]` is the primary (dominant) profile."
    )
    .unwrap();
    writeln!(
        s,
        "/// `attr_id` matches the field key in `RdfBlock.fields`."
    )
    .unwrap();
    writeln!(
        s,
        "pub static ATTR_ORIGINS: &[(&str, &[&str])] = &["
    )
    .unwrap();
    for (attr_id, mut origins) in attr_map {
        // Sort origins consistently: EQ first (priority 1), rest alphabetically
        origins.sort_by(|a, b| {
            let pa = if a == "EQ" { 0u32 } else { 1 };
            let pb = if b == "EQ" { 0u32 } else { 1 };
            pa.cmp(&pb).then(a.cmp(b))
        });
        let quoted: Vec<String> = origins.iter().map(|o| format!("\"{o}\"")).collect();
        writeln!(s, "    (\"{attr_id}\", &[{}]),", quoted.join(", ")).unwrap();
    }
    writeln!(s, "];").unwrap();
    writeln!(s).unwrap();

    // PROFILE_URIS: (keyword, owl_version_iri) for each known profile ontology
    writeln!(
        s,
        "/// `(profile_code, profile_uri)` — versioned URI for `md:Model.profile`."
    )
    .unwrap();
    writeln!(
        s,
        "pub static PROFILE_URIS: &[(&str, &str)] = &["
    )
    .unwrap();
    let mut ontologies: Vec<(&String, &CimOntology)> = spec.ontologies.iter().collect();
    ontologies.sort_by_key(|(k, _)| k.as_str());
    for (keyword, ont) in ontologies {
        if ont.owl_version_iri.is_empty() {
            continue;
        }
        writeln!(s, "    (\"{keyword}\", \"{}\"),", ont.owl_version_iri).unwrap();
    }
    writeln!(s, "];").unwrap();
    writeln!(s).unwrap();

    // TYPE_NS: RDF namespace IRI per CIM class. The decoder drops the XML prefix
    // (`local_name()`), so this is the only way back to a class IRI at runtime.
    writeln!(
        s,
        "/// `(type_name, namespace)` — RDF namespace IRI of each CIM class, trailing `#` included."
    )
    .unwrap();
    writeln!(s, "pub static TYPE_NS: &[(&str, &str)] = &[").unwrap();
    let mut ns_type_ids: Vec<&String> = spec.types.keys().collect();
    ns_type_ids.sort();
    for id in ns_type_ids {
        let t = &spec.types[id];
        if t.namespace.is_empty() {
            continue;
        }
        writeln!(s, "    (\"{id}\", \"{}\"),", t.namespace).unwrap();
    }
    writeln!(s, "];").unwrap();
    writeln!(s).unwrap();

    // ATTR_RDF: (attr_id, namespace, range, kind) for every attribute of every type.
    // Deduped by attr_id like ATTR_ORIGINS above — the same id recurs across inheriting
    // types. Unlike ATTR_ORIGINS this is *not* filtered on `is_association_used`:
    // `RdfBlock.fields` can hold keys the typed struct dropped, and a predicate IRI is
    // wanted for those too.
    let mut rdf_map: BTreeMap<String, (String, String, u8)> = BTreeMap::new();
    let mut type_ids3: Vec<&String> = spec.types.keys().collect();
    type_ids3.sort();
    for id in type_ids3 {
        for attr in &spec.types[id].attributes {
            if attr.namespace.is_empty() || rdf_map.contains_key(&attr.id) {
                continue;
            }
            // Test the enum registry directly rather than trusting `is_enum_value`:
            // `eu:OperationalLimitType.kind` ranges over the `eu:LimitKind` enumeration but
            // is classified as a plain class reference upstream, so it would otherwise get an
            // MRID-shaped object IRI instead of the enum value IRI.
            let (range, kind) = if let Some(e) = spec.enums.get(&attr.rdf_range) {
                // The decoder strips the fragment off enum values, so the enum's own
                // namespace is what rebuilds `<ns>WindingConnection.D` from `WindingConnection.D`.
                (e.namespace.clone(), 2u8)
            } else if attr.is_enum_value || attr.is_primitive || attr.is_cim_datatype {
                (xsd_iri(attr), 0u8)
            } else {
                (String::new(), 1u8)
            };
            rdf_map.insert(attr.id.clone(), (attr.namespace.clone(), range, kind));
        }
    }
    writeln!(
        s,
        "/// `(attr_id, namespace, range, kind)` — `attr_id` matches the key in `RdfBlock.fields`."
    )
    .unwrap();
    writeln!(
        s,
        "/// `kind`: 0 = literal, 1 = association (IRI), 2 = enum value (IRI)."
    )
    .unwrap();
    writeln!(
        s,
        "/// `range`: for kind 0 the XSD datatype IRI, for kind 2 the enum's namespace IRI,"
    )
    .unwrap();
    writeln!(s, "/// empty for kind 1.").unwrap();
    writeln!(s, "pub static ATTR_RDF: &[(&str, &str, &str, u8)] = &[").unwrap();
    for (attr_id, (ns, range, kind)) in rdf_map {
        writeln!(s, "    (\"{attr_id}\", \"{ns}\", \"{range}\", {kind}),").unwrap();
    }
    writeln!(s, "];").unwrap();
    s
}

/// XSD datatype IRI for a literal-valued attribute, falling back on the generated Rust
/// type when the CIM datatype is unset.
///
/// CGMES `Float` maps to `xsd:double`, not `xsd:float`: the decoder parses into `f64`, and
/// claiming single precision would make `FILTER(?r > 0.1)` disagree with the value that was
/// actually decoded.
fn xsd_iri(attr: &CimAttribute) -> String {
    const XSD: &str = "http://www.w3.org/2001/XMLSchema#";
    let name = match attr.data_type.as_str() {
        DATA_TYPE_STRING => "string",
        DATA_TYPE_INTEGER => "integer",
        DATA_TYPE_BOOLEAN => "boolean",
        DATA_TYPE_FLOAT => "double",
        DATA_TYPE_DECIMAL => "decimal",
        DATA_TYPE_DATE => "date",
        DATA_TYPE_DATE_TIME => "dateTime",
        DATA_TYPE_MONTH_DAY => "gMonthDay",
        // `md:Model.profile` and friends declare `eu:URI`, and the SHACL files type their
        // values `^^xsd:anyURI`.
        "URI" => "anyURI",
        // List-valued literals carry a `Vec<..>` lang type; the element type is what matters.
        _ => match attr
            .lang_type
            .trim_start_matches("Vec<")
            .trim_end_matches('>')
        {
            "f64" => "double",
            "i64" => "integer",
            "bool" => "boolean",
            "String" => "string",
            _ => return String::new(),
        },
    };
    format!("{XSD}{name}")
}

fn render_lib(ids: &[String]) -> String {
    let mut s = String::new();
    writeln!(s, "// Generated by cimgen — do not edit by hand.").unwrap();
    writeln!(s, "#![allow(non_snake_case, non_camel_case_types, dead_code)]").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "pub mod base;").unwrap();
    writeln!(s, "pub mod constants;").unwrap();
    writeln!(s, "pub mod profile_meta;").unwrap();
    writeln!(s, "pub mod registry;").unwrap();
    writeln!(s).unwrap();

    // Collect unique IDs (struct/enum/alias files may share names in edge cases)
    let unique: Vec<&String> = {
        let mut seen = HashSet::new();
        ids.iter().filter(|id| seen.insert(id.as_str())).collect()
    };

    for id in unique {
        let mod_name = to_snake_case(id);
        writeln!(s, "#[path = \"{id}.rs\"]").unwrap();
        writeln!(s, "mod {mod_name}_mod;").unwrap();
        writeln!(s, "pub use {mod_name}_mod::*;").unwrap();
    }
    s
}

// --- name helpers -----------------------------------------------------------

pub fn to_snake_case(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len() + 4);
    for (i, &c) in chars.iter().enumerate() {
        if c.is_uppercase() {
            let prev_lower = i > 0 && chars[i - 1].is_lowercase();
            let next_lower = i + 1 < chars.len() && chars[i + 1].is_lowercase();
            let prev_upper = i > 0 && chars[i - 1].is_uppercase();
            if i > 0 && (prev_lower || (next_lower && prev_upper)) {
                out.push('_');
            }
            out.extend(c.to_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

pub fn sanitize_field(name: String) -> String {
    match name.as_str() {
        "type" | "where" | "in" | "for" | "let" | "pub" | "use" | "mod" | "match" | "if"
        | "else" | "fn" | "struct" | "enum" | "impl" | "trait" | "return" | "break"
        | "continue" | "loop" | "while" | "move" | "ref" | "mut" | "const" | "static"
        | "self" | "super" | "crate" | "extern" | "unsafe" | "async" | "await" | "dyn"
        | "box" | "true" | "false" | "abstract" | "become" | "do" | "final" | "macro"
        | "override" | "priv" | "typeof" | "unsized" | "virtual" | "yield" => {
            format!("{name}_")
        }
        _ => name,
    }
}

fn sanitize_variant(label: &str) -> String {
    if label.is_empty() {
        return "_Empty".to_string();
    }
    let first = label.chars().next().unwrap();
    if first.is_ascii_digit() {
        format!("_{label}")
    } else {
        label.to_string()
    }
}

// --- from_block code generation ---------------------------------------------

fn id_obj_path(spec: &CimSpecification, t: &CimType, obj: &str) -> String {
    let mut depth = 0usize;
    let mut current = t.super_type.clone();
    while !current.is_empty() {
        depth += 1;
        current = spec
            .types
            .get(&current)
            .map(|p| p.super_type.clone())
            .unwrap_or_default();
    }
    if depth == 0 {
        format!("{obj}.id")
    } else {
        format!("{obj}.{}id", "base.".repeat(depth))
    }
}

fn emit_attr_arm(s: &mut String, prefix: &str, attr: &CimAttribute) {
    let fname = sanitize_field(to_snake_case(&attr.label));
    writeln!(s, "                \"{}\" => {{", attr.id).unwrap();

    if attr.is_primitive || attr.is_cim_datatype {
        if attr.is_list {
            // Repeated text elements arrive as one TextList; a single element as Text.
            let push = if attr.lang_type == "Vec<String>" || attr.lang_type == "String" {
                format!("{prefix}.{fname}.push(sv.trim().to_string());")
            } else {
                format!("if let Ok(v) = sv.trim().parse() {{ {prefix}.{fname}.push(v); }}")
            };
            writeln!(s, "                    match val {{").unwrap();
            writeln!(s, "                        crate::base::FieldValue::Text(sv) => {{ {push} }}").unwrap();
            writeln!(s, "                        crate::base::FieldValue::TextList(svs) => {{").unwrap();
            writeln!(s, "                            for sv in svs {{ {push} }}").unwrap();
            writeln!(s, "                        }}").unwrap();
            writeln!(s, "                        _ => {{}}").unwrap();
            writeln!(s, "                    }}").unwrap();
        } else {
            // Scalar text field: a TextList means duplicate XML elements — keep
            // the last value (decoder overwrite semantics; the duplicate itself
            // is reported via RdfBlock.duplicate_fields).
            let assign = match attr.lang_type.as_str() {
                "String" => format!("{prefix}.{fname} = sv.clone();"),
                "bool" => format!("{prefix}.{fname} = Some(sv.trim() == \"true\");"),
                _ => format!("if let Ok(v) = sv.trim().parse() {{ {prefix}.{fname} = Some(v); }}"),
            };
            writeln!(s, "                    match val {{").unwrap();
            writeln!(s, "                        crate::base::FieldValue::Text(sv) => {{ {assign} }}").unwrap();
            writeln!(s, "                        crate::base::FieldValue::TextList(svs) => {{").unwrap();
            writeln!(s, "                            if let Some(sv) = svs.last() {{ {assign} }}").unwrap();
            writeln!(s, "                        }}").unwrap();
            writeln!(s, "                        _ => {{}}").unwrap();
            writeln!(s, "                    }}").unwrap();
        }
    } else if attr.is_enum_value {
        writeln!(s, "                    if let crate::base::FieldValue::Resource(sv) = val {{").unwrap();
        writeln!(s, "                        {prefix}.{fname} = Some(crate::base::UriRef {{ uri: sv.clone() }});").unwrap();
        writeln!(s, "                    }}").unwrap();
    } else if attr.is_list {
        writeln!(s, "                    match val {{").unwrap();
        writeln!(s, "                        crate::base::FieldValue::Resource(sv) => {prefix}.{fname}.push(crate::base::MridRef {{ mrid: sv.clone() }}),").unwrap();
        writeln!(s, "                        crate::base::FieldValue::ResourceList(svs) => {{").unwrap();
        writeln!(s, "                            for sv in svs {{ {prefix}.{fname}.push(crate::base::MridRef {{ mrid: sv.clone() }}); }}").unwrap();
        writeln!(s, "                        }}").unwrap();
        writeln!(s, "                        _ => {{}}").unwrap();
        writeln!(s, "                    }}").unwrap();
    } else {
        writeln!(s, "                    if let crate::base::FieldValue::Resource(sv) = val {{").unwrap();
        writeln!(s, "                        {prefix}.{fname} = Some(crate::base::MridRef {{ mrid: sv.clone() }});").unwrap();
        writeln!(s, "                    }}").unwrap();
    }

    writeln!(s, "                }}").unwrap();
}

fn emit_to_block_field(s: &mut String, attr: &CimAttribute) {
    let fname = sanitize_field(to_snake_case(&attr.label));
    if attr.is_primitive || attr.is_cim_datatype {
        if attr.is_list {
            // A single TextList keeps every value; per-item Text inserts would
            // overwrite each other in the fields HashMap.
            writeln!(s, "        if !self.{fname}.is_empty() {{").unwrap();
            writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::TextList(self.{fname}.iter().map(|v| v.to_string()).collect()));", attr.id).unwrap();
            writeln!(s, "        }}").unwrap();
        } else {
            match attr.lang_type.as_str() {
                "String" => {
                    writeln!(s, "        if !self.{fname}.is_empty() {{").unwrap();
                    writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::Text(self.{fname}.clone()));", attr.id).unwrap();
                    writeln!(s, "        }}").unwrap();
                }
                _ => {
                    writeln!(s, "        if let Some(v) = self.{fname} {{").unwrap();
                    writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::Text(v.to_string()));", attr.id).unwrap();
                    writeln!(s, "        }}").unwrap();
                }
            }
        }
    } else if attr.is_enum_value {
        writeln!(s, "        if let Some(ref v) = self.{fname} {{").unwrap();
        writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::Resource(v.uri.clone()));", attr.id).unwrap();
        writeln!(s, "        }}").unwrap();
    } else if attr.is_list {
        writeln!(s, "        if !self.{fname}.is_empty() {{").unwrap();
        writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::ResourceList(self.{fname}.iter().map(|r| r.mrid.clone()).collect()));", attr.id).unwrap();
        writeln!(s, "        }}").unwrap();
    } else {
        writeln!(s, "        if let Some(ref v) = self.{fname} {{").unwrap();
        writeln!(s, "            block.fields.insert(\"{}\".into(), crate::base::FieldValue::Resource(v.mrid.clone()));", attr.id).unwrap();
        writeln!(s, "        }}").unwrap();
    }
}

fn render_from_block(spec: &CimSpecification, t: &CimType) -> String {
    let mut s = String::new();

    // CimElement trait impl
    let self_id = id_obj_path(spec, t, "self");
    writeln!(s, "impl crate::base::CimElement for {id} {{", id = t.id).unwrap();
    writeln!(s, "    fn mrid(&self) -> &str {{ &{self_id} }}").unwrap();
    writeln!(s, "    fn type_name(&self) -> &'static str {{ \"{}\" }}", t.id).unwrap();
    writeln!(s, "    fn as_any(&self) -> &dyn std::any::Any {{ self }}").unwrap();
    writeln!(s, "    fn to_json_value(&self) -> serde_json::Value {{").unwrap();
    writeln!(s, "        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    fn to_block(&self) -> crate::base::RdfBlock {{").unwrap();
    let has_own = t.attributes.iter().any(|a| a.is_association_used);
    // root types: mut only if fields to insert; inherited types: always mut (type_name update)
    let needs_mut = has_own || !t.super_type.is_empty();
    let mut_kw = if needs_mut { "mut " } else { "" };
    if t.super_type.is_empty() {
        writeln!(s, "        let {mut_kw}block = crate::base::RdfBlock {{").unwrap();
        writeln!(s, "            type_name: \"{}\".to_string(),", t.id).unwrap();
        writeln!(s, "            mrid: self.id.clone(),").unwrap();
        writeln!(s, "            fields: std::collections::HashMap::new(),").unwrap();
        writeln!(s, "            duplicate_fields: std::collections::HashSet::new(),").unwrap();
        writeln!(s, "        }};").unwrap();
    } else {
        writeln!(s, "        let {mut_kw}block = self.base.to_block();").unwrap();
        writeln!(s, "        block.type_name = \"{}\".to_string();", t.id).unwrap();
    }
    for attr in t.attributes.iter().filter(|a| a.is_association_used) {
        emit_to_block_field(&mut s, attr);
    }
    writeln!(s, "        block").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();

    // Collect all (field-access-prefix, attrs) layers: own first, then ancestors
    let mut layers: Vec<(String, Vec<CimAttribute>)> = Vec::new();
    layers.push(("obj".to_string(), t.attributes.clone()));
    let mut prefix = "obj.base".to_string();
    let mut current_id = t.super_type.clone();
    while let Some(ancestor) = spec.types.get(&current_id) {
        layers.push((prefix.clone(), ancestor.attributes.clone()));
        prefix = format!("{prefix}.base");
        current_id = ancestor.super_type.clone();
    }

    let has_fields = layers
        .iter()
        .any(|(_, attrs)| attrs.iter().any(|a| a.is_association_used));

    let obj_id = id_obj_path(spec, t, "obj");
    writeln!(s, "impl {id} {{", id = t.id).unwrap();
    writeln!(s, "    pub fn from_block(b: &crate::base::RdfBlock) -> Self {{").unwrap();
    writeln!(s, "        let mut obj = Self::default();").unwrap();
    writeln!(s, "        {obj_id}.clone_from(&b.mrid);").unwrap();

    if has_fields {
        writeln!(s, "        for (key, val) in &b.fields {{").unwrap();
        writeln!(s, "            match key.as_str() {{").unwrap();
        for (pfx, attrs) in &layers {
            for attr in attrs.iter().filter(|a| a.is_association_used) {
                emit_attr_arm(&mut s, pfx, attr);
            }
        }
        writeln!(s, "                _ => {{}}").unwrap();
        writeln!(s, "            }}").unwrap();
        writeln!(s, "        }}").unwrap();
    }

    writeln!(s, "        obj").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "}}").unwrap();
    s
}

fn render_registry(spec: &CimSpecification) -> String {
    let mut s = String::new();
    writeln!(s, "// Generated by cimgen — do not edit by hand.").unwrap();
    writeln!(s, "use std::collections::HashMap;").unwrap();
    writeln!(s, "use crate::base::{{CimElement, RdfBlock}};").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "pub type ParseFn = fn(&RdfBlock) -> Box<dyn CimElement>;").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "pub fn registry() -> HashMap<&'static str, ParseFn> {{").unwrap();
    writeln!(s, "    let mut m: HashMap<&'static str, ParseFn> = HashMap::new();").unwrap();

    let mut ids: Vec<&String> = spec.types.keys().collect();
    ids.sort();
    for id in &ids {
        writeln!(s, "    m.insert(\"{id}\", |b| Box::new(super::{id}::from_block(b)));").unwrap();
    }

    writeln!(s, "    m").unwrap();
    writeln!(s, "}}").unwrap();

    writeln!(s).unwrap();
    writeln!(s, "pub type JsonParseFn = fn(serde_json::Value) -> Result<Box<dyn CimElement>, serde_json::Error>;").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "pub fn json_registry() -> HashMap<&'static str, JsonParseFn> {{").unwrap();
    writeln!(s, "    let mut m: HashMap<&'static str, JsonParseFn> = HashMap::new();").unwrap();
    for id in &ids {
        writeln!(s, "    m.insert(\"{id}\", |v| Ok(Box::new(serde_json::from_value::<super::{id}>(v)?)));").unwrap();
    }
    writeln!(s, "    m").unwrap();
    writeln!(s, "}}").unwrap();
    s
}