cadmpeg-ir 0.6.5

CAD data model, validation, diffing, and codec API for cadmpeg.
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
// SPDX-License-Identifier: Apache-2.0
//! Neutral product structure and occurrence instancing.

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub(crate) mod assembly_graph;

use cadmpeg_core::text::NonBlankString;

use crate::ids::{BodyId, OccurrenceId, ProductDefinitionId};
use crate::scalar::FiniteReal;
use crate::transform::Transform;

crate::ids::id_type!(
    /// Stable assembly-joint identity.
    JointId, compose
);

/// Role of a component definition in the product tree.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ProductDefinitionKind {
    /// Product part or assembly container.
    Part,
    /// Generic ordered object group.
    Group,
    /// Container whose children are link instances.
    LinkGroup,
    /// Reusable leaf object without container semantics.
    Object,
}

/// A reusable product definition or structural container.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ProductDefinition {
    /// Globally unique definition identity.
    pub id: ProductDefinitionId,
    /// Structural role.
    pub kind: ProductDefinitionKind,
    /// Stable source object name used by product/BOM tooling.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_name"
    )]
    pub source_name: Option<String>,
    /// User-visible component label, when distinct from the source name.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_label"
    )]
    pub label: Option<String>,
    /// User-maintained BOM description.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_description"
    )]
    pub description: Option<String>,
    /// User-maintained part or stock number.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_part_number"
    )]
    pub part_number: Option<String>,
    /// Additional persisted BOM identity fields by exact property name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    #[serde(deserialize_with = "cadmpeg_core::distinct_keys::btree_map")]
    pub bom_properties: BTreeMap<NonBlankString, String>,
    /// Shape bodies owned by this reusable definition.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bodies: Vec<BodyId>,
    /// Format-native object supplying this definition.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// Local or unresolved external prototype of an occurrence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "scope", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum PrototypeReference {
    /// Prototype resolves to a definition in this document.
    Local {
        /// Resolved component definition.
        definition: ProductDefinitionId,
    },
    /// Prototype belongs to another document, loaded or not.
    External {
        /// Persisted external-document reference and unresolved state.
        document: ExternalDocument,
        /// Persisted object identity within that document.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_object"
        )]
        object: Option<String>,
    },
    /// The source intentionally carries no resolvable prototype.
    Unresolved {},
}

/// Typed identity or explicit absence of an external document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "resolution", rename_all = "snake_case", deny_unknown_fields)]
pub enum ExternalDocument {
    /// Non-empty file path stored by the source.
    Path {
        /// Persisted file path.
        path: NonBlankString,
    },
    /// Non-empty document identity stored by the source.
    DocumentId {
        /// Persisted document identity.
        document_id: NonBlankString,
    },
    /// Persisted reference was empty or structurally unusable.
    Missing {},
}

impl ExternalDocument {
    /// Constructs a path reference, or [`Self::Missing`] when the path is empty.
    pub fn path(path: impl Into<String>) -> Self {
        match NonBlankString::new(path) {
            Some(path) => Self::Path { path },
            None => Self::Missing {},
        }
    }

    /// Constructs a document-id reference, or [`Self::Missing`] when the id is empty.
    pub fn document_id(document_id: impl Into<String>) -> Self {
        match NonBlankString::new(document_id) {
            Some(document_id) => Self::DocumentId { document_id },
            None => Self::Missing {},
        }
    }
}

/// Copy-on-change ownership behavior of a link.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    tag = "policy",
    content = "native_policy",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum CopyOnChangePolicy {
    /// Link follows its prototype without making an owned copy.
    Disabled,
    /// Copy is created when a marked prototype property changes.
    Enabled,
    /// Link currently owns a changed copy.
    Owned,
    /// Owned copy continues tracking its original source.
    Tracking,
    /// Future policy retained without reinterpretation.
    Native(String),
}

/// Position of an occurrence in the canonical placed-instance tree.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum OccurrenceParent {
    /// A root occurrence has no containing occurrence.
    Root {},
    /// A child is placed inside another occurrence.
    Occurrence {
        /// Containing occurrence identity.
        occurrence: OccurrenceId,
    },
}

/// One placed use, including an element of a link array.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Occurrence {
    /// Globally unique instance identity.
    pub id: OccurrenceId,
    /// Reusable definition used by this instance.
    pub prototype: PrototypeReference,
    /// Position in the occurrence tree.
    pub parent: OccurrenceParent,
    /// Stable zero-based source order within the parent.
    pub ordinal: u32,
    /// Placement relative to the direct container.
    pub transform: Transform,
    /// Linked prototype placement contribution when link-transform policy applies.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_linked_prototype"
    )]
    pub linked_prototype: Option<Transform>,
    /// Per-axis instance scale.
    #[serde(deserialize_with = "deserialize_occurrence_scale")]
    pub scale: [FiniteReal; 3],
    /// Source occurrence identifier or display name.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_name"
    )]
    pub name: Option<String>,
    /// Per-element visibility override.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_visible"
    )]
    pub visible: Option<bool>,
    /// `FreeCAD` `App::Link`-specific occurrence state.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_link"
    )]
    pub link: Option<LinkState>,
    /// Format-native object supplying this instance.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// One member of an `App::Link` occurrence state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum LinkMember {
    /// One persisted prototype subelement selection.
    LinkedSubelement {
        /// Subelement path inside the prototype.
        subelement: String,
    },
    /// The explicit application object representing this array element.
    ElementComponent {
        /// Component definition.
        component: ProductDefinitionId,
    },
    /// Whether this link claims its prototype in the source tree.
    ClaimChild {
        /// The claim the source recorded.
        claim: bool,
    },
    /// Copy-on-change ownership state.
    CopyOnChange {
        /// The recorded ownership state.
        state: CopyOnChange,
    },
}

/// `FreeCAD` `App::Link`-specific occurrence state.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(with = "LinkStateWire"))]
#[serde(try_from = "LinkStateWire", into = "LinkStateWire")]
pub struct LinkState {
    linked_subelements: Vec<String>,
    element_component: Option<ProductDefinitionId>,
    claim_child: Option<bool>,
    copy_on_change: Option<CopyOnChange>,
}

/// `FreeCAD` `App::Link`-specific occurrence state.
///
/// The wire carries one member list, so "all four members are absent" has no
/// spelling: the only emptiness admission is over that one list, and the three
/// members a link states at most once are refused only when repeated.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "LinkState"))]
#[serde(deny_unknown_fields)]
struct LinkStateWire {
    /// The link members the source recorded.
    members: Vec<LinkMember>,
}

impl TryFrom<LinkStateWire> for LinkState {
    type Error = &'static str;

    fn try_from(wire: LinkStateWire) -> Result<Self, Self::Error> {
        if wire.members.is_empty() {
            return Err("link state states at least one member");
        }
        let mut state = Self {
            linked_subelements: Vec::new(),
            element_component: None,
            claim_child: None,
            copy_on_change: None,
        };
        for member in wire.members {
            match member {
                LinkMember::LinkedSubelement { subelement } => {
                    state.linked_subelements.push(subelement);
                }
                LinkMember::ElementComponent { component } => {
                    if state.element_component.replace(component).is_some() {
                        return Err("link state states element_component once");
                    }
                }
                LinkMember::ClaimChild { claim } => {
                    if state.claim_child.replace(claim).is_some() {
                        return Err("link state states claim_child once");
                    }
                }
                LinkMember::CopyOnChange {
                    state: copy_on_change,
                } => {
                    if state.copy_on_change.replace(copy_on_change).is_some() {
                        return Err("link state states copy_on_change once");
                    }
                }
            }
        }
        Ok(state)
    }
}

impl LinkState {
    /// Nonempty link state, or absence when all members are empty.
    pub fn new(
        linked_subelements: Vec<String>,
        element_component: Option<ProductDefinitionId>,
        claim_child: Option<bool>,
        copy_on_change: Option<CopyOnChange>,
    ) -> Option<Self> {
        if linked_subelements.is_empty()
            && element_component.is_none()
            && claim_child.is_none()
            && copy_on_change.is_none()
        {
            return None;
        }
        Some(Self {
            linked_subelements,
            element_component,
            claim_child,
            copy_on_change,
        })
    }

    /// Persisted prototype subelement selection.
    pub fn linked_subelements(&self) -> &[String] {
        &self.linked_subelements
    }

    /// Explicit application object representing this array element.
    pub fn element_component(&self) -> Option<&ProductDefinitionId> {
        self.element_component.as_ref()
    }

    /// Whether this link claims its prototype in the source tree.
    ///
    /// `FreeCAD` states `LinkClaimChild` as an optional `App::PropertyBool`,
    /// so an absent property and a stated `false` are separate source facts
    /// and reach separate wire member lists.
    pub const fn claim_child(&self) -> Option<bool> {
        self.claim_child
    }

    /// Copy-on-change ownership state.
    pub fn copy_on_change(&self) -> Option<&CopyOnChange> {
        self.copy_on_change.as_ref()
    }
}

/// Copy-on-change ownership state carried by an `App::Link` occurrence.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CopyOnChange {
    /// Ownership policy.
    pub policy: CopyOnChangePolicy,
    /// Original component or external object tracked by copy-on-change.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source"
    )]
    pub source: Option<PrototypeReference>,
    /// Internal component or external object holding owned copies.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_group"
    )]
    pub group: Option<PrototypeReference>,
    /// Whether the tracked source was persisted as changed.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_touched"
    )]
    pub touched: Option<bool>,
}

crate::units::named_field!(deserialize_occurrence_scale, [FiniteReal; 3], "scale");

impl Occurrence {
    /// Placement after applying the linked prototype contribution, when present.
    pub fn effective_transform(&self) -> Result<Transform, crate::transform::TransformError> {
        self.linked_prototype
            .map_or(Ok(self.transform), |prototype| {
                self.transform.compose(prototype)
            })
    }
}

/// Failure to construct a canonical occurrence graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssemblyGraphError {
    /// Two occurrences carry the same identity.
    DuplicateOccurrence(OccurrenceId),
    /// An occurrence names a parent that is not present.
    MissingParent {
        /// Child occurrence.
        occurrence: OccurrenceId,
        /// Missing parent occurrence.
        parent: OccurrenceId,
    },
    /// Parent links contain a cycle.
    ParentCycle(OccurrenceId),
    /// An occurrence placement cannot be composed into a finite transform.
    Transform {
        /// The occurrence whose placement failed.
        occurrence: OccurrenceId,
        /// The transform arithmetic failure.
        source: crate::transform::TransformError,
    },
}

impl std::fmt::Display for AssemblyGraphError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateOccurrence(id) => write!(formatter, "duplicate occurrence {id}"),
            Self::MissingParent { occurrence, parent } => {
                write!(
                    formatter,
                    "occurrence {occurrence} has missing parent {parent}"
                )
            }
            Self::ParentCycle(id) => write!(formatter, "occurrence parent cycle at {id}"),
            Self::Transform { occurrence, source } => {
                write!(formatter, "occurrence {occurrence}: {source}")
            }
        }
    }
}

impl std::error::Error for AssemblyGraphError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Transform { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Validated lookup view over a canonical occurrence tree.
pub struct AssemblyGraph<'a> {
    occurrences: assembly_graph::Facts<'a>,
}

#[cfg(test)]
mod tests {
    mod joints;
    mod occurrences;
    use super::{
        AssemblyGraph, AssemblyGraphError, CopyOnChange, CopyOnChangePolicy, ExternalDocument,
        JointLimits, JointOperand, LinkState, Occurrence, OccurrenceParent, PrototypeReference,
    };
    use crate::ids::{OccurrenceId, ProductDefinitionId};
    use crate::transform::Transform;

    #[test]
    fn a_blank_selection_id_has_no_wire_spelling() {
        assert!(serde_json::from_value::<crate::features::SelectionMember>(
            serde_json::json!({"kind": "face", "id": "   "})
        )
        .is_err());
        assert!(serde_json::from_value::<crate::features::SelectionMember>(
            serde_json::json!({"kind": "face", "id": " a "})
        )
        .is_ok());
        let topology = |id: &str| {
            serde_json::json!({
                "id": "test:model:feature-result#1",
                "output_of": "test:test:feature#1",
                "members": [{"kind": "face", "id": id}],
            })
        };
        assert!(
            serde_json::from_value::<crate::features::FeatureResultTopology>(topology("   "))
                .is_err()
        );
        assert!(
            serde_json::from_value::<crate::features::FeatureResultTopology>(topology(" a "))
                .is_ok()
        );
    }

    #[test]
    fn an_external_document_states_its_resolution_and_carries_one_identity() {
        let path = ExternalDocument::path("parts/widget.FCStd");
        let path_wire = serde_json::to_value(&path).unwrap();
        assert_eq!(
            path_wire,
            serde_json::json!({
                "resolution": "path",
                "path": "parts/widget.FCStd"
            })
        );
        assert_eq!(
            serde_json::from_value::<ExternalDocument>(path_wire.clone()).unwrap(),
            path
        );

        let document_id = ExternalDocument::document_id("document-7");
        let document_id_wire = serde_json::to_value(&document_id).unwrap();
        assert_eq!(
            document_id_wire,
            serde_json::json!({"resolution": "document_id", "document_id": "document-7"})
        );
        assert_eq!(
            serde_json::from_value::<ExternalDocument>(document_id_wire).unwrap(),
            document_id
        );

        let missing = ExternalDocument::Missing {};
        assert_eq!(ExternalDocument::path(""), missing);
        assert_eq!(ExternalDocument::document_id(""), missing);
        let missing_wire = serde_json::to_value(&missing).unwrap();
        assert_eq!(missing_wire, serde_json::json!({"resolution": "missing"}));
        assert_eq!(
            serde_json::from_value::<ExternalDocument>(missing_wire).unwrap(),
            missing
        );

        for (invalid, named) in [
            (
                serde_json::json!({"resolution": "path", "path": ""}),
                "must not be blank",
            ),
            (
                serde_json::json!({"resolution": "path", "path": "   "}),
                "must not be blank",
            ),
            (
                serde_json::json!({
                    "resolution": "path",
                    "path": "parts/widget.FCStd",
                    "document_id": "document-7"
                }),
                "document_id",
            ),
            (
                serde_json::json!({"resolution": "missing", "path": ""}),
                "path",
            ),
            (serde_json::json!({"resolution": "path"}), "path"),
        ] {
            let error = serde_json::from_value::<ExternalDocument>(invalid)
                .unwrap_err()
                .to_string();
            assert!(error.contains(named), "{error}");
        }
    }

    #[test]
    fn a_joint_operand_states_the_container_that_owns_its_object() {
        let root = JointOperand::root("Body1", Vec::new());
        let root_wire = serde_json::to_value(&root).unwrap();
        assert_eq!(
            root_wire,
            serde_json::json!({"container": {"container": "root"}, "object": "Body1"})
        );
        assert_eq!(
            serde_json::from_value::<JointOperand>(root_wire.clone()).unwrap(),
            root
        );

        let occurrence_id = OccurrenceId::mint("test:model:occurrence#0").unwrap();
        let occurrence = JointOperand::occurrence(occurrence_id.clone(), "Body1", Vec::new());
        let occurrence_wire = serde_json::to_value(&occurrence).unwrap();
        assert_eq!(occurrence_wire["container"]["container"], "occurrence");
        assert_eq!(
            serde_json::from_value::<JointOperand>(occurrence_wire.clone()).unwrap(),
            occurrence
        );

        let external = JointOperand::external(
            ExternalDocument::path("parts/widget.FCStd"),
            "Body1",
            Vec::new(),
        );
        let external_wire = serde_json::to_value(&external).unwrap();
        assert_eq!(external_wire["container"]["container"], "external");
        assert_eq!(
            serde_json::from_value::<JointOperand>(external_wire).unwrap(),
            external
        );

        let mut both = occurrence_wire;
        both["container"]["external_document"] = serde_json::json!({"resolution": "missing"});
        let error = serde_json::from_value::<JointOperand>(both)
            .unwrap_err()
            .to_string();
        assert!(error.contains("external_document"), "{error}");

        let mut stray = root_wire.clone();
        stray["container"]["occurrence"] = serde_json::json!(occurrence_id.as_str());
        let error = serde_json::from_value::<JointOperand>(stray)
            .unwrap_err()
            .to_string();
        assert!(error.contains("occurrence"), "{error}");

        let mut without_object = root_wire;
        without_object.as_object_mut().unwrap().remove("object");
        let error = serde_json::from_value::<JointOperand>(without_object)
            .unwrap_err()
            .to_string();
        assert!(error.contains("object"), "{error}");
    }

    fn translation(x: f64) -> Transform {
        Transform::affine([
            [1.0, 0.0, 0.0, x],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
        ])
        .expect("translation is affine")
    }

    fn occurrence(id: &str, parent: OccurrenceParent, x: f64) -> Occurrence {
        Occurrence {
            id: OccurrenceId::mint(id).expect("valid identity"),
            prototype: PrototypeReference::Unresolved {},
            parent,
            ordinal: 0,
            transform: translation(x),
            linked_prototype: None,
            scale: [crate::scalar::FiniteReal::ONE; 3],
            name: None,
            visible: None,
            link: None,
            native_ref: None,
        }
    }

    #[test]
    fn resolves_parent_chains_and_conditional_prototype_placement() {
        let root = occurrence("test:model:entity#root", OccurrenceParent::Root {}, 1.0);
        let mut child = occurrence(
            "test:model:entity#child",
            OccurrenceParent::Occurrence {
                occurrence: root.id.clone(),
            },
            2.0,
        );
        child.linked_prototype = Some(translation(10.0));
        let occurrences = [child, root];
        let mut graph = AssemblyGraph::new(&occurrences).expect("valid graph");
        assert_eq!(
            crate::index::public_result(super::assembly_graph::resolve_occurrence(
                graph
                    .occurrence(
                        &OccurrenceId::mint("test:model:entity#child").expect("valid identity")
                    )
                    .unwrap(),
                &mut graph.occurrences,
                &crate::index::PublicStorage
            ))
            .expect("resolved child")
            .rows()[0][3],
            13.0
        );
    }

    #[test]
    fn an_absent_linked_prototype_key_is_the_only_spelling_of_absence() {
        let plain = occurrence(
            "test:model:occurrence#plain",
            OccurrenceParent::Root {},
            1.0,
        );
        let plain_wire = serde_json::to_value(&plain).expect("plain occurrence wire");
        assert!(plain_wire.get("linked_prototype").is_none());
        assert_eq!(
            serde_json::from_value::<Occurrence>(plain_wire).unwrap(),
            plain
        );

        let mut linked = plain;
        linked.linked_prototype = Some(translation(10.0));
        let linked_wire = serde_json::to_value(&linked).expect("linked occurrence wire");
        assert_eq!(
            linked_wire.get("linked_prototype"),
            Some(&serde_json::to_value(translation(10.0)).unwrap())
        );
        assert_eq!(
            serde_json::from_value::<Occurrence>(linked_wire).unwrap(),
            linked
        );

        let mut identity = serde_json::to_value(&linked).unwrap();
        identity["linked_prototype"] = serde_json::to_value(Transform::identity()).unwrap();
        assert_eq!(
            serde_json::from_value::<Occurrence>(identity)
                .unwrap()
                .linked_prototype,
            Some(Transform::identity())
        );
    }

    #[test]
    fn joint_limits_admit_only_finite_ordered_bounds() {
        assert!(JointLimits::new(None, None).is_none());
        assert!(JointLimits::new(Some(2.0), Some(1.0)).is_none());
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            assert!(JointLimits::new(Some(value), None).is_none());
            assert!(JointLimits::new(None, Some(value)).is_none());
        }
        for (minimum, maximum) in [
            (Some(-2.0), None),
            (None, Some(-1.0)),
            (Some(0.0), Some(0.0)),
        ] {
            let limits = JointLimits::new(minimum, maximum).unwrap();
            assert_eq!(
                serde_json::from_value::<JointLimits>(serde_json::to_value(&limits).unwrap())
                    .unwrap(),
                limits
            );
        }
    }

    #[test]
    fn joint_limits_from_parts_checks_only_presence_and_order() {
        let lower = crate::scalar::FiniteReal::new(-2.0).unwrap();
        let upper = crate::scalar::FiniteReal::new(1.0).unwrap();
        assert!(JointLimits::from_parts(None, None).is_none());
        assert!(JointLimits::from_parts(Some(upper), Some(lower)).is_none());
        assert_eq!(
            JointLimits::from_parts(Some(lower), Some(upper)),
            Some(JointLimits::Range(
                super::JointLimitRange::new(lower, upper).unwrap()
            ))
        );
    }

    #[test]
    fn a_joint_limit_range_owns_the_order_of_its_bounds() {
        use super::JointLimitRange;
        use crate::scalar::FiniteReal;

        let bound = |value: f64| FiniteReal::new(value).unwrap();
        assert!(JointLimitRange::new(bound(2.0), bound(1.0)).is_none());
        let equal = JointLimitRange::new(bound(1.0), bound(1.0)).unwrap();
        assert_eq!([equal.minimum(), equal.maximum()], [bound(1.0), bound(1.0)]);
        let range = JointLimitRange::new(bound(-2.0), bound(3.0)).unwrap();
        assert_eq!(
            [range.minimum(), range.maximum()],
            [bound(-2.0), bound(3.0)]
        );

        let wire = serde_json::to_value(JointLimits::Range(range)).unwrap();
        assert_eq!(
            wire,
            serde_json::json!({"bounds": "range", "minimum": -2.0, "maximum": 3.0})
        );
        assert_eq!(
            serde_json::from_value::<JointLimits>(wire).unwrap(),
            JointLimits::Range(range)
        );
        let error = serde_json::from_value::<JointLimits>(
            serde_json::json!({"bounds": "range", "minimum": 2.0, "maximum": 1.0}),
        )
        .unwrap_err()
        .to_string();
        assert!(
            error.contains("joint limit range must be ordered"),
            "{error}"
        );
    }

    #[test]
    fn empty_link_state_is_absent() {
        assert!(LinkState::new(Vec::new(), None, None, None).is_none());
        assert!(LinkState::new(Vec::new(), None, Some(false), None).is_some());
        let plain = occurrence(
            "test:model:occurrence#empty-link",
            OccurrenceParent::Root {},
            0.0,
        );
        let wire = serde_json::to_value(&plain).unwrap();
        assert!(serde_json::from_value::<Occurrence>(wire)
            .unwrap()
            .link
            .is_none());
    }

    #[test]
    fn the_link_state_is_one_nested_object_with_its_own_copy_on_change() {
        let mut linked = occurrence("test:model:occurrence#link", OccurrenceParent::Root {}, 1.0);
        linked.link = LinkState::new(
            vec!["Face1".into()],
            Some(ProductDefinitionId::mint("test:model:product#element").expect("valid identity")),
            Some(true),
            Some(CopyOnChange {
                policy: CopyOnChangePolicy::Owned,
                source: Some(PrototypeReference::Local {
                    definition: ProductDefinitionId::mint("test:model:product#source")
                        .expect("valid identity"),
                }),
                group: Some(PrototypeReference::Local {
                    definition: ProductDefinitionId::mint("test:model:product#group")
                        .expect("valid identity"),
                }),
                touched: Some(true),
            }),
        );
        let wire = serde_json::to_value(&linked).expect("App::Link occurrence wire");
        assert_eq!(
            wire["link"]["members"],
            serde_json::json!([
                {"kind": "linked_subelement", "subelement": "Face1"},
                {"kind": "element_component", "component": "test:model:product#element"},
                {"kind": "claim_child", "claim": true},
                {"kind": "copy_on_change", "state": {
                    "policy": {"policy": "owned"},
                    "source": {"scope": "local", "definition": "test:model:product#source"},
                    "group": {"scope": "local", "definition": "test:model:product#group"},
                    "touched": true
                }}
            ])
        );
        assert_eq!(
            serde_json::from_value::<Occurrence>(wire.clone()).unwrap(),
            linked
        );

        let mut without_policy = wire.clone();
        without_policy["link"]["members"][3]["state"]
            .as_object_mut()
            .expect("a copy-on-change object")
            .remove("policy");
        let error = serde_json::from_value::<Occurrence>(without_policy)
            .unwrap_err()
            .to_string();
        assert!(error.contains("policy"), "{error}");

        let mut bogus = wire;
        bogus["link"]["members"][3]["state"]["zz_bogus"] = serde_json::json!(1);
        let error = serde_json::from_value::<Occurrence>(bogus)
            .unwrap_err()
            .to_string();
        assert!(error.contains("zz_bogus"), "{error}");

        let mut empty = serde_json::to_value(occurrence(
            "test:model:occurrence#empty-link",
            OccurrenceParent::Root {},
            1.0,
        ))
        .unwrap();
        empty["link"] = serde_json::json!({"members": []});
        assert!(serde_json::from_value::<Occurrence>(empty).is_err());
    }

    #[test]
    fn rejects_duplicate_missing_and_cyclic_parent_links() {
        let duplicate = occurrence("test:model:entity#same", OccurrenceParent::Root {}, 0.0);
        assert!(matches!(
            AssemblyGraph::new(&[duplicate.clone(), duplicate]),
            Err(AssemblyGraphError::DuplicateOccurrence(_))
        ));

        let missing = occurrence(
            "test:model:entity#child",
            OccurrenceParent::Occurrence {
                occurrence: OccurrenceId::mint("test:model:entity#missing")
                    .expect("valid identity"),
            },
            0.0,
        );
        assert!(matches!(
            AssemblyGraph::new(&[missing]),
            Err(AssemblyGraphError::MissingParent { .. })
        ));

        let first = occurrence(
            "test:model:entity#first",
            OccurrenceParent::Occurrence {
                occurrence: OccurrenceId::mint("test:model:entity#second").expect("valid identity"),
            },
            0.0,
        );
        let second = occurrence(
            "test:model:entity#second",
            OccurrenceParent::Occurrence {
                occurrence: OccurrenceId::mint("test:model:entity#first").expect("valid identity"),
            },
            0.0,
        );
        assert!(matches!(
            AssemblyGraph::new(&[first, second]),
            Err(AssemblyGraphError::ParentCycle(_))
        ));
    }
}

impl<'a> AssemblyGraph<'a> {
    /// Validates parent links and every composed occurrence transform.
    pub fn new(occurrences: &'a [Occurrence]) -> Result<Self, AssemblyGraphError> {
        crate::index::public_result(assembly_graph::build(
            occurrences,
            &crate::index::PublicStorage,
        ))
        .map(|occurrences| Self { occurrences })
        .map_err(|error| match error {
            assembly_graph::GraphError::Duplicate(id) => {
                AssemblyGraphError::DuplicateOccurrence(id.clone())
            }
            assembly_graph::GraphError::Missing { occurrence, parent } => {
                AssemblyGraphError::MissingParent {
                    occurrence: occurrence.clone(),
                    parent: parent.clone(),
                }
            }
            assembly_graph::GraphError::Cycle(id) => AssemblyGraphError::ParentCycle(id.clone()),
            assembly_graph::GraphError::Transform { occurrence, source } => {
                AssemblyGraphError::Transform {
                    occurrence: occurrence.clone(),
                    source,
                }
            }
        })
    }

    /// Returns an occurrence by identity.
    pub fn occurrence(&self, id: &OccurrenceId) -> Option<&'a Occurrence> {
        self.occurrences.occurrence(id)
    }
}

/// Container that owns a joint operand object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "container", rename_all = "snake_case", deny_unknown_fields)]
pub enum OperandContainer {
    /// Object in the current document root.
    Root {},
    /// Object in a placed local occurrence.
    Occurrence {
        /// Placed local occurrence that owns the object.
        occurrence: OccurrenceId,
        /// Native keys of the nested occurrences, outermost first, that lead
        /// from the prototype of `occurrence` to the document that owns the
        /// object. Empty when the prototype of `occurrence` owns the object.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        occurrence_path: Vec<String>,
    },
    /// Object in an external document.
    External {
        /// External document that owns the object.
        external_document: ExternalDocument,
    },
}

/// One connector operand and its selected native subelements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct JointOperand {
    /// Container that owns the object.
    pub container: OperandContainer,
    /// Exact referenced application object identity.
    pub object: String,
    /// Ordered persistent object/element paths.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subelements: Vec<String>,
}

impl JointOperand {
    /// Constructs an operand owned by the current document root.
    pub fn root(object: impl Into<String>, subelements: Vec<String>) -> Self {
        Self {
            container: OperandContainer::Root {},
            object: object.into(),
            subelements,
        }
    }

    /// Constructs an operand owned by a local occurrence.
    pub fn occurrence(
        occurrence: OccurrenceId,
        object: impl Into<String>,
        subelements: Vec<String>,
    ) -> Self {
        Self::nested_occurrence(occurrence, Vec::new(), object, subelements)
    }

    /// Constructs an operand owned by a document nested below a local
    /// occurrence. `occurrence_path` lists the native keys of the nested
    /// occurrences, outermost first.
    pub fn nested_occurrence(
        occurrence: OccurrenceId,
        occurrence_path: Vec<String>,
        object: impl Into<String>,
        subelements: Vec<String>,
    ) -> Self {
        Self {
            container: OperandContainer::Occurrence {
                occurrence,
                occurrence_path,
            },
            object: object.into(),
            subelements,
        }
    }

    /// Constructs an operand owned by an external document.
    pub fn external(
        document: ExternalDocument,
        object: impl Into<String>,
        subelements: Vec<String>,
    ) -> Self {
        Self {
            container: OperandContainer::External {
                external_document: document,
            },
            object: object.into(),
            subelements,
        }
    }
}

/// Enabled bounds for one joint degree of freedom.
///
/// Each arm names the bounds the source enabled, so "neither bound" has no
/// spelling. The two-bound arm holds a [`JointLimitRange`], which owns the
/// order of its bounds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "JointLimitsWire", into = "JointLimitsWire")]
pub enum JointLimits {
    /// Only the lower bound is enabled.
    Minimum {
        /// Lower bound.
        minimum: FiniteReal,
    },
    /// Only the upper bound is enabled.
    Maximum {
        /// Upper bound.
        maximum: FiniteReal,
    },
    /// Both bounds are enabled, in order.
    Range(JointLimitRange),
}

/// Finite lower and upper joint bounds with the upper bound at or above the
/// lower bound.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct JointLimitRange {
    minimum: FiniteReal,
    maximum: FiniteReal,
}

impl JointLimitRange {
    /// Admit bounds whose upper bound is at or above the lower bound.
    #[must_use]
    pub fn new(minimum: FiniteReal, maximum: FiniteReal) -> Option<Self> {
        (minimum.get() <= maximum.get()).then_some(Self { minimum, maximum })
    }

    /// Return the lower bound.
    #[must_use]
    pub const fn minimum(self) -> FiniteReal {
        self.minimum
    }

    /// Return the upper bound, at or above [`Self::minimum`].
    #[must_use]
    pub const fn maximum(self) -> FiniteReal {
        self.maximum
    }
}

impl JointLimits {
    /// Constructs finite ordered limits with at least one enabled bound.
    pub fn new(minimum: Option<f64>, maximum: Option<f64>) -> Option<Self> {
        let minimum = match minimum {
            None => None,
            Some(value) => Some(FiniteReal::new(value)?),
        };
        let maximum = match maximum {
            None => None,
            Some(value) => Some(FiniteReal::new(value)?),
        };
        Self::from_parts(minimum, maximum)
    }

    /// Build from admitted bounds; check only presence and order.
    pub fn from_parts(minimum: Option<FiniteReal>, maximum: Option<FiniteReal>) -> Option<Self> {
        match (minimum, maximum) {
            (None, None) => None,
            (Some(minimum), None) => Some(Self::Minimum { minimum }),
            (None, Some(maximum)) => Some(Self::Maximum { maximum }),
            (Some(minimum), Some(maximum)) => {
                JointLimitRange::new(minimum, maximum).map(Self::Range)
            }
        }
    }
}

/// The wire spelling of [`JointLimits`], before the ordered-pair mint.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "bounds", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
enum JointLimitsWire {
    /// Only the lower bound is enabled.
    Minimum {
        /// Lower bound.
        minimum: FiniteReal,
    },
    /// Only the upper bound is enabled.
    Maximum {
        /// Upper bound.
        maximum: FiniteReal,
    },
    /// Both bounds are enabled, in order.
    Range {
        /// Lower bound.
        minimum: FiniteReal,
        /// Upper bound, at or above `minimum`.
        maximum: FiniteReal,
    },
}

impl From<JointLimits> for JointLimitsWire {
    fn from(limits: JointLimits) -> Self {
        match limits {
            JointLimits::Minimum { minimum } => Self::Minimum { minimum },
            JointLimits::Maximum { maximum } => Self::Maximum { maximum },
            JointLimits::Range(range) => Self::Range {
                minimum: range.minimum(),
                maximum: range.maximum(),
            },
        }
    }
}

impl TryFrom<JointLimitsWire> for JointLimits {
    type Error = &'static str;

    fn try_from(wire: JointLimitsWire) -> Result<Self, Self::Error> {
        Ok(match wire {
            JointLimitsWire::Minimum { minimum } => Self::Minimum { minimum },
            JointLimitsWire::Maximum { maximum } => Self::Maximum { maximum },
            JointLimitsWire::Range { minimum, maximum } => Self::Range(
                JointLimitRange::new(minimum, maximum)
                    .ok_or("joint limit range must be ordered")?,
            ),
        })
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for JointLimits {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "JointLimits".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::JointLimits").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        JointLimitsWire::json_schema(generator)
    }
}

/// One joint connector with its local frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct JointConnector {
    /// Referenced operand.
    pub operand: JointOperand,
    /// Connector-local frame.
    pub frame: Transform,
    /// Whether this connector is detached from the solve.
    pub detached: bool,
}

/// Structurally complete operands and frames for an assembly joint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "arity", rename_all = "snake_case", deny_unknown_fields)]
pub enum JointOperands {
    /// One grounded connector and its optional attachment offset.
    Grounded {
        /// Grounded connector.
        connector: JointConnector,
        /// Connector attachment offset.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_offset_frame"
        )]
        offset_frame: Option<Transform>,
    },
    /// Two paired connectors and their optional attachment offsets.
    Pair {
        /// Non-grounded joint family.
        kind: PairedJointKind,
        /// Connectors in operand order.
        connectors: Box<[JointConnector; 2]>,
        /// Connector attachment offsets in operand order.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_offset_frames"
        )]
        offset_frames: Option<[Transform; 2]>,
    },
}

/// Relative direction of the two normals of a plane coincidence or an insert.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum PlaneSense {
    /// The normals point toward each other: `z₁ = −z₀`.
    Opposed,
    /// The normals point the same way: `z₁ = z₀`.
    Aligned,
}

/// The side of a tangent plane on which the touching face lies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TangentContact {
    /// The face lies on the side that the plane normal points to.
    Outside,
    /// The face lies on the side opposite the plane normal.
    Inside,
}

/// Assembly-joint families that connect two operands.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PairedJointKind {
    /// Rigid connection with no relative degrees of freedom.
    Fixed {
        /// Angular offset in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<FiniteReal>,
        /// Connector-local translation offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_translation_offset"
        )]
        translation_offset: Option<[FiniteReal; 3]>,
        /// Enabled angular interval in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angular_limits"
        )]
        angular_limits: Option<JointLimits>,
        /// Enabled linear interval in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_linear_limits"
        )]
        linear_limits: Option<JointLimits>,
    },
    /// Rotation about one axis.
    Revolute {
        /// Angular offset in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<FiniteReal>,
        /// Enabled angular interval in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angular_limits"
        )]
        angular_limits: Option<JointLimits>,
    },
    /// Translation along one axis.
    Slider {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Connector-local translation offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_translation_offset"
        )]
        translation_offset: Option<[FiniteReal; 3]>,
        /// Enabled linear interval in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_linear_limits"
        )]
        linear_limits: Option<JointLimits>,
    },
    /// Coupled rotation and translation on one axis.
    Cylindrical {
        /// Angular offset in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<FiniteReal>,
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Enabled angular interval in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angular_limits"
        )]
        angular_limits: Option<JointLimits>,
        /// Enabled linear interval in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_linear_limits"
        )]
        linear_limits: Option<JointLimits>,
    },
    /// Rotation about a common point.
    Ball {},
    /// Maintains a scalar separation.
    Distance {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
    },
    /// Maintains parallel connector directions.
    Parallel {},
    /// Maintains perpendicular connector directions.
    Perpendicular {},
    /// Maintains an angular separation.
    Angle {
        /// Angular offset in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<FiniteReal>,
    },
    /// Couples rack translation to pinion rotation.
    RackPinion {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Secondary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance2"
        )]
        distance2: Option<FiniteReal>,
    },
    /// Couples translation and rotation by screw pitch.
    Screw {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
    },
    /// Couples two gear rotations.
    Gears {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Secondary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance2"
        )]
        distance2: Option<FiniteReal>,
    },
    /// Couples two pulley rotations through a belt.
    Belt {
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Secondary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance2"
        )]
        distance2: Option<FiniteReal>,
    },
    /// Coincident connector planes. The z axis of each connector frame is
    /// the outward normal of its plane, and the frame origin lies on the plane.
    PlaneCoincidence {
        /// Relative direction of the two plane normals.
        sense: PlaneSense,
        /// Signed separation `(origin₁ − origin₀) · z₀` in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_offset"
        )]
        offset: Option<FiniteReal>,
    },
    /// Coincident connector axes. The z axis of each connector frame is the
    /// axis direction, and the frame origin lies on the axis. The two
    /// directions are parallel in either sense.
    AxisCoincidence {},
    /// The origin of the first connector frame lies at `distance` from the
    /// axis that the z axis of the second connector frame spans.
    PointOnAxis {
        /// Point-to-axis distance in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
    },
    /// Coincident circle axes with coincident or offset circle planes. The z
    /// axis of each connector frame is the normal of its circle, and the
    /// frame origin is the circle centre. Both origins lie on the line that
    /// the z axis of the first connector frame spans.
    Insert {
        /// Relative direction of the two circle normals.
        sense: PlaneSense,
        /// Signed separation `(origin₀ − origin₁) · z₀` in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_offset"
        )]
        offset: Option<FiniteReal>,
    },
    /// A cylindrical face of the first connector touches the plane of the
    /// second connector. The z axis of the first connector frame is the
    /// cylinder axis and its origin lies on that axis; the z axis of the
    /// second connector frame is the outward plane normal and its origin lies
    /// on the plane. The cylinder radius is that of the referenced face.
    Tangent {
        /// The side of the plane on which the cylinder lies.
        contact: TangentContact,
    },
    /// Future application-defined family retained without relabeling.
    Native {
        /// Application-defined family name.
        name: String,
        /// Angular offset in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<FiniteReal>,
        /// Connector-local translation offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_translation_offset"
        )]
        translation_offset: Option<[FiniteReal; 3]>,
        /// Primary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance"
        )]
        distance: Option<FiniteReal>,
        /// Secondary linear offset in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance2"
        )]
        distance2: Option<FiniteReal>,
        /// Enabled angular interval in radians.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angular_limits"
        )]
        angular_limits: Option<JointLimits>,
        /// Enabled linear interval in document length units.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_linear_limits"
        )]
        linear_limits: Option<JointLimits>,
    },
}

/// Neutral assembly constraint between connector frames.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AssemblyJoint {
    /// Globally unique joint identity.
    pub id: JointId,
    /// Structurally complete connector state.
    operands: JointOperands,
    /// Whether solving this joint is suppressed.
    pub suppressed: bool,
    /// Design parameter whose value drives the offset, distance, or angle of the joint.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_driving_parameter"
    )]
    pub driving_parameter: Option<crate::features::ParameterId>,
    /// Format-native joint record supplying this constraint.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

impl AssemblyJoint {
    /// Constructs a grounded joint with exactly one connector.
    pub fn grounded(
        id: JointId,
        connector: JointConnector,
        offset_frame: Option<Transform>,
    ) -> Self {
        Self::with_operands(
            id,
            JointOperands::Grounded {
                connector,
                offset_frame,
            },
        )
    }

    /// Constructs a non-grounded joint with exactly two connectors.
    pub fn paired(
        id: JointId,
        kind: PairedJointKind,
        connectors: [JointConnector; 2],
        offset_frames: Option<[Transform; 2]>,
    ) -> Self {
        Self::with_operands(
            id,
            JointOperands::Pair {
                kind,
                connectors: Box::new(connectors),
                offset_frames,
            },
        )
    }

    fn with_operands(id: JointId, operands: JointOperands) -> Self {
        Self {
            id,
            operands,
            suppressed: false,
            driving_parameter: None,
            native_ref: None,
        }
    }

    /// Visits every connector in operand order.
    pub fn connectors(&self) -> impl Iterator<Item = &JointConnector> {
        let slice: &[JointConnector] = match &self.operands {
            JointOperands::Grounded { connector, .. } => std::slice::from_ref(connector),
            JointOperands::Pair { connectors, .. } => connectors.as_slice(),
        };
        slice.iter()
    }
}

#[cfg(test)]
mod nonblank_literal_tests {
    /// A whitespace-leading template fails the build, so the probe below is
    /// the run-time reach the macro does not have: the `const { … }` block
    /// evaluates the constructor at compile time at every use.
    #[test]
    fn a_formatted_literal_keeps_its_non_blank_prefix() {
        assert_eq!(
            cadmpeg_core::nonblank_literal!("sldprt:marker-relation:{}", 34).as_str(),
            "sldprt:marker-relation:34"
        );
        assert_eq!(cadmpeg_core::nonblank_literal!("d6").as_str(), "d6");
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_source_name, String, "source_name");
cadmpeg_core::named_optional_field!(deserialize_label, String, "label");
cadmpeg_core::named_optional_field!(deserialize_description, String, "description");
cadmpeg_core::named_optional_field!(deserialize_part_number, String, "part_number");
cadmpeg_core::named_optional_field!(deserialize_native_ref, String, "native_ref");
cadmpeg_core::named_optional_field!(deserialize_object, String, "object");
cadmpeg_core::named_optional_field!(deserialize_linked_prototype, Transform, "linked_prototype");
cadmpeg_core::named_optional_field!(deserialize_name, String, "name");
cadmpeg_core::named_optional_field!(deserialize_visible, bool, "visible");
cadmpeg_core::named_optional_field!(deserialize_link, LinkState, "link");
cadmpeg_core::named_optional_field!(deserialize_source, PrototypeReference, "source");
cadmpeg_core::named_optional_field!(deserialize_group, PrototypeReference, "group");
cadmpeg_core::named_optional_field!(deserialize_touched, bool, "touched");
cadmpeg_core::named_optional_field!(deserialize_offset_frame, Transform, "offset_frame");
cadmpeg_core::named_optional_field!(deserialize_offset_frames, [Transform; 2], "offset_frames");
cadmpeg_core::named_optional_field!(deserialize_angle, FiniteReal, "angle");
cadmpeg_core::named_optional_field!(
    deserialize_translation_offset,
    [FiniteReal; 3],
    "translation_offset"
);
cadmpeg_core::named_optional_field!(deserialize_angular_limits, JointLimits, "angular_limits");
cadmpeg_core::named_optional_field!(deserialize_linear_limits, JointLimits, "linear_limits");
cadmpeg_core::named_optional_field!(deserialize_distance, FiniteReal, "distance");
cadmpeg_core::named_optional_field!(deserialize_distance2, FiniteReal, "distance2");
cadmpeg_core::named_optional_field!(deserialize_offset, FiniteReal, "offset");
cadmpeg_core::named_optional_field!(
    deserialize_driving_parameter,
    crate::features::ParameterId,
    "driving_parameter"
);

mod identity_rewrite;

mod serialization;