cimoxide-gen 0.3.3

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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
use std::fmt::Write as FmtWrite;
use std::fs;
use std::path::Path;

use crate::generator::rust_gen::{sanitize_field, to_snake_case};
use crate::schema::model::{CimAttribute, CimSpecification};

use super::model::*;
use super::skip;

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

pub fn generate_validation(
    results: &[FileResults],
    spec: &CimSpecification,
    output_dir: &Path,
) -> Result<(usize, Vec<skip::FileSkipInfo>), Box<dyn std::error::Error>> {
    fs::create_dir_all(output_dir)?;

    let mut total_checks = 0usize;
    let mut generated_modules: Vec<String> = Vec::new();
    let mut file_skips: Vec<skip::FileSkipInfo> = Vec::new();

    for fr in results {
        let (code, count, skips) = render_file(fr, spec);
        let mod_name = file_to_mod_name(&fr.file_name);
        file_skips.push(skip::FileSkipInfo { file_name: fr.file_name.clone(), check_count: count, skips });
        if count == 0 {
            continue;
        }
        total_checks += count;
        let out_path = output_dir.join(format!("generated_{mod_name}.rs"));
        fs::write(&out_path, code)?;
        generated_modules.push(mod_name);
    }

    Ok((total_checks, file_skips))
}

// ---------------------------------------------------------------------------
// Per-file rendering
// ---------------------------------------------------------------------------

fn render_file(fr: &FileResults, spec: &CimSpecification) -> (String, usize, Vec<skip::SkipEntry>) {
    let file_snake = file_to_mod_name(&fr.file_name);

    let mut regex_decls: Vec<String> = Vec::new();
    let mut regex_counter = 0usize;
    let mut check_names: Vec<String> = Vec::new();
    let mut checks_body = String::new();
    let mut used_fn_names: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut collector = skip::SkipCollector::new();
    // Tracks (path, component, name) triples -- deliberately *not* including the target
    // class -- so `count` below reports one entry per distinct rule pattern regardless of
    // how many concrete classes it's generated against, matching skip::SkipCollector's
    // existing dedup key for the Skipped side (see its doc comment) and cimgo's
    // `uniqueCheckPatterns`. `check_names`/`checks_body` above are unaffected by this: every
    // class still gets its own generated function and orchestrator call, since Rust's static
    // typing requires one function per concrete class.
    let mut unique_patterns: std::collections::HashSet<(String, String, String)> = std::collections::HashSet::new();

    for node_shape in &fr.shapes {
        for target in &node_shape.targets {
            if target.kind != "targetClass" && target.kind != "targetNode" {
                // targetSubjectsOf/targetObjectsOf/sparqlTarget carry no concrete class
                // to generate per-class checks against (see model.rs's TargetInfo::kind
                // doc). Record why instead of silently generating nothing.
                push_unsupported_target_skips(node_shape, &target.kind, &mut collector);
                continue;
            }
            let class_name = local_name(&target.value);
            if spec.types.get(&class_name).is_none() {
                continue; // class not in schema (e.g. md:FullModel)
            }

            // Compound node-level constraints (sh:xone, sh:or, sh:and)
            for node_constraint in &node_shape.constraints {
                match gen_compound_check(&file_snake, &class_name, spec, node_constraint) {
                    Ok(fn_code) => {
                        let raw_name = extract_fn_name(&fn_code);
                        let fn_name = dedup_fn_name(raw_name.clone(), &used_fn_names);
                        let patched = if fn_name != raw_name {
                            fn_code.replacen(&format!("pub fn {raw_name}("), &format!("pub fn {fn_name}("), 1)
                        } else { fn_code };
                        used_fn_names.insert(fn_name.clone());
                        check_names.push(fn_name);
                        checks_body.push_str(&patched);
                        checks_body.push('\n');
                        unique_patterns.insert((String::new(), node_constraint.component.clone(), node_constraint.name.clone()));
                    }
                    Err(reason) => {
                        collector.push(&class_name, "", &node_constraint.component, &node_constraint.name, &reason);
                    }
                }
            }

            for prop_shape in &node_shape.properties {
                if prop_shape.path.is_empty() {
                    continue;
                }
                for constraint in &prop_shape.constraints {
                    let (opt_code, opt_regex) = render_check(
                        &file_snake,
                        &class_name,
                        spec,
                        &prop_shape.path,
                        constraint,
                        &mut regex_counter,
                        &mut collector,
                    );
                    if let Some(fn_code) = opt_code {
                        if let Some(decl) = opt_regex {
                            regex_decls.push(decl);
                        }
                        let raw_name = extract_fn_name(&fn_code);
                        let fn_name = dedup_fn_name(raw_name.clone(), &used_fn_names);
                        let patched = if fn_name != raw_name {
                            fn_code.replacen(&format!("pub fn {raw_name}("), &format!("pub fn {fn_name}("), 1)
                        } else { fn_code };
                        used_fn_names.insert(fn_name.clone());
                        check_names.push(fn_name);
                        checks_body.push_str(&patched);
                        checks_body.push('\n');
                        unique_patterns.insert((constraint.path.join("/"), constraint.component.clone(), constraint.name.clone()));
                    }
                }
            }
        }
    }

    let count = unique_patterns.len();
    if check_names.is_empty() {
        return (String::new(), 0, collector.into_entries());
    }

    let mut s = String::new();
    writeln!(s, "// Generated by cimgen — do not edit by hand.").unwrap();
    writeln!(s, "#![allow(clippy::all, dead_code, unused)]").unwrap();
    writeln!(s, "use cimdecoder::CimDataset;").unwrap();
    writeln!(s, "use crate::Violation;").unwrap();
    writeln!(s, "use crate::helpers::*;").unwrap();
    writeln!(s).unwrap();

    if !regex_decls.is_empty() {
        writeln!(s, "use std::sync::LazyLock;").unwrap();
        for decl in &regex_decls {
            s.push_str(decl);
            s.push('\n');
        }
        writeln!(s).unwrap();
    }

    let orchestrator = format!("validate_{file_snake}");
    writeln!(s, "pub fn {orchestrator}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut v = Vec::new();").unwrap();
    for name in &check_names {
        writeln!(s, "    v.extend({name}(dataset));").unwrap();
    }
    writeln!(s, "    v").unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();

    s.push_str(&checks_body);

    (s, count, collector.into_entries())
}

/// Records why every constraint under `node_shape` isn't code-generated when the shape's
/// target is a kind with no resolvable concrete class (targetSubjectsOf/targetObjectsOf/
/// sparqlTarget) -- otherwise these would resolve to zero checks with no skip entry at
/// all, an invisible gap one level down from the shape being dropped entirely at parse
/// time (which ttl_import.rs no longer does).
fn push_unsupported_target_skips(node_shape: &ShapeInfo, kind: &str, collector: &mut skip::SkipCollector) {
    let label = format!("({kind})");
    let reason = match kind {
        "targetSubjectsOf" | "targetObjectsOf" => {
            "sh:targetSubjectsOf/targetObjectsOf target: property-based target, no concrete class to generate checks against".to_string()
        }
        _ => "sh:target SPARQLTarget: needs a hand-written implementation, not a SPARQL evaluator".to_string(),
    };
    for node_constraint in &node_shape.constraints {
        collector.push(&label, "", &node_constraint.component, &node_constraint.name, &reason);
    }
    for prop_shape in &node_shape.properties {
        let full_path_key = prop_shape.path.join("/");
        for constraint in &prop_shape.constraints {
            collector.push(&label, &full_path_key, &constraint.component, &constraint.name, &reason);
        }
    }
}

// ---------------------------------------------------------------------------
// Per-constraint rendering
// ---------------------------------------------------------------------------

fn render_check(
    file_snake: &str,
    class_name: &str,
    spec: &CimSpecification,
    full_path: &[String],
    constraint: &ConstraintInfo,
    regex_counter: &mut usize,
    collector: &mut skip::SkipCollector,
) -> (Option<String>, Option<String>) {
    let path_seg = full_path[0].as_str();
    let attr_id = local_name(path_seg);
    let is_multi_seg = full_path.len() > 1;
    // Full path, for skip-entry dedup only -- unlike path_seg (used for fn naming
    // and multi-segment routing), this must distinguish constraints that share a
    // sh:name and first path segment but diverge deeper in the path (e.g. two
    // property shapes both named "...:containment", one checking
    // Equipment.EquipmentContainer, the other Equipment.EquipmentContainer's own
    // DCConverterUnit.Substation) -- otherwise they'd wrongly collapse into one
    // skip entry, undercounting relative to the Generated-side dedup below (which
    // already keys on the full constraint.path) and cimgo's equivalent PathKey.
    let full_path_key = full_path.join("/");

    let comp = constraint.component.as_str();

    // Compute fn_name early so all branches can use it.
    let attr_part = to_snake_case(&attr_id.replace('.', "_"));
    let comp_suffix = component_suffix(comp);
    let raw_name = format!(
        "check_{file_snake}_{class_snake}_{attr_part}_{comp_suffix}",
        class_snake = to_snake_case(class_name),
    );
    let fn_name = safe_fn_name(&raw_name);

    // Multi-segment paths: chains of 0..1 reference hops, resolved against the
    // dataset one link at a time (mirroring cimgo's chain-walker semantics: any
    // missing/unresolvable link means the path yields no value and the object is
    // skipped, except sh:Required which collapses onto the first link's presence).
    if is_multi_seg {
        let is_inverse_head = path_seg.starts_with('^');
        let ends_rdf_type = full_path.last().map(|s| s == "rdf:type").unwrap_or(false);

        // [field, rdf:type] sh:In / sh:HasValue — single-hop reference type check.
        if full_path.len() == 2 && ends_rdf_type && !is_inverse_head
            && matches!(comp, "sh:InConstraintComponent" | "sh:HasValueConstraintComponent")
        {
            return match gen_slice_mrid_rdf_type_check(&fn_name, class_name, spec, &attr_id, constraint) {
                Ok((code, regex)) => (Some(code), regex),
                Err(reason) => {
                    collector.push(class_name, &full_path_key, comp, &constraint.name, &reason);
                    (None, None)
                }
            };
        }

        // Difference-model header paths into rdf:Statement members: subject/
        // predicate/object are mandated by the RDF specification for every
        // rdf:Statement, and rdf:Statement resources are not decoded into the
        // dataset — the constraint can neither fire nor be violated.
        if full_path.iter().any(|s| s.starts_with("rdf:Statements.")) {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "multi-segment path into rdf:Statement members: guaranteed by the RDF specification, rdf:Statement resources are not decoded");
            return (None, None);
        }

        // Every hop in a forward CIM reference chain is a 0..1 field, so the
        // value count can never exceed 1 — sh:maxCount 1 is structurally satisfied.
        if comp == "sh:MaxCountConstraintComponent" {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "multi-segment MaxCount=1 structurally satisfied: every hop is a 0..1 field");
            return (None, None);
        }
        // The decoded Rust type fixes the value kind of every path step.
        if comp == "sh:NodeKindConstraintComponent" {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "multi-segment NodeKind structurally satisfied: value kind is fixed by the decoded Rust type");
            return (None, None);
        }

        let result = if !is_inverse_head {
            match comp {
                // sh:Required over a chain ending in rdf:type collapses onto the
                // first link's presence (cimgo parity): later links that don't
                // resolve are indistinguishable from data split across files.
                "sh:RequiredConstraintComponent" | "sh:MinCountConstraintComponent" if ends_rdf_type => {
                    Some(gen_chain_required_first_link(&fn_name, class_name, spec, &attr_id, constraint))
                }
                // sh:HasValue with an rdf:type tail: walk the chain, the final
                // entry's class must be the hasValue class (or a subclass).
                "sh:HasValueConstraintComponent" if ends_rdf_type => {
                    let allowed = match constraint.payload.get("hasValue").and_then(|v| v.as_str()) {
                        Some(v) => class_and_subclasses(spec, &local_name(v)),
                        None => Vec::new(),
                    };
                    if allowed.is_empty() {
                        Some(Err("chain sh:HasValue: value class not decodable".to_string()))
                    } else {
                        Some(gen_forward_chain_type_check(&fn_name, class_name, spec,
                            &full_path[..full_path.len() - 1], &allowed, constraint))
                    }
                }
                // sh:or of sh:class alternatives on an association tail: walk the
                // chain, the final referenced entry's class must be in the allow-list.
                "sh:OrClassConstraintComponent" if !ends_rdf_type => {
                    let raw: Vec<String> = constraint.payload.get("classes").and_then(|v| v.as_list())
                        .map(|v| v.iter().map(|s| local_name(s)).collect())
                        .unwrap_or_default();
                    let mut set = std::collections::BTreeSet::new();
                    for cls in &raw {
                        for t in class_and_subclasses(spec, cls) { set.insert(t); }
                    }
                    let allowed: Vec<String> = set.into_iter().collect();
                    if allowed.is_empty() || allowed.len() >= spec.types.len() {
                        Some(Err("chain sh:OrClass: empty or vacuous class list".to_string()))
                    } else {
                        Some(gen_forward_chain_type_check(&fn_name, class_name, spec,
                            full_path, &allowed, constraint))
                    }
                }
                // sh:datatype on a primitive leaf at the end of a chain.
                "sh:DatatypeConstraintComponent" if !ends_rdf_type => {
                    Some(gen_forward_chain_datatype_check(&fn_name, class_name, spec, full_path, constraint))
                }
                _ => None,
            }
        } else if full_path.len() == 2 && comp == "sh:HasValueConstraintComponent" {
            // [^forward-ref, attr] sh:HasValue: at least one referrer must carry
            // the expected attribute value.
            Some(gen_inverse_chain_has_value(&fn_name, class_name, spec, path_seg, &full_path[1], constraint))
        } else {
            None
        };

        return match result {
            Some(Ok((code, regex))) => (Some(code), regex),
            Some(Err(reason)) => {
                collector.push(class_name, &full_path_key, comp, &constraint.name, &reason);
                (None, None)
            }
            None => {
                collector.push(class_name, &full_path_key, comp, &constraint.name, "multi-segment path not supported");
                (None, None)
            }
        };
    }

    // Inverse path (encoded as "^<forward-iri>" by the parser) — route to dedicated generator
    // before the component skip list so MaxCount is not dropped for inverse shapes.
    if path_seg.starts_with('^') {
        let forward_pred = &path_seg[1..]; // strip "^"
        return match gen_inverse_count(&fn_name, class_name, forward_pred, spec, constraint) {
            Ok((code, regex)) => (Some(code), regex),
            Err(reason) => {
                collector.push(class_name, &full_path_key, comp, &constraint.name, &reason);
                (None, None)
            }
        };
    }

    match comp {
        "sh:NodeKindConstraintComponent" => {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "sh:NodeKindConstraintComponent structurally satisfied by Rust type system");
            return (None, None);
        }
        "sh:SPARQLConstraintComponent" => {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "sh:SPARQLConstraintComponent: needs a hand-written implementation, not a SPARQL evaluator");
            return (None, None);
        }
        "sh:OrInversePathConstraintComponent" => {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                "sh:OrInversePathConstraintComponent structurally satisfied");
            return (None, None);
        }
        _ => {}
    }

    let (accessor_prefix, attr) = match find_attr_in_hierarchy(spec, class_name, &attr_id) {
        Some(pair) => pair,
        None => {
            collector.push(class_name, &full_path_key, comp, &constraint.name,
                &format!("attribute {} not found in hierarchy", attr_id));
            return (None, None);
        }
    };
    if !attr.is_association_used {
        collector.push(class_name, &full_path_key, comp, &constraint.name, "unused association");
        return (None, None);
    }

    let field_name = sanitize_field(to_snake_case(&attr.label));
    let full_accessor = format!("{accessor_prefix}.{field_name}");

    let result = match comp {
        "sh:RequiredConstraintComponent" | "sh:MinCountConstraintComponent" => {
            gen_required(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:MaxCountConstraintComponent" => {
            gen_max_count_one(&fn_name, class_name, &attr_id, &attr, constraint)
        }
        "sh:ExactCountConstraintComponent" => {
            gen_exact_count(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:InConstraintComponent" => {
            gen_in(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:HasValueConstraintComponent" => {
            gen_has_value(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:DatatypeConstraintComponent" => {
            gen_datatype(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:PatternConstraintComponent" => {
            gen_pattern(&fn_name, class_name, &full_accessor, &attr, constraint, regex_counter)
        }
        "sh:MinLengthConstraintComponent"
        | "sh:MaxLengthConstraintComponent"
        | "sh:LengthConstraintComponent" => {
            gen_length(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:MinExclusiveConstraintComponent"
        | "sh:MaxExclusiveConstraintComponent"
        | "sh:MinInclusiveConstraintComponent"
        | "sh:MaxInclusiveConstraintComponent" => {
            gen_numeric_range(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        "sh:LessThanConstraintComponent" => {
            gen_less_than(&fn_name, class_name, spec, &full_accessor, &attr, constraint)
        }
        "sh:LessThanOrEqualsConstraintComponent" => {
            gen_less_than_or_equals(&fn_name, class_name, spec, &full_accessor, &attr, constraint)
        }
        "sh:ClassConstraintComponent" => {
            gen_class(&fn_name, class_name, spec, &full_accessor, &attr, constraint)
        }
        "sh:OrClassConstraintComponent" => {
            gen_or_class(&fn_name, class_name, spec, &full_accessor, &attr, constraint)
        }
        "sh:NotClassConstraintComponent" => {
            gen_not_class(&fn_name, class_name, &full_accessor, &attr, constraint)
        }
        _ => Err(format!("unknown component: {comp}")),
    };
    match result {
        Ok((code, regex)) => (Some(code), regex),
        Err(reason) => {
            collector.push(class_name, &full_path_key, comp, &constraint.name, &reason);
            (None, None)
        }
    }
}

// ---------------------------------------------------------------------------
// Constraint generators
// ---------------------------------------------------------------------------

fn gen_required(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let condition = if attr.is_list {
        format!("{accessor}.is_empty()")
    } else if attr.is_primitive || attr.is_cim_datatype {
        match attr.lang_type.as_str() {
            "String" => format!("{accessor}.is_empty()"),
            "bool" | "i64" | "f64" => format!("{accessor}.is_none()"),
            _ => format!("{accessor}.is_empty()"),
        }
    } else if attr.is_enum_value {
        format!("{accessor}.is_none()")
    } else {
        format!("{accessor}.is_none()")
    };
    Ok((build_fn(fn_name, class_name, None, None, &condition, c, attr), None))
}

fn gen_max_count_one(
    fn_name: &str,
    class_name: &str,
    attr_id: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let max = c.payload.get("maxCount").and_then(|v| v.as_int()).unwrap_or(1);
    if max != 1 {
        return Err(format!("sh:MaxCount={max} on non-list field (only maxCount=1 is supported)"));
    }
    if attr.is_list {
        return Err("sh:MaxCount=1 on list field — use sh:ExactCount instead".to_string());
    }
    fn esc(s: &str) -> String { s.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        if dataset.entries[mrid].block.duplicate_fields.contains(\"{attr_id}\") {{").unwrap();
    writeln!(s, "            violations.push(Violation {{").unwrap();
    writeln!(s, "                object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "            }});").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

fn gen_exact_count(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if !attr.is_list {
        return Err("sh:ExactCount on non-list field".to_string());
    }
    let n = c.payload.get("minCount").and_then(|v| v.as_int()).unwrap_or(1);
    let condition = format!("{accessor}.len() != {n}");
    Ok((build_fn(fn_name, class_name, None, None, &condition, c, attr), None))
}

/// Literal form an enum value takes after decoding: the decoder strips enum
/// resource URIs to their fragment (`http://...#PhaseCode.ABC` → `PhaseCode.ABC`),
/// so comparison values from the TTL (prefix-simplified, e.g. `cim:PhaseCode.ABC`)
/// must be reduced the same way or the check can never match.
fn enum_literal(v: &str) -> String {
    if let Some(i) = v.rfind('#') {
        v[i + 1..].to_string()
    } else {
        local_name(v)
    }
}

fn gen_in(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.is_list {
        if (attr.is_primitive || attr.is_cim_datatype) && attr.lang_type == "Vec<String>" {
            return gen_slice_string_in(fn_name, class_name, accessor, attr, c);
        }
        return Err("sh:In on non-string list field".to_string());
    }
    if (attr.is_primitive || attr.is_cim_datatype) && attr.lang_type != "String" {
        return Err(format!("sh:In on non-string primitive field ({})", attr.lang_type));
    }
    let values = match c.payload.get("in").and_then(|v| v.as_list()) {
        Some(v) if !v.is_empty() => v,
        _ => return Err("sh:In: empty payload".to_string()),
    };

    // Enum URIs and MridRef resources are both fragment-stripped by the decoder;
    // only plain string literals are stored verbatim.
    let is_string_literal = (attr.is_primitive || attr.is_cim_datatype) && attr.lang_type == "String";
    let allowed_items: Vec<String> = values
        .iter()
        .map(|v| {
            let lit = if is_string_literal { v.clone() } else { enum_literal(v) };
            format!("\"{}\"", lit.replace('"', "\\\""))
        })
        .collect();
    let allowed_str = allowed_items.join(", ");

    let (field_expr, guard) = field_expr_and_guard(accessor, attr);
    let prelude = format!("    const ALLOWED: &[&str] = &[{allowed_str}];\n");
    let condition = format!("!ALLOWED.contains(&{field_expr})");

    Ok((build_fn(fn_name, class_name, guard.as_deref(), Some(&prelude), &condition, c, attr), None))
}

fn gen_has_value(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.is_list { return Err("sh:HasValue on list field".to_string()); }
    if (attr.is_primitive || attr.is_cim_datatype) && attr.lang_type != "String" {
        return Err(format!("sh:HasValue on non-string primitive field ({})", attr.lang_type));
    }
    let expected = match c.payload.get("hasValue").and_then(|v| v.as_str()) {
        Some(v) => v.to_string(),
        None => return Err("sh:HasValue: missing payload".to_string()),
    };
    let esc = expected.replace('"', "\\\"");

    let (condition, guard) = if attr.is_enum_value {
        let lit = enum_literal(&expected).replace('"', "\\\"");
        (format!("{accessor}.as_ref().map_or(true, |u| u.uri != \"{lit}\")"), None)
    } else if attr.is_primitive || attr.is_cim_datatype {
        (format!("{accessor} != \"{esc}\""),
         Some(format!("if {accessor}.is_empty() {{ continue; }}")))
    } else {
        // MridRef resources are fragment-stripped by the decoder, like enum URIs.
        let lit = enum_literal(&expected).replace('"', "\\\"");
        (format!("{accessor}.as_ref().map_or(true, |r| r.mrid != \"{lit}\")"), None)
    };

    Ok((build_fn(fn_name, class_name, guard.as_deref(), None, &condition, c, attr), None))
}

fn gen_datatype(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.lang_type != "String" && attr.lang_type != "Vec<String>" {
        return Err(format!("sh:Datatype on non-string field ({})", attr.lang_type));
    }
    let dt = c.payload.get("datatype").and_then(|v| v.as_str()).unwrap_or("");
    let check_fn = match dt {
        "xsd:dateTime" | "<http://www.w3.org/2001/XMLSchema#dateTime>" => "is_xsd_datetime",
        "xsd:date" | "<http://www.w3.org/2001/XMLSchema#date>" => "is_xsd_date",
        "xsd:gMonthDay" | "<http://www.w3.org/2001/XMLSchema#gMonthDay>" => "is_xsd_gmonthday",
        "xsd:anyURI" | "<http://www.w3.org/2001/XMLSchema#anyURI>" => "is_xsd_anyuri",
        _ => return Err(format!("sh:Datatype: unsupported datatype {:?}", dt)),
    };
    if attr.lang_type == "Vec<String>" {
        return Ok((gen_slice_string_datatype(fn_name, class_name, accessor, attr, c, check_fn), None));
    }
    let guard = format!("if {accessor}.is_empty() {{ continue; }}");
    let condition = format!("!{check_fn}(&{accessor})");
    Ok((build_fn(fn_name, class_name, Some(&guard), None, &condition, c, attr), None))
}

/// sh:Datatype format check applied per-element to a `Vec<String>` field
/// (e.g. md:Model.profile, one xsd:anyURI value per declared profile).
fn gen_slice_string_datatype(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
    check_fn: &str,
) -> String {
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        for val in &{accessor} {{").unwrap();
    writeln!(s, "            if val.is_empty() {{ continue; }}").unwrap();
    writeln!(s, "            if !{check_fn}(val) {{").unwrap();
    writeln!(s, "                violations.push(Violation {{").unwrap();
    writeln!(s, "                    object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                    rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                    class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                    property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                    message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                    severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                    name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                    description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "                }});").unwrap();
    writeln!(s, "            }}").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    s
}

fn gen_pattern(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
    regex_counter: &mut usize,
) -> Result<(String, Option<String>), String> {
    if attr.lang_type != "String" {
        return Err(format!("sh:Pattern on non-string field ({})", attr.lang_type));
    }
    let pattern = match c.payload.get("pattern").and_then(|v| v.as_str()) {
        Some(p) => p.to_string(),
        None => return Err("sh:Pattern: missing pattern payload".to_string()),
    };
    let idx = *regex_counter;
    *regex_counter += 1;
    let static_name = format!("REGEX_{idx}");
    let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
    let regex_decl = format!(
        "static {static_name}: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(\"{escaped}\").expect(\"SHACL regex\"));\n"
    );
    let guard = format!("if {accessor}.is_empty() {{ continue; }}");
    let condition = format!("!{static_name}.is_match(&{accessor})");
    Ok((build_fn(fn_name, class_name, Some(&guard), None, &condition, c, attr), Some(regex_decl)))
}

fn gen_length(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.lang_type != "String" {
        return Err(format!("sh:Length on non-string field ({})", attr.lang_type));
    }
    let comp = c.component.as_str();
    let (key, op) = match comp {
        "sh:MinLengthConstraintComponent" => ("minLength", "<"),
        "sh:MaxLengthConstraintComponent" => ("maxLength", ">"),
        "sh:LengthConstraintComponent" => ("length", "!="),
        _ => return Err(format!("unknown length component: {comp}")),
    };
    let n = match c.payload.get(key).and_then(|v| v.as_int()) {
        Some(n) => n,
        None => return Err("sh:Length: missing payload".to_string()),
    };
    // A missing string and a present-but-empty one both decode to "", so the empty guard
    // below already swallows every value a `sh:minLength 1` could reject. Emitting the check
    // anyway would produce a function that can never fire while claiming coverage of the
    // rule -- CGMES has such a shape on Model.modelingAuthoritySet, handled in
    // cimvalidation/src/sparql/common.rs where the empty case is actually reachable.
    if key == "minLength" && n <= 1 {
        return Err("sh:MinLength<=1 unreachable behind the empty-string guard".to_string());
    }
    let guard = format!("if {accessor}.is_empty() {{ continue; }}");
    let condition = format!("{accessor}.chars().count() {op} {n}");
    Ok((build_fn(fn_name, class_name, Some(&guard), None, &condition, c, attr), None))
}

fn gen_numeric_range(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let comp = c.component.as_str();
    let (key, op) = match comp {
        "sh:MinExclusiveConstraintComponent" => ("minExclusive", "<="),
        "sh:MaxExclusiveConstraintComponent" => ("maxExclusive", ">="),
        "sh:MinInclusiveConstraintComponent" => ("minInclusive", "<"),
        "sh:MaxInclusiveConstraintComponent" => ("maxInclusive", ">"),
        _ => return Err(format!("unknown numeric range component: {comp}")),
    };
    let val = match c.payload.get(key).and_then(|v| v.as_float()) {
        Some(f) => f,
        None => return Err("sh:NumericRange: missing payload".to_string()),
    };
    let (guard, condition) = match attr.lang_type.as_str() {
        "f64" => (
            format!("if {accessor}.is_none() {{ continue; }}"),
            format!("{accessor}.unwrap() {op} {val}_f64"),
        ),
        "i64" => (
            format!("if {accessor}.is_none() {{ continue; }}"),
            format!("({accessor}.unwrap() as f64) {op} {val}_f64"),
        ),
        _ => return Err(format!("sh:NumericRange on non-numeric field ({})", attr.lang_type)),
    };
    Ok((build_fn(fn_name, class_name, Some(&guard), None, &condition, c, attr), None))
}

fn gen_less_than(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    gen_less_than_cmp(fn_name, class_name, spec, accessor, attr, c, "lessThan", "sh:LessThan", "<")
}

fn gen_less_than_or_equals(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    gen_less_than_cmp(fn_name, class_name, spec, accessor, attr, c, "lessThanOrEquals", "sh:LessThanOrEquals", "<=")
}

/// Shared generator for sh:LessThan / sh:LessThanOrEquals: both compare two
/// numeric fields on the same decoded object, differing only in the payload
/// key and the comparison operator.
fn gen_less_than_cmp(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
    payload_key: &str,
    label: &str,
    op: &str,
) -> Result<(String, Option<String>), String> {
    if !matches!(attr.lang_type.as_str(), "f64" | "i64") {
        return Err(format!("{label} on non-numeric field ({})", attr.lang_type));
    }
    let other_iri = match c.payload.get(payload_key).and_then(|v| v.as_str()) {
        Some(v) => v.to_string(),
        None => return Err(format!("{label}: missing {payload_key} payload")),
    };
    let other_attr_id = local_name(&other_iri);
    let (other_prefix, other_attr) = match find_attr_in_hierarchy(spec, class_name, &other_attr_id) {
        Some(p) => p,
        None => return Err(format!("{label}: other attribute {} not found in hierarchy", other_attr_id)),
    };
    if !matches!(other_attr.lang_type.as_str(), "f64" | "i64") {
        return Err(format!("{label}: other attribute {} is non-numeric ({})", other_attr_id, other_attr.lang_type));
    }
    let other_field = sanitize_field(to_snake_case(&other_attr.label));
    let other_accessor = format!("{other_prefix}.{other_field}");

    let mut s = String::new();
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;

    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        if {accessor}.is_none() || {other_accessor}.is_none() {{ continue; }}").unwrap();
    writeln!(s, "        if !(({accessor}.unwrap() as f64) {op} {other_accessor}.unwrap() as f64) {{").unwrap();
    writeln!(s, "            violations.push(Violation {{").unwrap();
    writeln!(s, "                object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "            }});").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

fn gen_not_class(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value || attr.is_list {
        return Err("sh:NotClass on non-association field".to_string());
    }
    let forbidden = match c.payload.get("class").and_then(|v| v.as_str()) {
        Some(v) => local_name(v),
        None => return Err("sh:NotClass: missing class payload".to_string()),
    };

    let mut s = String::new();
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;

    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        let ref_mrid = match {accessor}.as_ref() {{").unwrap();
    writeln!(s, "            Some(r) => &r.mrid, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        if let Some(ref_entry) = dataset.entries.get(ref_mrid) {{").unwrap();
    writeln!(s, "            if ref_entry.element.type_name() == \"{forbidden}\" {{").unwrap();
    writeln!(s, "                violations.push(Violation {{").unwrap();
    writeln!(s, "                    object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                    rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                    class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                    property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                    message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                    severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                    name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                    description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "                }});").unwrap();
    writeln!(s, "            }}").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

fn gen_class(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value {
        return Err("sh:Class on non-association field".to_string());
    }
    let wanted = match c.payload.get("class").and_then(|v| v.as_str()) {
        Some(v) => local_name(v),
        None => return Err("sh:Class: missing class payload".to_string()),
    };
    // Expand to all types that ARE or inherit from `wanted`. If everything
    // qualifies, the constraint is vacuously true and can be skipped.
    let allowed_types = class_and_subclasses(spec, &wanted);
    if allowed_types.is_empty() || allowed_types.len() >= spec.types.len() {
        return Err(format!("sh:Class vacuously true: all subtypes of {} qualify", wanted));
    }
    gen_ref_type_check(fn_name, class_name, accessor, attr, c, &allowed_types)
}

fn gen_or_class(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value {
        return Err("sh:OrClass on non-association field".to_string());
    }
    let raw_classes: Vec<String> = match c.payload.get("classes").and_then(|v| v.as_list()) {
        Some(v) if !v.is_empty() => v.iter().map(|s| local_name(s)).collect(),
        _ => return Err("sh:OrClass: empty class list".to_string()),
    };
    // Expand each listed class to include its subclasses.
    let mut allowed_set = std::collections::BTreeSet::new();
    for cls in &raw_classes {
        for t in class_and_subclasses(spec, cls) {
            allowed_set.insert(t);
        }
    }
    let allowed_types: Vec<String> = allowed_set.into_iter().collect();
    if allowed_types.is_empty() || allowed_types.len() >= spec.types.len() {
        return Err("sh:OrClass vacuously true: all subtypes qualify".to_string());
    }
    gen_ref_type_check(fn_name, class_name, accessor, attr, c, &allowed_types)
}

fn gen_ref_type_check(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
    allowed_types: &[String],
) -> Result<(String, Option<String>), String> {
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;
    let allowed_str = allowed_types.iter()
        .map(|t| format!("\"{}\"", t))
        .collect::<Vec<_>>()
        .join(", ");

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();

    if attr.is_list {
        writeln!(s, "        for r in &{accessor} {{").unwrap();
        writeln!(s, "            let ref_id = r.mrid.trim_start_matches('#');").unwrap();
        writeln!(s, "            if ref_id.is_empty() {{ continue; }}").unwrap();
        writeln!(s, "            if let Some(ref_entry) = dataset.entries.get(ref_id) {{").unwrap();
        writeln!(s, "                let allowed: &[&str] = &[{allowed_str}];").unwrap();
        writeln!(s, "                if !allowed.contains(&ref_entry.element.type_name()) {{").unwrap();
        writeln!(s, "                    violations.push(Violation {{").unwrap();
        writeln!(s, "                        object_id:   mrid.clone(),").unwrap();
        writeln!(s, "                        rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
        writeln!(s, "                        class:       \"{class_name}\".to_string(),").unwrap();
        writeln!(s, "                        property:    \"{prop}\".to_string(),").unwrap();
        writeln!(s, "                        message:     \"{message}\".to_string(),").unwrap();
        writeln!(s, "                        severity:    \"{severity}\".to_string(),").unwrap();
        writeln!(s, "                        name:        \"{name_str}\".to_string(),").unwrap();
        writeln!(s, "                        description: \"{desc_str}\".to_string(),").unwrap();
        writeln!(s, "                    }});").unwrap();
        writeln!(s, "                }}").unwrap();
        writeln!(s, "            }}").unwrap();
        writeln!(s, "        }}").unwrap();
    } else {
        writeln!(s, "        let ref_mrid = match {accessor}.as_ref() {{").unwrap();
        writeln!(s, "            Some(r) => r.mrid.trim_start_matches('#'), None => continue,").unwrap();
        writeln!(s, "        }};").unwrap();
        writeln!(s, "        if let Some(ref_entry) = dataset.entries.get(ref_mrid) {{").unwrap();
        writeln!(s, "            let allowed: &[&str] = &[{allowed_str}];").unwrap();
        writeln!(s, "            if !allowed.contains(&ref_entry.element.type_name()) {{").unwrap();
        writeln!(s, "                violations.push(Violation {{").unwrap();
        writeln!(s, "                    object_id:   mrid.clone(),").unwrap();
        writeln!(s, "                    rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
        writeln!(s, "                    class:       \"{class_name}\".to_string(),").unwrap();
        writeln!(s, "                    property:    \"{prop}\".to_string(),").unwrap();
        writeln!(s, "                    message:     \"{message}\".to_string(),").unwrap();
        writeln!(s, "                    severity:    \"{severity}\".to_string(),").unwrap();
        writeln!(s, "                    name:        \"{name_str}\".to_string(),").unwrap();
        writeln!(s, "                    description: \"{desc_str}\".to_string(),").unwrap();
        writeln!(s, "                }});").unwrap();
        writeln!(s, "            }}").unwrap();
        writeln!(s, "        }}").unwrap();
    }

    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

fn gen_slice_mrid_rdf_type_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    attr_id: &str,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let (accessor_prefix, attr) = match find_attr_in_hierarchy(spec, class_name, attr_id) {
        Some(p) => p,
        None => return Err(format!("slice-mrid: attribute {} not found in hierarchy", attr_id)),
    };
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value || !attr.is_association_used {
        return Err("slice-mrid: field is not a usable association".to_string());
    }
    let field_name = sanitize_field(to_snake_case(&attr.label));
    let accessor = format!("{accessor_prefix}.{field_name}");

    let comp = c.component.as_str();
    let allowed_types: Vec<String> = match comp {
        "sh:InConstraintComponent" => {
            match c.payload.get("in").and_then(|v| v.as_list()) {
                Some(v) if !v.is_empty() => v.iter().map(|s| local_name(s)).collect(),
                _ => return Err("slice-mrid sh:In: empty payload".to_string()),
            }
        }
        "sh:HasValueConstraintComponent" => {
            match c.payload.get("hasValue").and_then(|v| v.as_str()) {
                Some(v) => vec![local_name(v)],
                None => return Err("slice-mrid sh:HasValue: missing payload".to_string()),
            }
        }
        _ => return Err(format!("slice-mrid: component {} not supported", comp)),
    };
    if allowed_types.is_empty() {
        return Err("slice-mrid: empty allowed types list".to_string());
    }
    gen_ref_type_check(fn_name, class_name, &accessor, &attr, c, &allowed_types)
}

fn gen_slice_string_in(
    fn_name: &str,
    class_name: &str,
    accessor: &str,
    attr: &CimAttribute,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let values = match c.payload.get("in").and_then(|v| v.as_list()) {
        Some(v) if !v.is_empty() => v,
        _ => return Err("sh:SliceStringIn: empty list".to_string()),
    };
    let allowed_items: Vec<String> = values
        .iter()
        .map(|v| format!("\"{}\"", v.replace('"', "\\\"")))
        .collect();
    let allowed_str = allowed_items.join(", ");

    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &attr.id;

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        let allowed: &[&str] = &[{allowed_str}];").unwrap();
    writeln!(s, "        for val in &{accessor} {{").unwrap();
    writeln!(s, "            if val.is_empty() {{ continue; }}").unwrap();
    writeln!(s, "            if !allowed.contains(&val.as_str()) {{").unwrap();
    writeln!(s, "                violations.push(Violation {{").unwrap();
    writeln!(s, "                    object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                    rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                    class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                    property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                    message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                    severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                    name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                    description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "                }});").unwrap();
    writeln!(s, "            }}").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

// ---------------------------------------------------------------------------
// Inverse path generator
// ---------------------------------------------------------------------------

/// sh:targetNode <cim:Class> with sh:path [ sh:inversePath rdf:type ] and
/// sh:minCount/sh:maxCount: a single dataset-wide check on how many instances
/// of `target_class` exist (e.g. "at least one TopologicalIsland", "at most
/// one GeographicalRegion"), not a per-instance check. Emits at most one
/// violation, matching cimgo's generated form (empty object_id).
fn gen_instance_count(
    fn_name: &str,
    target_class: &str,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let (op, threshold) = match c.component.as_str() {
        "sh:MinCountConstraintComponent" | "sh:RequiredConstraintComponent" =>
            ("<", c.payload.get("minCount").and_then(|v| v.as_int()).unwrap_or(1)),
        "sh:MaxCountConstraintComponent" =>
            (">", c.payload.get("maxCount").and_then(|v| v.as_int()).unwrap_or(1)),
        _ => return Err(format!("inverse rdf:type count: component {} not supported", c.component)),
    };

    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop = &c.name;

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let count = dataset.by_type.get(\"{target_class}\").map_or(0, |v| v.len());").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    if count {op} {threshold} {{").unwrap();
    writeln!(s, "        violations.push(Violation {{").unwrap();
    writeln!(s, "            object_id:   String::new(),").unwrap();
    writeln!(s, "            rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "            class:       \"{target_class}\".to_string(),").unwrap();
    writeln!(s, "            property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "            message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "            severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "            name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "            description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "        }});").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

fn gen_inverse_count(
    fn_name: &str,
    target_class: &str,
    forward_pred: &str,
    spec: &CimSpecification,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    // sh:targetNode <cim:Class> with sh:path [ sh:inversePath rdf:type ]: the
    // inverse of rdf:type from the class node reaches every instance of that
    // class, so min/maxCount here means "N instances of Class must exist" —
    // a single dataset-wide check, not one CIM association per instance.
    if local_name(forward_pred) == "type" {
        return gen_instance_count(fn_name, target_class, c);
    }
    let local = local_name(forward_pred);
    let (src_class, src_prop) = match local.split_once('.') {
        Some(p) => p,
        None => return Err("inverse path has no class.prop shape".to_string()),
    };

    let (_, attr) = match find_attr_in_hierarchy(spec, src_class, &local) {
        Some(p) => p,
        None => return Err(format!("inverse attribute {} not found in hierarchy", local)),
    };
    if !attr.is_association_used {
        return Err("inverse unused association".to_string());
    }
    // Inverse path requires an association field (Option<MridRef> or Vec<MridRef>)
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value {
        return Err("inverse path on non-association field".to_string());
    }

    // The referrer class can be abstract (e.g. RegulatingCondEq) — dataset.by_type
    // only holds concrete type names, so the index must scan every subclass that
    // can carry the forward field, or the count is always 0 and every target is
    // falsely flagged.
    let field_name = sanitize_field(to_snake_case(src_prop));
    let mut scan_classes: Vec<(String, String)> = Vec::new();
    for cls in class_and_subclasses(spec, src_class) {
        if let Some((prefix, _)) = find_attr_in_hierarchy(spec, &cls, &local) {
            let src_prefix = prefix.replacen("obj", "src", 1);
            scan_classes.push((cls, format!("{src_prefix}.{field_name}")));
        }
    }
    if scan_classes.is_empty() {
        return Err(format!("inverse attribute {} has no concrete referrer class", local));
    }

    let index_snippets: Vec<(String, String)> = scan_classes
        .into_iter()
        .map(|(cls, src_field)| {
            let snippet = if attr.is_list {
                format!("for r in &{src_field} {{ *ref_counts.entry(r.mrid.as_str()).or_insert(0) += 1; }}")
            } else {
                format!("if let Some(r) = &{src_field} {{ *ref_counts.entry(r.mrid.as_str()).or_insert(0) += 1; }}")
            };
            (cls, snippet)
        })
        .collect();

    let (op, threshold) = match c.component.as_str() {
        "sh:MinCountConstraintComponent" | "sh:RequiredConstraintComponent" =>
            ("<", c.payload.get("minCount").and_then(|v| v.as_int()).unwrap_or(1)),
        "sh:MaxCountConstraintComponent" =>
            (">", c.payload.get("maxCount").and_then(|v| v.as_int()).unwrap_or(1)),
        // The prelude's downcast_ref::<src_class> already type-asserts every scanned
        // referrer, so an sh:class constraint on the inverse path can never fire.
        "sh:ClassConstraintComponent" =>
            return Err("sh:Class vacuously true: inverse index already type-asserts the referrer class".to_string()),
        _ => return Err(format!("inverse path: component {} not supported", c.component)),
    };

    Ok((build_inverse_fn(fn_name, target_class, &index_snippets, threshold, op, c), None))
}

fn build_inverse_fn(
    fn_name: &str,
    target_class: &str,
    index_snippets: &[(String, String)],
    threshold: i64,
    op: &str,
    c: &ConstraintInfo,
) -> String {
    let mut s = String::new();
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message  = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);
    let prop     = &c.name;

    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut ref_counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();").unwrap();
    for (src_class, index_snippet) in index_snippets {
        writeln!(s, "    for src_mrid in dataset.by_type.get(\"{src_class}\").into_iter().flatten() {{").unwrap();
        writeln!(s, "        if let Some(src) = dataset.entries.get(src_mrid)").unwrap();
        writeln!(s, "            .and_then(|e| e.element.as_any().downcast_ref::<cimstructs::{src_class}>()) {{").unwrap();
        writeln!(s, "            {index_snippet}").unwrap();
        writeln!(s, "        }}").unwrap();
        writeln!(s, "    }}").unwrap();
    }
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{target_class}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let count = ref_counts.get(mrid.as_str()).copied().unwrap_or(0);").unwrap();
    writeln!(s, "        if count {op} {threshold} {{").unwrap();
    writeln!(s, "            violations.push(Violation {{").unwrap();
    writeln!(s, "                object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                class:       \"{target_class}\".to_string(),").unwrap();
    writeln!(s, "                property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "            }});").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    s
}

// ---------------------------------------------------------------------------
// Forward chain generators (multi-segment paths)
// ---------------------------------------------------------------------------

/// Splits a path segment like "cim:StreetAddress.status" into ("StreetAddress",
/// full local name "StreetAddress.status").
fn seg_class_and_local(seg: &str) -> Result<(String, String), String> {
    let local = local_name(seg);
    match local.split_once('.') {
        Some((class, _)) => Ok((class.to_string(), local.clone())),
        None => Err(format!("chain segment {} has no Class.prop shape", seg)),
    }
}

/// Resolves a chain hop attribute and enforces that it decodes to a single
/// 0..1 `MridRef` field. Returns (accessor relative to `var`, attr).
fn chain_hop_accessor(
    spec: &CimSpecification,
    owner_class: &str,
    attr_local: &str,
    var: &str,
) -> Result<(String, CimAttribute), String> {
    let (prefix, attr) = find_attr_in_hierarchy(spec, owner_class, attr_local)
        .ok_or_else(|| format!("chain attribute {} not found in hierarchy", attr_local))?;
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value {
        return Err(format!("chain hop {} is not a reference field", attr_local));
    }
    if attr.is_list {
        return Err(format!("chain hop {} is a list field (not supported)", attr_local));
    }
    let field = sanitize_field(to_snake_case(&attr.label));
    Ok((format!("{}.{field}", prefix.replacen("obj", var, 1)), attr))
}

/// Emits the reference walk for the association segments `segs` into `s` (inside
/// the per-object loop opened by `write_fn_header`, i.e. with `obj` in scope).
/// Any missing or unresolvable link `continue`s — the path yields no value there,
/// matching cimgo's chain-walker. Returns the variable naming the final entry.
fn emit_forward_chain_walk(
    s: &mut String,
    class_name: &str,
    spec: &CimSpecification,
    segs: &[String],
) -> Result<String, String> {
    let (acc0, _) = chain_hop_accessor(spec, class_name, &local_name(&segs[0]), "obj")?;
    writeln!(s, "        let ref0 = match {acc0}.as_ref() {{").unwrap();
    writeln!(s, "            Some(r) => r.mrid.trim_start_matches('#'), None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        let entry0 = match dataset.entries.get(ref0) {{").unwrap();
    writeln!(s, "            Some(e) => e, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();

    for (i, seg) in segs.iter().enumerate().skip(1) {
        let (hop_class, attr_local) = seg_class_and_local(seg)?;
        if !spec.types.contains_key(&hop_class) {
            return Err(format!("chain hop class {} not in schema", hop_class));
        }
        let hop_var = format!("hop{i}");
        let (acc, _) = chain_hop_accessor(spec, &hop_class, &attr_local, &hop_var)?;
        let prev = i - 1;
        writeln!(s, "        let {hop_var} = match entry{prev}.element.as_any()").unwrap();
        writeln!(s, "            .downcast_ref::<cimstructs::{hop_class}>() {{").unwrap();
        writeln!(s, "            Some(o) => o, None => continue,").unwrap();
        writeln!(s, "        }};").unwrap();
        writeln!(s, "        let ref{i} = match {acc}.as_ref() {{").unwrap();
        writeln!(s, "            Some(r) => r.mrid.trim_start_matches('#'), None => continue,").unwrap();
        writeln!(s, "        }};").unwrap();
        writeln!(s, "        let entry{i} = match dataset.entries.get(ref{i}) {{").unwrap();
        writeln!(s, "            Some(e) => e, None => continue,").unwrap();
        writeln!(s, "        }};").unwrap();
    }
    Ok(format!("entry{}", segs.len() - 1))
}

/// sh:Required over a multi-segment forward chain: the presence requirement
/// collapses onto the first link (cimgo parity — a later link that doesn't
/// resolve is indistinguishable from data legitimately split across files).
fn gen_chain_required_first_link(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    attr_local: &str,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let (prefix, attr) = find_attr_in_hierarchy(spec, class_name, attr_local)
        .ok_or_else(|| format!("chain attribute {} not found in hierarchy", attr_local))?;
    if attr.is_primitive || attr.is_cim_datatype || attr.is_enum_value {
        return Err(format!("chain Required first link {} is not a reference field", attr_local));
    }
    let field = sanitize_field(to_snake_case(&attr.label));
    let accessor = format!("{prefix}.{field}");
    gen_required(fn_name, class_name, &accessor, &attr, c)
}

/// Walks the association segments and requires the final resolved entry's class
/// to be in `allowed` (already subclass-expanded). Backs sh:HasValue with an
/// rdf:type tail and multi-hop sh:or-of-sh:class.
fn gen_forward_chain_type_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    segs: &[String],
    allowed: &[String],
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let mut walk = String::new();
    let final_entry = emit_forward_chain_walk(&mut walk, class_name, spec, segs)?;
    let (message, severity, name_str, rule_id_str, desc_str, _) = extract_violation_fields(c);
    let prop = local_name(&segs[0]);
    let allowed_str = allowed.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(", ");

    let mut s = String::new();
    write_fn_header(&mut s, fn_name, class_name);
    s.push_str(&walk);
    writeln!(s, "        let allowed: &[&str] = &[{allowed_str}];").unwrap();
    writeln!(s, "        if !allowed.contains(&{final_entry}.element.type_name()) {{").unwrap();
    write_violation(&mut s, class_name, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    write_fn_footer(&mut s);
    Ok((s, None))
}

/// Walks the association segments up to the last one, then applies an
/// sh:datatype format check to the primitive leaf field named by the final segment.
fn gen_forward_chain_datatype_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    segs: &[String],
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let (mid, leaf_seg) = segs.split_at(segs.len() - 1);
    if mid.is_empty() {
        return Err("chain datatype: no hop segments".to_string());
    }
    let (leaf_class, leaf_local) = seg_class_and_local(&leaf_seg[0])?;
    if !spec.types.contains_key(&leaf_class) {
        return Err(format!("chain leaf class {} not in schema", leaf_class));
    }
    let (leaf_prefix, leaf_attr) = find_attr_in_hierarchy(spec, &leaf_class, &leaf_local)
        .ok_or_else(|| format!("chain attribute {} not found in hierarchy", leaf_local))?;
    if leaf_attr.lang_type != "String" || leaf_attr.is_list {
        return Err(format!("chain sh:Datatype on non-string leaf {}", leaf_local));
    }
    let dt = c.payload.get("datatype").and_then(|v| v.as_str()).unwrap_or("");
    let check_fn = match dt {
        "xsd:dateTime" | "<http://www.w3.org/2001/XMLSchema#dateTime>" => "is_xsd_datetime",
        "xsd:date" | "<http://www.w3.org/2001/XMLSchema#date>" => "is_xsd_date",
        "xsd:gMonthDay" | "<http://www.w3.org/2001/XMLSchema#gMonthDay>" => "is_xsd_gmonthday",
        "xsd:anyURI" | "<http://www.w3.org/2001/XMLSchema#anyURI>" => "is_xsd_anyuri",
        _ => return Err(format!("chain sh:Datatype: unsupported datatype {:?}", dt)),
    };

    let mut walk = String::new();
    let final_entry = emit_forward_chain_walk(&mut walk, class_name, spec, mid)?;
    let (message, severity, name_str, rule_id_str, desc_str, _) = extract_violation_fields(c);
    let prop = local_name(&segs[0]);
    let leaf_field = sanitize_field(to_snake_case(&leaf_attr.label));
    let leaf_acc = format!("{}.{leaf_field}", leaf_prefix.replacen("obj", "leaf", 1));

    let mut s = String::new();
    write_fn_header(&mut s, fn_name, class_name);
    s.push_str(&walk);
    writeln!(s, "        let leaf = match {final_entry}.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{leaf_class}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        if {leaf_acc}.is_empty() {{ continue; }}").unwrap();
    writeln!(s, "        if !{check_fn}(&{leaf_acc}) {{").unwrap();
    write_violation(&mut s, class_name, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    write_fn_footer(&mut s);
    Ok((s, None))
}

/// [^forward-ref, enum-attr] sh:HasValue: the target object must be referenced by
/// at least one source object whose enum attribute carries the expected value
/// (e.g. every Ground needs a Terminal with Terminal.phases = PhaseCode.N).
fn gen_inverse_chain_has_value(
    fn_name: &str,
    target_class: &str,
    spec: &CimSpecification,
    inv_seg: &str,
    value_seg: &str,
    c: &ConstraintInfo,
) -> Result<(String, Option<String>), String> {
    let forward = &inv_seg[1..];
    let (src_class, ref_local) = seg_class_and_local(forward)?;
    if !spec.types.contains_key(&src_class) {
        return Err(format!("inverse chain source class {} not in schema", src_class));
    }
    let (ref_prefix, ref_attr) = find_attr_in_hierarchy(spec, &src_class, &ref_local)
        .ok_or_else(|| format!("chain attribute {} not found in hierarchy", ref_local))?;
    if ref_attr.is_primitive || ref_attr.is_cim_datatype || ref_attr.is_enum_value {
        return Err(format!("inverse chain link {} is not a reference field", ref_local));
    }
    let value_local = local_name(value_seg);
    let (val_prefix, val_attr) = find_attr_in_hierarchy(spec, &src_class, &value_local)
        .ok_or_else(|| format!("chain attribute {} not found in hierarchy", value_local))?;
    if !val_attr.is_enum_value {
        return Err(format!("inverse chain sh:HasValue on non-enum attribute {}", value_local));
    }
    let expected = enum_literal(
        c.payload.get("hasValue").and_then(|v| v.as_str())
            .ok_or_else(|| "inverse chain sh:HasValue: missing payload".to_string())?,
    )
    .replace('"', "\\\"");

    let ref_field = sanitize_field(to_snake_case(&ref_attr.label));
    let ref_acc = format!("{}.{ref_field}", ref_prefix.replacen("obj", "src", 1));
    let val_field = sanitize_field(to_snake_case(&val_attr.label));
    let val_acc = format!("{}.{val_field}", val_prefix.replacen("obj", "src", 1));

    let (message, severity, name_str, rule_id_str, desc_str, _) = extract_violation_fields(c);
    let prop = ref_local;

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut has_value: std::collections::HashSet<&str> = std::collections::HashSet::new();").unwrap();
    writeln!(s, "    for src_mrid in dataset.by_type.get(\"{src_class}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let src = match dataset.entries.get(src_mrid)").unwrap();
    writeln!(s, "            .and_then(|e| e.element.as_any().downcast_ref::<cimstructs::{src_class}>()) {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    writeln!(s, "        if {val_acc}.as_ref().map_or(true, |u| u.uri != \"{expected}\") {{ continue; }}").unwrap();
    if ref_attr.is_list {
        writeln!(s, "        for r in &{ref_acc} {{ has_value.insert(r.mrid.trim_start_matches('#')); }}").unwrap();
    } else {
        writeln!(s, "        if let Some(r) = {ref_acc}.as_ref() {{ has_value.insert(r.mrid.trim_start_matches('#')); }}").unwrap();
    }
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{target_class}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        if !has_value.contains(mrid.as_str()) {{").unwrap();
    write_violation(&mut s, target_class, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Ok((s, None))
}

// ---------------------------------------------------------------------------
// Code-building helpers
// ---------------------------------------------------------------------------

fn field_expr_and_guard(accessor: &str, attr: &CimAttribute) -> (String, Option<String>) {
    if attr.is_enum_value {
        (
            format!("{accessor}.as_ref().map_or(\"\", |u| u.uri.as_str())"),
            Some(format!("if {accessor}.is_none() {{ continue; }}")),
        )
    } else if attr.is_primitive || attr.is_cim_datatype {
        (
            format!("{accessor}.as_str()"),
            Some(format!("if {accessor}.is_empty() {{ continue; }}")),
        )
    } else {
        (
            format!("{accessor}.as_ref().map_or(\"\", |r| r.mrid.as_str())"),
            Some(format!("if {accessor}.is_none() {{ continue; }}")),
        )
    }
}

fn build_fn(
    fn_name: &str,
    class_name: &str,
    guard: Option<&str>,
    prelude: Option<&str>,     // constant decls outside the loop
    condition: &str,
    c: &ConstraintInfo,
    attr: &CimAttribute,
) -> String {
    let mut s = String::new();
    let prop = &attr.id;
    fn esc(s: &str) -> String { s.replace('\\', "\\\\").replace('"', "\\\"") }
    let message = esc(&c.message);
    let severity = &c.severity;
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str = esc(&c.description);

    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    // Prelude goes BEFORE the loop (constants, regex etc.)
    if let Some(pre) = prelude {
        s.push_str(pre);
    }
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
    if let Some(g) = guard {
        writeln!(s, "        {g}").unwrap();
    }
    writeln!(s, "        if {condition} {{").unwrap();
    writeln!(s, "            violations.push(Violation {{").unwrap();
    writeln!(s, "                object_id:   mrid.clone(),").unwrap();
    writeln!(s, "                rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "                class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "                property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "                message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "                severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "                name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "                description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "            }});").unwrap();
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    s
}

// ---------------------------------------------------------------------------
// Field lookup
// ---------------------------------------------------------------------------

fn find_attr_in_hierarchy(
    spec: &CimSpecification,
    class_name: &str,
    attr_id: &str,
) -> Option<(String, CimAttribute)> {
    let mut depth = 0usize;
    let mut current_id = class_name.to_string();
    loop {
        let t = spec.types.get(&current_id)?;
        if let Some(attr) = t.attributes.iter().find(|a| a.id == attr_id) {
            // depth 0 → "obj", depth 1 → "obj.base", depth 2 → "obj.base.base"
            let prefix = format!("obj{}", ".base".repeat(depth));
            return Some((prefix, attr.clone()));
        }
        if t.super_type.is_empty() || t.super_type == current_id {
            break;
        }
        depth += 1;
        current_id = t.super_type.clone();
    }
    None
}

// ---------------------------------------------------------------------------
// Name helpers
// ---------------------------------------------------------------------------

fn local_name(simplified_iri: &str) -> String {
    if let Some(colon) = simplified_iri.find(':') {
        simplified_iri[colon + 1..].to_string()
    } else {
        simplified_iri.to_string()
    }
}

/// Convert a TTL file name to a valid Rust module name.
fn file_to_mod_name(file_name: &str) -> String {
    let raw: String = file_name
        .chars()
        .map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '_' })
        .collect();
    // Module names can't start with a digit
    let raw = raw.trim_matches('_');
    if raw.starts_with(|c: char| c.is_ascii_digit()) {
        format!("p{raw}")
    } else {
        raw.to_string()
    }
}

fn component_suffix(component: &str) -> &str {
    match component {
        "sh:RequiredConstraintComponent" => "required",
        "sh:MinCountConstraintComponent" => "min_count",
        "sh:MaxCountConstraintComponent" => "max_count",
        "sh:ExactCountConstraintComponent" => "exact_count",
        "sh:InConstraintComponent" => "in",
        "sh:HasValueConstraintComponent" => "has_value",
        "sh:DatatypeConstraintComponent" => "datatype",
        "sh:ClassConstraintComponent" => "class_check",
        "sh:OrClassConstraintComponent" => "or_class",
        "sh:NotClassConstraintComponent" => "not_class",
        "sh:LessThanConstraintComponent" => "less_than",
        "sh:LessThanOrEqualsConstraintComponent" => "less_than_or_equals",
        "sh:PatternConstraintComponent" => "pattern",
        "sh:MinLengthConstraintComponent" => "min_length",
        "sh:MaxLengthConstraintComponent" => "max_length",
        "sh:LengthConstraintComponent" => "length",
        "sh:MinExclusiveConstraintComponent" => "min_excl",
        "sh:MaxExclusiveConstraintComponent" => "max_excl",
        "sh:MinInclusiveConstraintComponent" => "min_incl",
        "sh:MaxInclusiveConstraintComponent" => "max_incl",
        _ => "constraint",
    }
}

fn safe_fn_name(raw: &str) -> String {
    // Collapse runs of underscores, ensure doesn't start with digit
    let collapsed: String = {
        let mut prev = '_';
        let mut s = String::new();
        for c in raw.chars() {
            if c == '_' && prev == '_' { continue; }
            s.push(c);
            prev = c;
        }
        s.trim_matches('_').to_string()
    };
    if collapsed.starts_with(|c: char| c.is_ascii_digit()) {
        format!("check_{collapsed}")
    } else if collapsed.len() > 100 {
        format!("{}_etc", collapsed[..97].trim_end_matches('_'))
    } else {
        collapsed
    }
}

fn extract_fn_name(code: &str) -> String {
    code.lines()
        .find(|l| l.starts_with("pub fn "))
        .and_then(|l| l.strip_prefix("pub fn "))
        .and_then(|l| l.split('(').next())
        .unwrap_or("")
        .to_string()
}

// ---------------------------------------------------------------------------
// Compound constraint generators (sh:xone, sh:or, sh:and)
// ---------------------------------------------------------------------------

fn gen_compound_check(
    file_snake: &str,
    class_name: &str,
    spec: &CimSpecification,
    c: &ConstraintInfo,
) -> Result<String, String> {
    let branches = c.payload.get("branches").and_then(|v| v.as_shapes())
        .ok_or_else(|| "compound check: missing branches payload".to_string())?;

    let comp_suffix = match c.component.as_str() {
        "sh:XoneConstraintComponent" => "xone",
        "sh:OrConstraintComponent" => "or",
        "sh:AndConstraintComponent" => "and",
        _ => return Err(format!("unknown compound component: {}", c.component)),
    };
    let raw_name = format!(
        "check_{file_snake}_{class_snake}_{comp_suffix}",
        class_snake = to_snake_case(class_name),
    );
    let fn_name = safe_fn_name(&raw_name);

    match c.component.as_str() {
        "sh:XoneConstraintComponent" => gen_xone_check(&fn_name, class_name, spec, c, branches)
            .ok_or_else(|| "sh:xone: branch structure not supported".to_string()),
        "sh:OrConstraintComponent"   => gen_or_compound_check(&fn_name, class_name, spec, c, branches)
            .ok_or_else(|| "sh:or: branch structure not supported".to_string()),
        "sh:AndConstraintComponent"  => gen_and_compound_check(&fn_name, class_name, spec, c, branches)
            .ok_or_else(|| "sh:and: branch structure not supported".to_string()),
        _ => Err(format!("unknown compound component: {}", c.component)),
    }
}

/// sh:xone: exactly one of N forward-pointer fields must be non-None.
/// Each branch must have a single MinCount=1 on a forward association path.
fn gen_xone_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    c: &ConstraintInfo,
    branches: &[Vec<ConstraintInfo>],
) -> Option<String> {
    let mut field_accessors: Vec<String> = Vec::new();
    for branch in branches {
        let min1 = branch.iter().find(|ci|
            ci.component == "sh:MinCountConstraintComponent"
            && ci.payload.get("minCount").and_then(|v| v.as_int()) == Some(1)
            && ci.path.len() == 1 && !ci.path[0].starts_with('^'))?;
        let attr_id = local_name(&min1.path[0]);
        let (acc_prefix, attr) = find_attr_in_hierarchy(spec, class_name, &attr_id)?;
        if !attr.is_association_used || attr.is_list { return None; }
        let field = sanitize_field(to_snake_case(&attr.label));
        field_accessors.push(format!("{acc_prefix}.{field}"));
    }
    if field_accessors.len() < 2 { return None; }

    let (message, severity, name_str, rule_id_str, desc_str, prop) = extract_violation_fields(c);
    let mut s = String::new();
    write_fn_header(&mut s, fn_name, class_name);
    writeln!(s, "        let mut pass_count = 0usize;").unwrap();
    for acc in &field_accessors {
        writeln!(s, "        if {acc}.is_some() {{ pass_count += 1; }}").unwrap();
    }
    writeln!(s, "        if pass_count != 1 {{").unwrap();
    write_violation(&mut s, class_name, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    write_fn_footer(&mut s);
    Some(s)
}

/// sh:or: violation when ALL branches fail their inverse-count range.
/// Each branch must have exactly one inverse-path with min/max count.
fn gen_or_compound_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    c: &ConstraintInfo,
    branches: &[Vec<ConstraintInfo>],
) -> Option<String> {
    struct InvBranch { prelude: String, fail_cond: String }
    let mut parsed: Vec<InvBranch> = Vec::new();

    for (i, branch) in branches.iter().enumerate() {
        // Must have at least one constraint with inverse path
        let inv = branch.iter().find(|ci|
            !ci.path.is_empty() && ci.path[0].starts_with('^'))?;
        if inv.path.len() != 1 { return None; } // multi-segment: skip

        let prelude = build_inverse_count_prelude(spec, &inv.path[0], i)?;
        let min = branch.iter().find(|ci| ci.component == "sh:MinCountConstraintComponent")
            .and_then(|ci| ci.payload.get("minCount").and_then(|v| v.as_int()))
            .unwrap_or(0);
        let max = branch.iter().find(|ci| ci.component == "sh:MaxCountConstraintComponent")
            .and_then(|ci| ci.payload.get("maxCount").and_then(|v| v.as_int()))
            .unwrap_or(i64::MAX / 2);
        let fail_cond = inverse_fail_cond(i, min, max);
        parsed.push(InvBranch { prelude, fail_cond });
    }
    if parsed.len() < 2 { return None; }

    let (message, severity, name_str, rule_id_str, desc_str, prop) = extract_violation_fields(c);
    let all_fail = parsed.iter().map(|b| b.fail_cond.as_str()).collect::<Vec<_>>().join(" && ");

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    for b in &parsed { s.push_str(&b.prelude); }
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        if {all_fail} {{").unwrap();
    write_violation(&mut s, class_name, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Some(s)
}

/// sh:and: violation when ANY branch fails.
/// Branches can be:
///   - forward MaxCount=0 (field must be absent)
///   - forward MinCount=1+MaxCount=1 (field must be present, scalar only)
///   - inverse single-segment path with min/max count
///   - multi-segment (skipped — returns None for whole check)
fn gen_and_compound_check(
    fn_name: &str,
    class_name: &str,
    spec: &CimSpecification,
    c: &ConstraintInfo,
    branches: &[Vec<ConstraintInfo>],
) -> Option<String> {
    let mut prelude_parts: Vec<String> = Vec::new();
    let mut fail_conds: Vec<String> = Vec::new();
    let mut needs_obj = false;
    let mut inv_idx = 0usize;

    for branch in branches {
        // Find a path from any constraint in this branch
        let any_path = branch.iter().find(|ci| !ci.path.is_empty()).map(|ci| &ci.path[0]);
        let path0 = any_path?;

        if path0.starts_with('^') {
            // Inverse path branch, single-segment (^Class.field) or two-segment
            // (^Class.field / Class.otherField): the latter counts, per outer
            // object, how many referrers ALSO have the second field set (e.g.
            // "how many referring Terminals also have a ConnectivityNode").
            let inv_ci = branch.iter().find(|ci| !ci.path.is_empty())?;
            let prelude = match inv_ci.path.len() {
                1 => build_inverse_count_prelude(spec, &inv_ci.path[0], inv_idx)?,
                2 => build_inverse_forward_count_prelude(spec, &inv_ci.path, inv_idx)?,
                _ => return None, // longer chains: skip
            };
            let min = branch.iter().find(|ci| ci.component == "sh:MinCountConstraintComponent")
                .and_then(|ci| ci.payload.get("minCount").and_then(|v| v.as_int()))
                .unwrap_or(0);
            let max = branch.iter().find(|ci| ci.component == "sh:MaxCountConstraintComponent")
                .and_then(|ci| ci.payload.get("maxCount").and_then(|v| v.as_int()))
                .unwrap_or(i64::MAX / 2);
            prelude_parts.push(prelude);
            fail_conds.push(inverse_fail_cond(inv_idx, min, max));
            inv_idx += 1;
        } else {
            // Forward field branch — determine what kind
            if branch.iter().any(|ci| ci.path.len() > 1) { return None; } // multi-seg: skip
            let attr_id = local_name(path0);
            let (acc_prefix, attr) = find_attr_in_hierarchy(spec, class_name, &attr_id)?;
            let field = sanitize_field(to_snake_case(&attr.label));
            let accessor = format!("{acc_prefix}.{field}");

            let max = branch.iter().find(|ci| ci.component == "sh:MaxCountConstraintComponent")
                .and_then(|ci| ci.payload.get("maxCount").and_then(|v| v.as_int()));
            let min = branch.iter().find(|ci| ci.component == "sh:MinCountConstraintComponent")
                .and_then(|ci| ci.payload.get("minCount").and_then(|v| v.as_int()));

            let fail_cond = if max == Some(0) {
                // Field must be absent
                field_absent_cond(&attr, &accessor)?
            } else if min == Some(1) && (max == Some(1) || max.is_none()) {
                // Field must be present
                field_required_cond(&attr, &accessor)?
            } else {
                return None; // unsupported pattern
            };
            needs_obj = true;
            fail_conds.push(fail_cond);
        }
    }

    if fail_conds.is_empty() { return None; }
    let any_fail = fail_conds.join(" || ");

    let (message, severity, name_str, rule_id_str, desc_str, prop) = extract_violation_fields(c);

    let mut s = String::new();
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    for p in &prelude_parts { s.push_str(p); }
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    if needs_obj {
        writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
        writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
        writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
        writeln!(s, "            Some(o) => o, None => continue,").unwrap();
        writeln!(s, "        }};").unwrap();
    }
    writeln!(s, "        if {any_fail} {{").unwrap();
    write_violation(&mut s, class_name, &prop, &message, &severity, &name_str, &rule_id_str, &desc_str, "            ");
    writeln!(s, "        }}").unwrap();
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
    Some(s)
}

// ---------------------------------------------------------------------------
// Compound generator helpers
// ---------------------------------------------------------------------------

/// Build the prelude code that counts inverse references for one branch.
/// `path0` is the raw inverse path segment like "^cim:Terminal.ConductingEquipment".
fn build_inverse_count_prelude(spec: &CimSpecification, path0: &str, idx: usize) -> Option<String> {
    let forward_pred = &path0[1..]; // strip leading '^'
    let local = local_name(forward_pred);
    let (src_class, _) = local.split_once('.')?;
    let (_, attr) = find_attr_in_hierarchy(spec, src_class, &local)?;
    if !attr.is_association_used { return None; }
    let field = sanitize_field(to_snake_case(&attr.label));

    let mut s = String::new();
    writeln!(s, "    let mut counts{idx}: std::collections::HashMap<String, usize> = std::collections::HashMap::new();").unwrap();
    // The referrer class can be abstract — scan every concrete subclass that
    // carries the forward field (dataset.by_type only holds concrete type names).
    let mut emitted = false;
    for cls in class_and_subclasses(spec, src_class) {
        let Some((acc_prefix, _)) = find_attr_in_hierarchy(spec, &cls, &local) else { continue };
        let src_prefix = acc_prefix.replacen("obj", "src", 1);
        let src_field = format!("{src_prefix}.{field}");
        emitted = true;
        writeln!(s, "    for src_mrid in dataset.by_type.get(\"{cls}\").into_iter().flatten() {{").unwrap();
        writeln!(s, "        if let Some(src) = dataset.entries.get(src_mrid)").unwrap();
        writeln!(s, "            .and_then(|e| e.element.as_any().downcast_ref::<cimstructs::{cls}>()) {{").unwrap();
        if attr.is_list {
            writeln!(s, "            for r in &{src_field} {{").unwrap();
            writeln!(s, "                *counts{idx}.entry(r.mrid.trim_start_matches('#').to_string()).or_insert(0) += 1;").unwrap();
            writeln!(s, "            }}").unwrap();
        } else {
            writeln!(s, "            if let Some(r) = &{src_field} {{").unwrap();
            writeln!(s, "                *counts{idx}.entry(r.mrid.trim_start_matches('#').to_string()).or_insert(0) += 1;").unwrap();
            writeln!(s, "            }}").unwrap();
        }
        writeln!(s, "        }}").unwrap();
        writeln!(s, "    }}").unwrap();
    }
    if !emitted { return None; }
    Some(s)
}

/// Build the prelude for a two-segment inverse-then-forward branch:
/// `[^Class.field, Class.otherField]` (e.g. "how many Terminals refer to this
/// Clamp via Terminal.ConductingEquipment AND also have Terminal.ConnectivityNode
/// set" — used by C:452:EQ:Clamp:numberOfTerminals's sh:and). Counts, per outer
/// object, referrers for which the SECOND field also resolves — a referrer
/// missing the second field doesn't count.
fn build_inverse_forward_count_prelude(spec: &CimSpecification, path: &[String], idx: usize) -> Option<String> {
    if path.len() != 2 { return None; }
    let inv_local = local_name(&path[0][1..]); // strip leading '^'
    let (src_class, _) = inv_local.split_once('.')?;
    let fwd_local = local_name(&path[1]);
    if !fwd_local.contains('.') { return None; }

    let mut s = String::new();
    writeln!(s, "    let mut counts{idx}: std::collections::HashMap<String, usize> = std::collections::HashMap::new();").unwrap();
    let mut emitted = false;
    for cls in class_and_subclasses(spec, src_class) {
        let Some((inv_prefix, inv_attr)) = find_attr_in_hierarchy(spec, &cls, &inv_local) else { continue };
        let Some((fwd_prefix, fwd_attr)) = find_attr_in_hierarchy(spec, &cls, &fwd_local) else { continue };
        if !inv_attr.is_association_used || !fwd_attr.is_association_used { continue; }
        let inv_field = sanitize_field(to_snake_case(&inv_attr.label));
        let inv_src_field = format!("{}.{inv_field}", inv_prefix.replacen("obj", "src", 1));
        let fwd_field = sanitize_field(to_snake_case(&fwd_attr.label));
        let fwd_src_field = format!("{}.{fwd_field}", fwd_prefix.replacen("obj", "src", 1));
        let fwd_present = if fwd_attr.is_list {
            format!("!{fwd_src_field}.is_empty()")
        } else {
            format!("{fwd_src_field}.is_some()")
        };
        emitted = true;
        writeln!(s, "    for src_mrid in dataset.by_type.get(\"{cls}\").into_iter().flatten() {{").unwrap();
        writeln!(s, "        if let Some(src) = dataset.entries.get(src_mrid)").unwrap();
        writeln!(s, "            .and_then(|e| e.element.as_any().downcast_ref::<cimstructs::{cls}>()) {{").unwrap();
        writeln!(s, "            if {fwd_present} {{").unwrap();
        if inv_attr.is_list {
            writeln!(s, "                for r in &{inv_src_field} {{").unwrap();
            writeln!(s, "                    *counts{idx}.entry(r.mrid.trim_start_matches('#').to_string()).or_insert(0) += 1;").unwrap();
            writeln!(s, "                }}").unwrap();
        } else {
            writeln!(s, "                if let Some(r) = &{inv_src_field} {{").unwrap();
            writeln!(s, "                    *counts{idx}.entry(r.mrid.trim_start_matches('#').to_string()).or_insert(0) += 1;").unwrap();
            writeln!(s, "                }}").unwrap();
        }
        writeln!(s, "            }}").unwrap();
        writeln!(s, "        }}").unwrap();
        writeln!(s, "    }}").unwrap();
    }
    if !emitted { return None; }
    Some(s)
}

fn inverse_fail_cond(idx: usize, min: i64, max: i64) -> String {
    let count = format!("counts{idx}.get(mrid.as_str()).copied().unwrap_or(0)");
    if min == max {
        format!("{count} != {min}")
    } else if max == i64::MAX / 2 {
        format!("{count} < {min}")
    } else if min == 0 {
        format!("{count} > {max}")
    } else {
        format!("{{ let c = {count}; c < {min} || c > {max} }}")
    }
}

/// Violation condition for "field must be absent" (sh:maxCount 0).
fn field_absent_cond(attr: &CimAttribute, accessor: &str) -> Option<String> {
    if attr.is_list {
        Some(format!("!{accessor}.is_empty()"))
    } else if attr.is_primitive || attr.is_cim_datatype {
        Some(match attr.lang_type.as_str() {
            "String" => format!("!{accessor}.is_empty()"),
            _ => format!("{accessor}.is_some()"),  // Option<f64>, Option<i64>, Option<bool>
        })
    } else if attr.is_enum_value {
        Some(format!("{accessor}.is_some()"))
    } else {
        Some(format!("{accessor}.is_some()"))  // Option<MridRef>
    }
}

/// Violation condition for "field must be present" (sh:minCount 1 + maxCount 1).
fn field_required_cond(attr: &CimAttribute, accessor: &str) -> Option<String> {
    if attr.is_list {
        Some(format!("{accessor}.is_empty()"))
    } else if attr.is_primitive || attr.is_cim_datatype {
        Some(match attr.lang_type.as_str() {
            "String" => format!("{accessor}.is_empty()"),
            _ => format!("{accessor}.is_none()"),
        })
    } else if attr.is_enum_value {
        Some(format!("{accessor}.is_none()"))
    } else {
        Some(format!("{accessor}.is_none()"))
    }
}

fn extract_violation_fields(c: &ConstraintInfo) -> (String, String, String, String, String, String) {
    fn esc(x: &str) -> String { x.replace('\\', "\\\\").replace('"', "\\\"") }
    let message     = esc(&c.message);
    let severity    = if c.severity.is_empty() { "sh:Violation".to_string() } else { c.severity.clone() };
    let name_str    = esc(&c.name);
    let rule_id_str = esc(&c.rule_id);
    let desc_str    = esc(&c.description);
    let prop        = esc(&c.name);
    (message, severity, name_str, rule_id_str, desc_str, prop)
}

fn write_fn_header(s: &mut String, fn_name: &str, class_name: &str) {
    writeln!(s, "pub fn {fn_name}(dataset: &CimDataset) -> Vec<Violation> {{").unwrap();
    writeln!(s, "    let mut violations = Vec::new();").unwrap();
    writeln!(s, "    for mrid in dataset.by_type.get(\"{class_name}\").into_iter().flatten() {{").unwrap();
    writeln!(s, "        let entry = &dataset.entries[mrid];").unwrap();
    writeln!(s, "        let obj = match entry.element.as_any()").unwrap();
    writeln!(s, "            .downcast_ref::<cimstructs::{class_name}>() {{").unwrap();
    writeln!(s, "            Some(o) => o, None => continue,").unwrap();
    writeln!(s, "        }};").unwrap();
}

fn write_fn_footer(s: &mut String) {
    writeln!(s, "    }}").unwrap();
    writeln!(s, "    violations").unwrap();
    writeln!(s, "}}").unwrap();
}

fn write_violation(s: &mut String, class_name: &str, prop: &str, message: &str, severity: &str, name_str: &str, rule_id_str: &str, desc_str: &str, indent: &str) {
    writeln!(s, "{indent}violations.push(Violation {{").unwrap();
    writeln!(s, "{indent}    object_id:   mrid.clone(),").unwrap();
    writeln!(s, "{indent}    rule_id:     \"{rule_id_str}\".to_string(),").unwrap();
    writeln!(s, "{indent}    class:       \"{class_name}\".to_string(),").unwrap();
    writeln!(s, "{indent}    property:    \"{prop}\".to_string(),").unwrap();
    writeln!(s, "{indent}    message:     \"{message}\".to_string(),").unwrap();
    writeln!(s, "{indent}    severity:    \"{severity}\".to_string(),").unwrap();
    writeln!(s, "{indent}    name:        \"{name_str}\".to_string(),").unwrap();
    writeln!(s, "{indent}    description: \"{desc_str}\".to_string(),").unwrap();
    writeln!(s, "{indent}}});").unwrap();
}

fn dedup_fn_name(raw_name: String, used: &std::collections::HashSet<String>) -> String {
    if !used.contains(&raw_name) {
        return raw_name;
    }
    let mut n = 2usize;
    loop {
        let candidate = format!("{raw_name}_{n}");
        if !used.contains(&candidate) { return candidate; }
        n += 1;
    }
}

// ---------------------------------------------------------------------------
// Class hierarchy helpers
// ---------------------------------------------------------------------------

fn is_subtype_of(spec: &CimSpecification, type_name: &str, ancestor: &str) -> bool {
    let mut current = type_name.to_string();
    let mut visited = std::collections::HashSet::new();
    loop {
        if !visited.insert(current.clone()) {
            return false;
        }
        match spec.types.get(&current) {
            Some(t) => {
                if t.super_type.is_empty() || t.super_type == current {
                    return false;
                }
                if t.super_type == ancestor {
                    return true;
                }
                current = t.super_type.clone();
            }
            None => return false,
        }
    }
}

fn class_and_subclasses(spec: &CimSpecification, class: &str) -> Vec<String> {
    let mut result: Vec<String> = spec.types
        .keys()
        .filter(|name| name.as_str() == class || is_subtype_of(spec, name, class))
        .cloned()
        .collect();
    result.sort();
    result
}