xtce-model 0.1.2

XTCE telemetry metadata: streaming XML parser and arena-backed intermediate representation
Documentation
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
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
//! Lowering: XML tree to [`XtceDb`].
//!
//! Two passes over the tree:
//!
//! 1. **Register.** Walk the `SpaceSystem` hierarchy and allocate an id for every parameter
//!    type, parameter and container, recording its qualified name and the tree node it came
//!    from. Nothing is resolved yet, because XTCE references run in both directions: a
//!    `<BaseContainer>` may name a container defined later in the file.
//! 2. **Lower.** Revisit each node, now able to turn every `parameterRef`,
//!    `parameterTypeRef` and `containerRef` into an id.
//!
//! A third, cheap step links each container to its inheritors and checks that inheritance is
//! acyclic, so a malformed database fails at load time rather than overflowing the stack on
//! the first packet.

use crate::commands::MetaCommand;
use crate::containers::{
    BooleanExpr, CompareOp, Comparison, ComparisonValue, Condition, Container, Entry, EntryKind,
    Location, LocationReference, MatchCriteria, Operand, SpaceSystem,
};
use crate::db::{Unsupported, XtceDb};
use crate::error::{RefKind, XtceError};
use crate::ids::{ContainerId, MetaCommandId, ParamId, SpaceSystemId, Span, TypeId};
use crate::intern::{FxHashMap, Interner, NameId};
use crate::types::{
    AggregateMember, ArrayDimension, BinaryEncoding, ByteOrder, Calibrator, Charset,
    ContextCalibrator, DataEncoding, DiscreteLookup, Enumeration, EnumerationList, FloatCoding,
    FloatEncoding, IntegerCoding, IntegerEncoding, LinearAdjustment, Parameter, ParameterType,
    PolynomialTerm, SizeSpec, Spline, SplinePoint, StringDelimiter, StringEncoding, TypeKind,
};
use crate::xml::{AttrKey, Dom, Element, Tag};

/// Encoding elements in the order the reference implementation searches for them.
const ENCODING_TAGS: [Tag; 4] = [
    Tag::StringDataEncoding,
    Tag::IntegerDataEncoding,
    Tag::FloatDataEncoding,
    Tag::BinaryDataEncoding,
];

/// A definition registered in pass 1, awaiting lowering in pass 2.
struct Pending<'d> {
    element: Element<'d>,
    space_system: SpaceSystemId,
    qualified_name: NameId,
    /// For a container, whether it came from `<CommandMetaData>` at all.
    ///
    /// True for a shared `<CommandContainerSet>` container as well as a command's own.
    is_command: bool,
    /// For a container, the telecommand whose `<CommandContainer>` it is.
    ///
    /// `None` for every telemetry container, and for the shared ones in a
    /// `<CommandContainerSet>`. It is what tells the entry lowering that `argumentRef` in
    /// this container resolves against that command's arguments and nothing else.
    command: Option<MetaCommandId>,
}

/// A `<MetaCommand>` registered in pass 1.
struct PendingCommand<'d> {
    element: Element<'d>,
    space_system: SpaceSystemId,
    qualified_name: NameId,
    /// The arguments it declares itself, by unqualified name, in document order.
    arguments: Vec<(NameId, ParamId)>,
    /// Its `<CommandContainer>`, if it has one.
    container: Option<ContainerId>,
    /// Resolved from `<BaseMetaCommand metaCommandRef=..>` once every command is registered.
    base: Option<MetaCommandId>,
}

pub(crate) struct Lowering<'d> {
    dom: &'d Dom,
    interner: Interner,

    space_systems: Vec<SpaceSystem>,
    /// Qualified path of each space system, owned separately from the interner.
    ///
    /// Building `"{parent}/{name}"` needs to read a path while writing to the interner. Held
    /// as its own `Vec`, the two are disjoint fields and the borrow checker allows it; read
    /// back out of the interner, every call would have to clone the parent path first —
    /// which is one allocation per definition, and a large database has ten thousand.
    ss_paths: Vec<String>,
    pending_types: Vec<Pending<'d>>,
    pending_params: Vec<Pending<'d>>,
    pending_containers: Vec<Pending<'d>>,
    pending_commands: Vec<PendingCommand<'d>>,
    /// Every argument each command can name, its own and its bases', by unqualified name.
    ///
    /// Indexed by [`MetaCommandId`] and filled by `resolve_command_bases` before anything is
    /// lowered, because an entry list resolves `argumentRef` through it.
    command_arguments: Vec<FxHashMap<NameId, ParamId>>,
    /// Bytes behind every `<FixedValueEntry>`, in one arena.
    fixed_values: Vec<u8>,

    type_by_qualified: FxHashMap<NameId, TypeId>,
    type_by_leaf: FxHashMap<NameId, TypeId>,
    /// Argument types, and the command half's parameter types, which share one namespace.
    ///
    /// The schema keys these separately from the telemetry parameter types — an
    /// `<IntegerArgumentType name="U8">` and an `<IntegerParameterType name="U8">` in the
    /// telemetry half are two different definitions and a valid file may have both. Sharing
    /// one index would reject it.
    argument_type_by_qualified: FxHashMap<NameId, TypeId>,
    argument_type_by_leaf: FxHashMap<NameId, TypeId>,
    param_by_qualified: FxHashMap<NameId, ParamId>,
    param_by_leaf: FxHashMap<NameId, ParamId>,
    container_by_qualified: FxHashMap<NameId, ContainerId>,
    container_by_leaf: FxHashMap<NameId, ContainerId>,
    command_by_qualified: FxHashMap<NameId, MetaCommandId>,
    command_by_leaf: FxHashMap<NameId, MetaCommandId>,

    unsupported: Vec<Unsupported>,
    /// Reusable buffer for building candidate qualified names during resolution.
    scratch: String,
}

impl<'d> Lowering<'d> {
    pub(crate) fn new(dom: &'d Dom) -> Self {
        // Two names per element is a generous upper bound (a definition contributes its own
        // name and its qualified path), and over-reserving here costs one allocation while
        // under-reserving costs a full rehash part-way through lowering.
        let interner = Interner::with_capacity(dom.len() * 2, dom.len() * 8);
        Self {
            dom,
            interner,
            space_systems: Vec::new(),
            ss_paths: Vec::new(),
            pending_types: Vec::new(),
            pending_params: Vec::new(),
            pending_containers: Vec::new(),
            pending_commands: Vec::new(),
            command_arguments: Vec::new(),
            fixed_values: Vec::new(),
            type_by_qualified: FxHashMap::default(),
            type_by_leaf: FxHashMap::default(),
            argument_type_by_qualified: FxHashMap::default(),
            argument_type_by_leaf: FxHashMap::default(),
            param_by_qualified: FxHashMap::default(),
            param_by_leaf: FxHashMap::default(),
            container_by_qualified: FxHashMap::default(),
            container_by_leaf: FxHashMap::default(),
            command_by_qualified: FxHashMap::default(),
            command_by_leaf: FxHashMap::default(),
            unsupported: Vec::new(),
            scratch: String::with_capacity(128),
        }
    }

    pub(crate) fn run(mut self) -> Result<XtceDb, XtceError> {
        let root = self.dom.root();
        if root.tag() != Tag::SpaceSystem {
            return Err(XtceError::NotXtce {
                found: root.name().to_owned(),
            });
        }

        self.register_space_system(root, None)?;
        // Before anything is lowered: an entry list in a command container resolves
        // `argumentRef` against the command's arguments *and its bases'*, so the inheritance
        // has to be settled first.
        self.resolve_command_bases()?;

        let types = self.lower_types()?;
        let mut parameters = self.lower_parameters()?;
        // `lower_containers` may append to `parameters`: an entry naming an array is expanded
        // into one synthetic parameter per index, so that nothing downstream has to know what
        // an array is.
        let (mut containers, entries) = self.lower_containers(&types, &mut parameters)?;
        let meta_commands = self.lower_commands();

        link_inheritors(&mut containers);
        check_acyclic(&containers, &self.interner)?;

        let root_containers = containers
            .iter()
            .enumerate()
            .filter(|(_, container)| container.base.is_none())
            .map(|(index, _)| ContainerId::new(u32::try_from(index).unwrap_or(u32::MAX)))
            .collect();

        Ok(XtceDb::assemble(crate::db::Parts {
            interner: self.interner,
            space_systems: self.space_systems,
            types,
            parameters,
            containers,
            entries,
            root_containers,
            meta_commands,
            fixed_values: self.fixed_values,
            type_by_qualified: self.type_by_qualified,
            type_by_leaf: self.type_by_leaf,
            param_by_qualified: self.param_by_qualified,
            param_by_leaf: self.param_by_leaf,
            container_by_qualified: self.container_by_qualified,
            container_by_leaf: self.container_by_leaf,
            unsupported: self.unsupported,
            xmlns: self.dom.xmlns().map(str::to_owned),
            skipped_sections: self.dom.skipped_sections().to_vec(),
        }))
    }

    // ---------------------------------------------------------------- pass 1: register

    fn register_space_system(
        &mut self,
        element: Element<'d>,
        parent: Option<SpaceSystemId>,
    ) -> Result<SpaceSystemId, XtceError> {
        let name = element
            .attr(AttrKey::Name)
            .ok_or_else(|| XtceError::Missing {
                what: "SpaceSystem name attribute",
                path: element.path(),
            })?;

        let mut qualified = String::new();
        if let Some(parent) = parent {
            qualified.push_str(self.ss_paths.get(parent.index()).map_or("", String::as_str));
        }
        qualified.push('/');
        qualified.push_str(name);

        let id = SpaceSystemId::new(u32::try_from(self.space_systems.len()).unwrap_or(u32::MAX));
        let name_id = self.interner.intern(name);
        let qualified_id = self.interner.intern(&qualified);
        self.ss_paths.push(qualified);
        self.space_systems.push(SpaceSystem {
            name: name_id,
            qualified_name: qualified_id,
            parent,
            children: Vec::new(),
        });
        if let Some(parent) = parent {
            if let Some(node) = self.space_systems.get_mut(parent.index()) {
                node.children.push(id);
            }
        }

        if let Some(telemetry) = element.child(Tag::TelemetryMetaData) {
            if let Some(set) = telemetry.child(Tag::ParameterTypeSet) {
                for child in set.children() {
                    self.register(child, id, Definition::Type)?;
                }
            }
            if let Some(set) = telemetry.child(Tag::ParameterSet) {
                for child in set.children_with(Tag::Parameter) {
                    self.register(child, id, Definition::Parameter)?;
                }
            }
            if let Some(set) = telemetry.child(Tag::ContainerSet) {
                for child in set.children_with(Tag::SequenceContainer) {
                    self.register(child, id, Definition::Container)?;
                }
            }
        }

        if let Some(commands) = element.child(Tag::CommandMetaData) {
            self.register_command_meta_data(commands, id)?;
        }

        for child in element.children_with(Tag::SpaceSystem) {
            self.register_space_system(child, Some(id))?;
        }
        Ok(id)
    }

    /// Registers what a `<CommandMetaData>` section defines.
    fn register_command_meta_data(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Result<(), XtceError> {
        // The schema keys these three sets in two overlapping ways: a command's parameter
        // types must not clash with the telemetry ones, *and* must not clash with the
        // argument types — but an argument type and a telemetry parameter type may share a
        // name, and a valid file does. So a command's parameter types are registered in both
        // namespaces and the argument types in only one.
        if let Some(set) = element.child(Tag::ParameterTypeSet) {
            for child in set.children() {
                self.register(child, space_system, Definition::Type)?;
                self.also_index_as_argument_type(child, space_system)?;
            }
        }
        if let Some(set) = element.child(Tag::ArgumentTypeSet) {
            for child in set.children() {
                self.register(child, space_system, Definition::ArgumentType)?;
            }
        }
        if let Some(set) = element.child(Tag::ParameterSet) {
            for child in set.children_with(Tag::Parameter) {
                self.register(child, space_system, Definition::Parameter)?;
            }
        }
        // Containers here are the shared kind: "containers that can be referenced/shared by
        // MetaCommand definitions". They are named at the system level like any other, which
        // a MetaCommand's own private container is not.
        if let Some(set) = element.child(Tag::CommandContainerSet) {
            for child in set.children() {
                self.register(child, space_system, Definition::Container)?;
                // Registered like a telemetry container — the schema keys its name the same
                // way — but it is still a telecommand's packaging, and root selection has to
                // know that or a shared one with no `<BaseContainer>` would look like a
                // packet to decode by default.
                if let Some(last) = self.pending_containers.last_mut() {
                    last.is_command = true;
                }
            }
        }
        if let Some(set) = element.child(Tag::MetaCommandSet) {
            for child in set.children_with(Tag::MetaCommand) {
                self.register_meta_command(child, space_system)?;
            }
        }
        Ok(())
    }

    /// Indexes an already-registered type under the argument-type namespace as well.
    ///
    /// Only for a `<CommandMetaData><ParameterTypeSet>` entry, which both an
    /// `argumentTypeRef` and a `parameterTypeRef` may name.
    fn also_index_as_argument_type(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Result<(), XtceError> {
        let Some(name) = element.attr(AttrKey::Name) else {
            return Ok(());
        };
        let ss_path = self
            .ss_paths
            .get(space_system.index())
            .map_or(String::new(), Clone::clone);
        let qualified = format!("{ss_path}/{name}");
        let Some(qualified_id) = self.interner.get(&qualified) else {
            return Ok(());
        };
        let Some(&id) = self.type_by_qualified.get(&qualified_id) else {
            return Ok(());
        };
        insert_unique(
            &mut self.argument_type_by_qualified,
            qualified_id,
            id,
            RefKind::ArgumentType,
            &qualified,
            &element,
        )?;
        if let Some(leaf_id) = self.interner.get(name) {
            self.argument_type_by_leaf.entry(leaf_id).or_insert(id);
        }
        Ok(())
    }

    /// Registers one `<MetaCommand>`, its arguments and its container.
    ///
    /// Arguments are qualified under the command — `/SS/SET_MODE/MODE` — because the schema
    /// says an argument reference "is always resolved locally to the metacommand", and two
    /// commands may each declare a `MODE`. They are deliberately *not* added to the
    /// unqualified index: that index is what `<Comparison parameterRef=..>` and every
    /// telemetry reference searches, and an argument appearing there could shadow a real
    /// parameter of the same name.
    fn register_meta_command(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Result<(), XtceError> {
        let Some(name) = element.attr(AttrKey::Name) else {
            return Err(XtceError::Missing {
                what: "MetaCommand name attribute",
                path: element.path(),
            });
        };
        let id = MetaCommandId::new(u32::try_from(self.pending_commands.len()).unwrap_or(u32::MAX));

        let ss_path = self
            .ss_paths
            .get(space_system.index())
            .map_or(String::new(), Clone::clone);
        let qualified = format!("{ss_path}/{name}");
        let qualified_id = self.interner.intern(&qualified);
        insert_unique(
            &mut self.command_by_qualified,
            qualified_id,
            id,
            RefKind::MetaCommand,
            &qualified,
            &element,
        )?;
        let leaf_id = self.interner.intern(name);
        self.command_by_leaf.entry(leaf_id).or_insert(id);

        let mut arguments = Vec::new();
        if let Some(list) = element.child(Tag::ArgumentList) {
            for argument in list.children_with(Tag::Argument) {
                let Some(argument_name) = argument.attr(AttrKey::Name) else {
                    return Err(XtceError::Missing {
                        what: "Argument name attribute",
                        path: argument.path(),
                    });
                };
                let argument_qualified = format!("{qualified}/{argument_name}");
                let argument_qualified_id = self.interner.intern(&argument_qualified);
                let param_id =
                    ParamId::new(u32::try_from(self.pending_params.len()).unwrap_or(u32::MAX));
                self.pending_params.push(Pending {
                    element: argument,
                    space_system,
                    qualified_name: argument_qualified_id,
                    is_command: false,
                    command: None,
                });
                insert_unique(
                    &mut self.param_by_qualified,
                    argument_qualified_id,
                    param_id,
                    RefKind::Parameter,
                    &argument_qualified,
                    &argument,
                )?;
                arguments.push((self.interner.intern(argument_name), param_id));
            }
        }

        let mut container = None;
        if let Some(element) = element.child(Tag::CommandContainer) {
            let Some(container_name) = element.attr(AttrKey::Name) else {
                return Err(XtceError::Missing {
                    what: "CommandContainer name attribute",
                    path: element.path(),
                });
            };
            let container_qualified = format!("{qualified}/{container_name}");
            let container_qualified_id = self.interner.intern(&container_qualified);
            let container_id =
                ContainerId::new(u32::try_from(self.pending_containers.len()).unwrap_or(u32::MAX));
            self.pending_containers.push(Pending {
                element,
                space_system,
                qualified_name: container_qualified_id,
                is_command: true,
                command: Some(id),
            });
            insert_unique(
                &mut self.container_by_qualified,
                container_qualified_id,
                container_id,
                RefKind::Container,
                &container_qualified,
                &element,
            )?;
            let container_leaf = self.interner.intern(container_name);
            self.container_by_leaf
                .entry(container_leaf)
                .or_insert(container_id);
            container = Some(container_id);
        }

        self.pending_commands.push(PendingCommand {
            element,
            space_system,
            qualified_name: qualified_id,
            arguments,
            container,
            base: None,
        });
        Ok(())
    }

    fn register(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
        kind: Definition,
    ) -> Result<(), XtceError> {
        let Some(name) = element.attr(AttrKey::Name) else {
            return Err(XtceError::Missing {
                what: "name attribute",
                path: element.path(),
            });
        };
        // `scratch` is moved out and back so that reading a space-system path and writing to
        // the interner do not overlap; no allocation happens after the first definition.
        let mut scratch = std::mem::take(&mut self.scratch);
        scratch.clear();
        scratch.push_str(
            self.ss_paths
                .get(space_system.index())
                .map_or("", String::as_str),
        );
        scratch.push('/');
        scratch.push_str(name);
        let qualified_id = self.interner.intern(&scratch);
        let leaf_id = self.interner.intern(name);
        let qualified = &scratch;

        let pending = Pending {
            element,
            space_system,
            qualified_name: qualified_id,
            is_command: false,
            command: None,
        };

        match kind {
            Definition::Type | Definition::ArgumentType => {
                let id = TypeId::new(u32::try_from(self.pending_types.len()).unwrap_or(u32::MAX));
                self.pending_types.push(pending);
                // Both namespaces live in one arena; only the indexes differ.
                let argument = matches!(kind, Definition::ArgumentType);
                let (by_qualified, by_leaf, ref_kind) = if argument {
                    (
                        &mut self.argument_type_by_qualified,
                        &mut self.argument_type_by_leaf,
                        RefKind::ArgumentType,
                    )
                } else {
                    (
                        &mut self.type_by_qualified,
                        &mut self.type_by_leaf,
                        RefKind::ParameterType,
                    )
                };
                insert_unique(
                    by_qualified,
                    qualified_id,
                    id,
                    ref_kind,
                    qualified,
                    &element,
                )?;
                by_leaf.entry(leaf_id).or_insert(id);
            }
            Definition::Parameter => {
                let id = ParamId::new(u32::try_from(self.pending_params.len()).unwrap_or(u32::MAX));
                self.pending_params.push(pending);
                insert_unique(
                    &mut self.param_by_qualified,
                    qualified_id,
                    id,
                    RefKind::Parameter,
                    qualified,
                    &element,
                )?;
                self.param_by_leaf.entry(leaf_id).or_insert(id);
            }
            Definition::Container => {
                let id = ContainerId::new(
                    u32::try_from(self.pending_containers.len()).unwrap_or(u32::MAX),
                );
                self.pending_containers.push(pending);
                insert_unique(
                    &mut self.container_by_qualified,
                    qualified_id,
                    id,
                    RefKind::Container,
                    qualified,
                    &element,
                )?;
                self.container_by_leaf.entry(leaf_id).or_insert(id);
            }
        }
        self.scratch = scratch;
        Ok(())
    }

    /// Resolves `<BaseMetaCommand>` links and works out what arguments each command can name.
    ///
    /// A command's arguments are its own plus every base's, with a derived declaration
    /// shadowing an inherited one of the same name — the same rule a struct's fields follow,
    /// and the reason the chain is walked root-first.
    fn resolve_command_bases(&mut self) -> Result<(), XtceError> {
        for index in 0..self.pending_commands.len() {
            let (reference, space_system, path) = {
                let command = &self.pending_commands[index];
                let Some(base) = command.element.child(Tag::BaseMetaCommand) else {
                    continue;
                };
                let Some(reference) = base.attr(AttrKey::MetaCommandRef) else {
                    return Err(XtceError::Missing {
                        what: "metaCommandRef attribute",
                        path: base.path(),
                    });
                };
                (reference.to_owned(), command.space_system, base.path())
            };
            let resolved = self
                .resolve(&reference, space_system, RefKind::MetaCommand)
                .ok_or_else(|| XtceError::UnresolvedReference {
                    kind: RefKind::MetaCommand,
                    reference: reference.clone(),
                    path,
                })?;
            self.pending_commands[index].base = Some(MetaCommandId::new(resolved));
        }

        self.command_arguments = Vec::with_capacity(self.pending_commands.len());
        for index in 0..self.pending_commands.len() {
            // Root-first, so an argument a command declares itself wins over the inherited
            // one it shadows.
            let mut chain = vec![index];
            let mut cursor = self.pending_commands[index].base;
            while let Some(base) = cursor {
                if chain.contains(&base.index()) {
                    return Err(XtceError::InheritanceCycle {
                        chain: chain
                            .iter()
                            .chain(std::iter::once(&base.index()))
                            .map(|&at| self.command_name(at))
                            .collect(),
                    });
                }
                chain.push(base.index());
                cursor = self
                    .pending_commands
                    .get(base.index())
                    .and_then(|command| command.base);
            }

            let mut arguments = FxHashMap::default();
            for &at in chain.iter().rev() {
                if let Some(command) = self.pending_commands.get(at) {
                    for &(name, parameter) in &command.arguments {
                        arguments.insert(name, parameter);
                    }
                }
            }
            self.command_arguments.push(arguments);
        }
        Ok(())
    }

    /// Whether a `MetaCommand` is marked `abstract="true"`.
    fn command_is_abstract(&self, command: MetaCommandId) -> bool {
        self.pending_commands
            .get(command.index())
            .and_then(|pending| pending.element.attr(AttrKey::Abstract))
            .is_some_and(|text| text.eq_ignore_ascii_case("true"))
    }

    fn command_name(&self, at: usize) -> String {
        self.pending_commands
            .get(at)
            .map(|command| self.interner.resolve(command.qualified_name).to_owned())
            .unwrap_or_default()
    }

    // ------------------------------------------------------------------- pass 2: lower

    fn lower_types(&mut self) -> Result<Vec<ParameterType>, XtceError> {
        let pending = std::mem::take(&mut self.pending_types);
        let mut out = Vec::with_capacity(pending.len());
        for item in &pending {
            out.push(self.lower_type(item)?);
        }
        self.pending_types = pending;
        Ok(out)
    }

    fn lower_type(&mut self, pending: &Pending<'d>) -> Result<ParameterType, XtceError> {
        let element = pending.element;
        let name = element.attr(AttrKey::Name).unwrap_or_default();
        let name_id = self.interner.intern(name);

        let mut encoding = self.lower_encoding(element, pending.space_system)?;
        apply_time_unit_scaler(element, &mut encoding);
        let units = self.lower_units(element);

        // An argument type is a parameter type. XTCE spells them differently because an
        // argument may carry a `<ValidRangeSet>` a parameter may not, but the encodings are
        // the same elements and every `*ArgumentType` extends the same base its
        // `*ParameterType` twin does.
        let kind = match element.tag() {
            Tag::IntegerParameterType | Tag::IntegerArgumentType => TypeKind::Integer,
            Tag::FloatParameterType | Tag::FloatArgumentType => TypeKind::Float,
            Tag::StringParameterType | Tag::StringArgumentType => TypeKind::String,
            Tag::BinaryParameterType | Tag::BinaryArgumentType => TypeKind::Binary,
            Tag::BooleanParameterType | Tag::BooleanArgumentType => TypeKind::Boolean {
                zero_label: element
                    .attr(AttrKey::ZeroStringValue)
                    .map(|text| self.interner.intern(text)),
                one_label: element
                    .attr(AttrKey::OneStringValue)
                    .map(|text| self.interner.intern(text)),
            },
            Tag::EnumeratedParameterType | Tag::EnumeratedArgumentType => {
                self.lower_enumeration(element)
            }
            Tag::AbsoluteTimeParameterType | Tag::AbsoluteTimeArgumentType => {
                TypeKind::AbsoluteTime {
                    epoch: element
                        .child(Tag::ReferenceTime)
                        .and_then(|reference| reference.child(Tag::Epoch))
                        .and_then(Element::text)
                        .map(|text| self.interner.intern(text)),
                    offset_from: element
                        .child(Tag::ReferenceTime)
                        .and_then(|reference| reference.child(Tag::OffsetFrom))
                        .and_then(|offset| offset.attr(AttrKey::ParameterRef))
                        .and_then(|reference| {
                            self.resolve_parameter_opt(reference, pending.space_system)
                        }),
                }
            }
            Tag::RelativeTimeParameterType | Tag::RelativeTimeArgumentType => {
                TypeKind::RelativeTime
            }
            Tag::ArrayParameterType | Tag::ArrayArgumentType => {
                self.lower_array_type(element, pending.space_system)
            }
            Tag::AggregateParameterType | Tag::AggregateArgumentType => {
                self.lower_aggregate_type(element, pending.space_system)
            }
            other => {
                let element_name = element.name().to_owned();
                self.note_unsupported(
                    &element_name,
                    &element.path(),
                    "parameter type outside the supported subset",
                );
                let _ = other;
                TypeKind::Unsupported {
                    element: self.interner.intern(&element_name),
                }
            }
        };

        Ok(ParameterType {
            name: name_id,
            qualified_name: pending.qualified_name,
            space_system: pending.space_system,
            units,
            kind,
            encoding,
        })
    }

    fn lower_units(&mut self, element: Element<'d>) -> Vec<NameId> {
        // Time parameter types put their unit on `<Encoding units=..>`; everything else
        // uses `<UnitSet><Unit>`.
        if let Some(units) = element
            .child(Tag::Encoding)
            .and_then(|encoding| encoding.attr(AttrKey::Units))
        {
            return vec![self.interner.intern(units)];
        }
        let Some(set) = element.child(Tag::UnitSet) else {
            return Vec::new();
        };
        set.children_with(Tag::Unit)
            .filter_map(Element::text)
            .map(|text| self.interner.intern(text))
            .collect()
    }

    /// `<ArrayParameterType>`: an element type and one dimension per axis.
    ///
    /// Anything the expansion could not carry out is reported as unsupported rather than
    /// guessed at, and the type still loads — `xtce info` names it, and only a container that
    /// actually uses it is blocked.
    fn lower_array_type(&mut self, element: Element<'d>, space_system: SpaceSystemId) -> TypeKind {
        let unsupported = |lower: &mut Self, reason: &'static str| {
            let name = element.name().to_owned();
            lower.note_unsupported(&name, &element.path(), reason);
            TypeKind::Unsupported {
                element: lower.interner.intern(&name),
            }
        };

        let Some(reference) = element.attr(AttrKey::ArrayTypeRef) else {
            return unsupported(self, "an array type with no arrayTypeRef has no elements");
        };
        let Some(element_type) = self.resolve(reference, space_system, RefKind::ParameterType)
        else {
            return unsupported(self, "the arrayTypeRef does not resolve");
        };

        let Some(list) = element.child(Tag::DimensionList) else {
            return unsupported(self, "an array type with no DimensionList has no size");
        };

        let mut dimensions = Vec::new();
        for dimension in list.children_with(Tag::Dimension) {
            // `StartingIndex` and `EndingIndex` are `IntegerValueType`, so each may also be a
            // `DynamicValue` or a `DiscreteLookupList`. Those make the element count a
            // property of the packet, and the expansion happens before any packet exists.
            let (Some(start), Some(end)) = (
                fixed_index(dimension.child(Tag::StartingIndex)),
                fixed_index(dimension.child(Tag::EndingIndex)),
            ) else {
                return unsupported(
                    self,
                    "only a Dimension with fixed StartingIndex and EndingIndex is expanded; a \
                     dimension read from the packet is not",
                );
            };
            if start < 0 || end < start {
                return unsupported(
                    self,
                    "a Dimension must run from a non-negative index upwards",
                );
            }
            dimensions.push(ArrayDimension { start, end });
        }

        if dimensions.is_empty() {
            return unsupported(self, "an array type with no Dimension has no size");
        }

        TypeKind::Array {
            element: TypeId::new(element_type),
            dimensions,
        }
    }

    /// `<AggregateParameterType>`: an ordered, packed list of named members.
    fn lower_aggregate_type(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> TypeKind {
        let unsupported = |lower: &mut Self, reason: &'static str| {
            let name = element.name().to_owned();
            lower.note_unsupported(&name, &element.path(), reason);
            TypeKind::Unsupported {
                element: lower.interner.intern(&name),
            }
        };

        let Some(list) = element.child(Tag::MemberList) else {
            return unsupported(self, "an aggregate with no MemberList has no members");
        };

        let mut members = Vec::new();
        for member in list.children_with(Tag::Member) {
            let Some(name) = member.attr(AttrKey::Name) else {
                return unsupported(self, "a Member with no name cannot be addressed");
            };
            let Some(reference) = member.attr(AttrKey::TypeRef) else {
                return unsupported(self, "a Member with no typeRef has no width");
            };
            let name = self.interner.intern(name);
            let Some(type_id) = self.resolve(reference, space_system, RefKind::ParameterType)
            else {
                return unsupported(self, "a Member's typeRef does not resolve");
            };
            members.push(AggregateMember {
                name,
                type_id: TypeId::new(type_id),
            });
        }

        if members.is_empty() {
            return unsupported(self, "an aggregate with no Member has no members");
        }

        TypeKind::Aggregate { members }
    }

    fn lower_enumeration(&mut self, element: Element<'d>) -> TypeKind {
        let Some(list) = element.child(Tag::EnumerationList) else {
            let name = element.name().to_owned();
            self.note_unsupported(
                &name,
                &element.path(),
                "EnumeratedParameterType without an EnumerationList",
            );
            return TypeKind::Unsupported {
                element: self.interner.intern("EnumerationList"),
            };
        };

        let mut entries = Vec::new();
        for enumeration in list.children_with(Tag::Enumeration) {
            let Some(value) = enumeration.attr(AttrKey::Value).and_then(parse_i128) else {
                self.note_unsupported(
                    "Enumeration",
                    &enumeration.path(),
                    "enumeration value is not an integer",
                );
                return TypeKind::Unsupported {
                    element: self.interner.intern("Enumeration"),
                };
            };
            let max_value = enumeration
                .attr(AttrKey::MaxValue)
                .and_then(parse_i128)
                .unwrap_or(value);
            let label = enumeration.attr(AttrKey::Label).unwrap_or_default();
            entries.push(Enumeration {
                value,
                max_value,
                label: self.interner.intern(label),
            });
        }
        TypeKind::Enumerated(EnumerationList::new(entries))
    }

    fn lower_encoding(
        &mut self,
        type_element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Result<DataEncoding, XtceError> {
        let Some((tag, element)) = ENCODING_TAGS
            .iter()
            .find_map(|&tag| type_element.descendant(tag).map(|found| (tag, found)))
        else {
            return Ok(DataEncoding::None);
        };

        Ok(match tag {
            Tag::IntegerDataEncoding => DataEncoding::Integer(IntegerEncoding {
                size_in_bits: Self::size_attr(element, 8)?,
                coding: integer_coding(element.attr(AttrKey::Encoding).unwrap_or("unsigned")),
                byte_order: byte_order(element.attr(AttrKey::ByteOrder)),
                default_calibrator: self.lower_default_calibrator(element),
                context_calibrators: self.lower_context_calibrators(element, space_system),
            }),
            Tag::FloatDataEncoding => DataEncoding::Float(FloatEncoding {
                size_in_bits: Self::size_attr(element, 32)?,
                coding: float_coding(element.attr(AttrKey::Encoding).unwrap_or("IEEE754")),
                byte_order: byte_order(element.attr(AttrKey::ByteOrder)),
                default_calibrator: self.lower_default_calibrator(element),
                context_calibrators: self.lower_context_calibrators(element, space_system),
            }),
            Tag::StringDataEncoding => {
                DataEncoding::String(self.lower_string_encoding(element, space_system))
            }
            Tag::BinaryDataEncoding => DataEncoding::Binary(BinaryEncoding {
                size: self.lower_size_spec(element.child(Tag::SizeInBits), space_system),
            }),
            _ => DataEncoding::None,
        })
    }

    fn size_attr(element: Element<'d>, default: u32) -> Result<u32, XtceError> {
        match element.attr(AttrKey::SizeInBits) {
            None => Ok(default),
            Some(text) => text
                .trim()
                .parse::<u32>()
                .map_err(|error| XtceError::Invalid {
                    what: "sizeInBits",
                    value: text.to_owned(),
                    path: element.path(),
                    reason: error.to_string(),
                }),
        }
    }

    fn lower_string_encoding(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> StringEncoding {
        let charset_text = element.attr(AttrKey::Encoding).unwrap_or("UTF-8");
        let charset = charset(charset_text);
        let byte_order = match element.attr(AttrKey::ByteOrder) {
            Some(text) => byte_order(Some(text)),
            // XTCE lets the charset name carry the endianness; honour that before falling
            // back to the big-endian default.
            None if charset_text.ends_with("LE") => ByteOrder::LeastSignificantFirst,
            None => ByteOrder::MostSignificantFirst,
        };

        // The raw size lives under `<SizeInBits>` (fixed) or `<Variable>` (dynamic), and the
        // delimiter is a child of whichever one is present.
        let size_holder = element
            .child(Tag::SizeInBits)
            .or_else(|| element.child(Tag::Variable));

        let raw_size = match size_holder {
            Some(holder) if holder.tag() == Tag::SizeInBits => {
                match holder
                    .child(Tag::Fixed)
                    .and_then(|fixed| fixed.child(Tag::FixedValue))
                    .or_else(|| holder.child(Tag::FixedValue))
                    .and_then(Element::text)
                    .and_then(|text| text.trim().parse::<u32>().ok())
                {
                    Some(bits) => SizeSpec::Fixed(bits),
                    None => self.lower_size_spec(Some(holder), space_system),
                }
            }
            Some(holder) => self.lower_size_spec(Some(holder), space_system),
            None => SizeSpec::Unsupported {
                element: self.interner.intern("SizeInBits"),
            },
        };

        let delimiter = size_holder
            .and_then(|holder| {
                if let Some(termination) = holder.child(Tag::TerminationChar) {
                    let hex = termination.text().unwrap_or_default();
                    return Some(StringDelimiter::TerminationChar(parse_hex(hex)));
                }
                let leading = holder.child(Tag::LeadingSize)?;
                let bits = leading
                    .attr(AttrKey::SizeInBitsOfSizeTag)
                    .and_then(|text| text.trim().parse::<u32>().ok())
                    .unwrap_or(8);
                Some(StringDelimiter::LeadingSize { size_in_bits: bits })
            })
            .unwrap_or_default();

        StringEncoding {
            charset,
            byte_order,
            raw_size,
            delimiter,
        }
    }

    fn lower_size_spec(
        &mut self,
        holder: Option<Element<'d>>,
        space_system: SpaceSystemId,
    ) -> SizeSpec {
        let Some(holder) = holder else {
            return SizeSpec::Unsupported {
                element: self.interner.intern("SizeInBits"),
            };
        };

        if let Some(fixed) = holder.child(Tag::FixedValue).or_else(|| {
            holder
                .child(Tag::Fixed)
                .and_then(|f| f.child(Tag::FixedValue))
        }) {
            if let Some(bits) = fixed
                .text()
                .and_then(|text| text.trim().parse::<u32>().ok())
            {
                return SizeSpec::Fixed(bits);
            }
        }

        if let Some(dynamic) = holder.child(Tag::DynamicValue) {
            if let Some(instance) = dynamic.child(Tag::ParameterInstanceRef) {
                let reference = instance.attr(AttrKey::ParameterRef).unwrap_or_default();
                if let Some(parameter) = self.resolve_parameter_opt(reference, space_system) {
                    return SizeSpec::Dynamic {
                        parameter,
                        use_calibrated: use_calibrated(instance),
                        adjustment: dynamic.child(Tag::LinearAdjustment).map(linear_adjustment),
                    };
                }
                self.note_unsupported(
                    "DynamicValue",
                    &dynamic.path(),
                    "size reference does not resolve to a known parameter",
                );
            }
            return SizeSpec::Unsupported {
                element: self.interner.intern("DynamicValue"),
            };
        }

        if let Some(list) = holder.child(Tag::DiscreteLookupList) {
            let lookups = list
                .children_with(Tag::DiscreteLookup)
                .map(|lookup| DiscreteLookup {
                    criteria: self.lower_criteria_children(lookup, space_system),
                    value: lookup
                        .attr(AttrKey::Value)
                        .and_then(|text| text.trim().parse::<i64>().ok())
                        .unwrap_or(0),
                })
                .collect();
            return SizeSpec::DiscreteLookup(lookups);
        }

        SizeSpec::Unsupported {
            element: self.interner.intern(holder.name()),
        }
    }

    fn lower_default_calibrator(&mut self, encoding: Element<'d>) -> Option<Calibrator> {
        let holder = encoding.child(Tag::DefaultCalibrator)?;
        self.lower_calibrator(holder)
    }

    fn lower_context_calibrators(
        &mut self,
        encoding: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Vec<ContextCalibrator> {
        let Some(list) = encoding.child(Tag::ContextCalibratorList) else {
            return Vec::new();
        };
        list.children_with(Tag::ContextCalibrator)
            .filter_map(|context| {
                let criteria = context
                    .child(Tag::ContextMatch)
                    .map(|match_element| self.lower_criteria_children(match_element, space_system))
                    .unwrap_or_default();
                let calibrator = context
                    .child(Tag::Calibrator)
                    .and_then(|holder| self.lower_calibrator(holder))?;
                Some(ContextCalibrator {
                    criteria,
                    calibrator,
                })
            })
            .collect()
    }

    fn lower_calibrator(&mut self, holder: Element<'d>) -> Option<Calibrator> {
        for child in holder.children() {
            match child.tag() {
                Tag::PolynomialCalibrator => {
                    let terms = child
                        .children_with(Tag::Term)
                        .map(|term| PolynomialTerm {
                            coefficient: term
                                .attr(AttrKey::Coefficient)
                                .and_then(parse_f64)
                                .unwrap_or(0.0),
                            exponent: term
                                .attr(AttrKey::Exponent)
                                .and_then(|text| text.trim().parse::<i32>().ok())
                                .unwrap_or(0),
                        })
                        .collect();
                    return Some(Calibrator::Polynomial(terms));
                }
                Tag::SplineCalibrator => {
                    let mut points: Vec<SplinePoint> = child
                        .children_with(Tag::SplinePoint)
                        .map(|point| SplinePoint {
                            raw: point.attr(AttrKey::Raw).and_then(parse_f64).unwrap_or(0.0),
                            calibrated: point
                                .attr(AttrKey::Calibrated)
                                .and_then(parse_f64)
                                .unwrap_or(0.0),
                        })
                        .collect();
                    points.sort_by(|a, b| a.raw.total_cmp(&b.raw));
                    return Some(Calibrator::Spline(Spline {
                        order: child
                            .attr(AttrKey::Order)
                            .and_then(|text| text.trim().parse::<u8>().ok())
                            .unwrap_or(0),
                        points,
                        extrapolate: child
                            .attr(AttrKey::Extrapolate)
                            .is_some_and(|text| text.eq_ignore_ascii_case("true")),
                    }));
                }
                Tag::MathOperationCalibrator | Tag::CustomAlgorithm => {
                    let name = child.name().to_owned();
                    self.note_unsupported(&name, &child.path(), "calibrator kind out of scope");
                    return Some(Calibrator::Unsupported {
                        element: self.interner.intern(&name),
                    });
                }
                _ => {}
            }
        }
        None
    }

    fn lower_parameters(&mut self) -> Result<Vec<Parameter>, XtceError> {
        let pending = std::mem::take(&mut self.pending_params);
        let mut out = Vec::with_capacity(pending.len());
        for item in &pending {
            let element = item.element;
            let name = element.attr(AttrKey::Name).unwrap_or_default();
            // `<Parameter parameterTypeRef=..>` and `<Argument argumentTypeRef=..>` are the
            // same thing named twice; an argument arrives here because arguments are lowered
            // as parameters.
            let argument = element.tag() == Tag::Argument;
            let type_ref = element
                .attr(AttrKey::ParameterTypeRef)
                .or_else(|| element.attr(AttrKey::ArgumentTypeRef))
                .ok_or_else(|| XtceError::Missing {
                    what: "parameterTypeRef attribute",
                    path: element.path(),
                })?;
            let kind = if argument {
                RefKind::ArgumentType
            } else {
                RefKind::ParameterType
            };
            let type_id = self
                .resolve(type_ref, item.space_system, kind)
                .ok_or_else(|| XtceError::UnresolvedReference {
                    kind,
                    reference: type_ref.to_owned(),
                    path: element.path(),
                })?;

            out.push(Parameter {
                name: self.interner.intern(name),
                qualified_name: item.qualified_name,
                space_system: item.space_system,
                type_id: TypeId::new(type_id),
                short_description: element
                    .attr(AttrKey::ShortDescription)
                    .map(|text| self.interner.intern(text)),
                long_description: element
                    .child(Tag::LongDescription)
                    .and_then(Element::text)
                    .map(|text| self.interner.intern(text)),
                initial_value: element
                    .attr(AttrKey::InitialValue)
                    .map(|text| self.interner.intern(text)),
            });
        }
        self.pending_params = pending;
        Ok(out)
    }

    fn lower_containers(
        &mut self,
        types: &[ParameterType],
        parameters: &mut Vec<Parameter>,
    ) -> Result<(Vec<Container>, Vec<Entry>), XtceError> {
        let pending = std::mem::take(&mut self.pending_containers);
        let mut containers = Vec::with_capacity(pending.len());
        let mut entries: Vec<Entry> = Vec::new();

        for item in &pending {
            let element = item.element;
            let name = element.attr(AttrKey::Name).unwrap_or_default();

            let base_element = element.child(Tag::BaseContainer);
            let base = match base_element.and_then(|base| base.attr(AttrKey::ContainerRef)) {
                Some(reference) => Some(ContainerId::new(
                    self.resolve(reference, item.space_system, RefKind::Container)
                        .ok_or_else(|| XtceError::UnresolvedReference {
                            kind: RefKind::Container,
                            reference: reference.to_owned(),
                            path: element.path(),
                        })?,
                )),
                None => None,
            };

            let mut restriction = base_element
                .and_then(|base| base.child(Tag::RestrictionCriteria))
                .map(|criteria| self.lower_criteria_children(criteria, item.space_system))
                .unwrap_or_default();
            // An `<ArgumentAssignment>` is a restriction criterion written the other way
            // round. It says this command is the base command with an argument pinned to a
            // value; that pinning is what specialises the definition, and comparing the same
            // bits is what recognises an arriving packet as this command rather than as a
            // sibling. So it joins the criteria the container already has.
            if let Some(command) = item.command {
                restriction.extend(self.argument_assignments(command)?);
            }

            let start = entries.len();
            if let Some(list) = element.child(Tag::EntryList) {
                for entry in list.children() {
                    self.lower_entry(
                        entry,
                        item.space_system,
                        item.command,
                        types,
                        parameters,
                        &mut entries,
                    )?;
                }
            }

            containers.push(Container {
                name: self.interner.intern(name),
                qualified_name: item.qualified_name,
                space_system: item.space_system,
                // A container is abstract when it says so — or when it packs a command that
                // does. `abstract` on a `MetaCommand` means it is "not instantiated, rather
                // only used as bases to inherit from", so no packet is one, so its container
                // can never be the final match for a packet either. That is the same thing
                // `abstract` means on a container, said one level up.
                is_abstract: element
                    .attr(AttrKey::Abstract)
                    .is_some_and(|text| text.eq_ignore_ascii_case("true"))
                    || item
                        .command
                        .is_some_and(|command| self.command_is_abstract(command)),
                base,
                is_command: item.is_command,
                command: item.command,
                restriction,
                entries: Span::between(start, entries.len()),
                inheritors: Vec::new(),
                short_description: element
                    .attr(AttrKey::ShortDescription)
                    .map(|text| self.interner.intern(text)),
                long_description: element
                    .child(Tag::LongDescription)
                    .and_then(Element::text)
                    .map(|text| self.interner.intern(text)),
            });
        }
        self.pending_containers = pending;
        Ok((containers, entries))
    }

    /// `<FixedValueEntry>`: bits the definition writes and nobody supplies.
    ///
    /// The bytes go into a shared arena because an entry is `Copy` and cannot own them. The
    /// width is the entry's own and is not derived from the bytes: XTCE requires both
    /// attributes and does not require them to agree.
    fn fixed_value_entry(&mut self, element: Element<'d>) -> Result<EntryKind, XtceError> {
        let Some(hex) = element.attr(AttrKey::BinaryValue) else {
            return Err(XtceError::Missing {
                what: "binaryValue attribute",
                path: element.path(),
            });
        };
        let Some(size_in_bits) = element
            .attr(AttrKey::SizeInBits)
            .and_then(|text| text.trim().parse::<u32>().ok())
        else {
            return Err(XtceError::Missing {
                what: "sizeInBits attribute",
                path: element.path(),
            });
        };
        let name = element
            .attr(AttrKey::Name)
            .map(|text| self.interner.intern(text));
        let bytes = parse_hex(hex);
        let start = self.fixed_values.len();
        self.fixed_values.extend_from_slice(&bytes);
        Ok(EntryKind::FixedValue {
            name,
            value: Span::between(start, self.fixed_values.len()),
            size_in_bits,
        })
    }

    /// Lowers one `<EntryList>` child, appending one entry — or, for an array, several.
    fn lower_entry(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
        command: Option<MetaCommandId>,
        types: &[ParameterType],
        parameters: &mut Vec<Parameter>,
        out: &mut Vec<Entry>,
    ) -> Result<(), XtceError> {
        // Parsed before the match rather than after it, because the composite arm returns
        // early: an array entry carrying either of these used to drop it on the way past.
        let location = entry_location(element);
        let repeat = entry_repeat(element);

        // What this reader cannot act on, reported rather than passed over. An entry whose
        // bits are claimed when they should not be does not go missing — it shifts every
        // entry behind it, and the values that come out are wrong rather than absent.
        if let Some(reason) = entry_out_of_scope(element, repeat) {
            self.push_unsupported_entry(element, reason, location, repeat, out);
            return Ok(());
        }

        let kind = match element.tag() {
            Tag::ParameterRefEntry
            | Tag::ArrayParameterRefEntry
            | Tag::ArgumentRefEntry
            | Tag::ArrayArgumentRefEntry => {
                let argument = matches!(
                    element.tag(),
                    Tag::ArgumentRefEntry | Tag::ArrayArgumentRefEntry
                );
                let attribute = if argument {
                    AttrKey::ArgumentRef
                } else {
                    AttrKey::ParameterRef
                };
                let reference = element.attr(attribute).ok_or_else(|| XtceError::Missing {
                    what: if argument {
                        "argumentRef attribute"
                    } else {
                        "parameterRef attribute"
                    },
                    path: element.path(),
                })?;
                // An argument reference is resolved against the command that owns this
                // container and nowhere else — "there is no path, this is a local
                // reference" — so it can neither reach another command's argument nor fall
                // back to a telemetry parameter that happens to share the name.
                let found = if argument {
                    self.lower_argument_lookup(command, reference)
                } else {
                    self.resolve(reference, space_system, RefKind::Parameter)
                        .map(ParamId::new)
                };
                let id = found.ok_or_else(|| XtceError::UnresolvedReference {
                    kind: RefKind::Parameter,
                    reference: reference.to_owned(),
                    path: element.path(),
                })?;

                // An array is a repetition, so it becomes a repetition of entries. Doing it
                // here means the interpreter, the code generator and the flight encoder all
                // see ordinary fields and none of them has to know arrays exist.
                if let Some(expanded) = self.expand_composite(element, id, types, parameters)? {
                    if location.is_some() || repeat.is_some() {
                        self.push_unsupported_entry(
                            element,
                            "a LocationInContainerInBits or a RepeatEntry on an entry that \
                             names an array or an aggregate; the entry becomes one field per \
                             leaf here, and neither is carried onto the leaves",
                            location,
                            repeat,
                            out,
                        );
                        return Ok(());
                    }
                    out.extend(expanded);
                    return Ok(());
                }
                EntryKind::Parameter(id)
            }
            Tag::FixedValueEntry => self.fixed_value_entry(element)?,
            Tag::ContainerRefEntry => {
                let reference =
                    element
                        .attr(AttrKey::ContainerRef)
                        .ok_or_else(|| XtceError::Missing {
                            what: "containerRef attribute",
                            path: element.path(),
                        })?;
                let id = self
                    .resolve(reference, space_system, RefKind::Container)
                    .ok_or_else(|| XtceError::UnresolvedReference {
                        kind: RefKind::Container,
                        reference: reference.to_owned(),
                        path: element.path(),
                    })?;
                EntryKind::Container(ContainerId::new(id))
            }
            _ => {
                let name = element.name().to_owned();
                self.note_unsupported(&name, &element.path(), "entry kind out of scope");
                EntryKind::Unsupported {
                    element: self.interner.intern(&name),
                }
            }
        };

        out.push(Entry {
            kind,
            location,
            repeat,
        });
        Ok(())
    }

    /// Turns an entry that names an array or an aggregate into one entry per leaf field, or
    /// `None` if it names neither.
    fn expand_composite(
        &mut self,
        element: Element<'d>,
        parameter: ParamId,
        types: &[ParameterType],
        parameters: &mut Vec<Parameter>,
    ) -> Result<Option<Vec<Entry>>, XtceError> {
        let Some(declared) = parameters.get(parameter.index()) else {
            return Ok(None);
        };
        let type_id = declared.type_id;
        let Some(ty) = types.get(type_id.index()) else {
            return Ok(None);
        };
        if !matches!(ty.kind, TypeKind::Array { .. } | TypeKind::Aggregate { .. }) {
            return Ok(None);
        }

        let base_name = self.interner.resolve(declared.name).to_owned();
        let qualified = declared.qualified_name;
        let space_system = declared.space_system;
        let path = element.path();

        // A `<DimensionList>` on the *entry* subsets the outermost array; the type carries
        // the full size. XTCE: "Only used for subsetting an array. The array's maximum
        // dimension sizes are set in the type." It says nothing about subsetting anything
        // nested, so nothing nested is subset.
        let subset = match element.child(Tag::DimensionList) {
            None => None,
            Some(list) => {
                let mut chosen = Vec::new();
                for dimension in list.children_with(Tag::Dimension) {
                    let (Some(start), Some(end)) = (
                        fixed_index(dimension.child(Tag::StartingIndex)),
                        fixed_index(dimension.child(Tag::EndingIndex)),
                    ) else {
                        return Err(XtceError::ArrayNotExpanded {
                            reason: "a subset with an index read from the packet cannot be \
                                     expanded when the file is loaded"
                                .to_owned(),
                            path,
                        });
                    };
                    chosen.push(ArrayDimension { start, end });
                }
                Some(chosen)
            }
        };

        let mut leaves = Vec::new();
        let mut visiting = Vec::new();
        self.collect_leaves(
            type_id,
            &base_name,
            subset.as_deref(),
            &mut Walk {
                types,
                out: &mut leaves,
                visiting: &mut visiting,
                path: &path,
            },
        )?;

        let mut out = Vec::with_capacity(leaves.len());
        for (name, leaf) in leaves {
            let Ok(id) = u32::try_from(parameters.len()) else {
                return Err(XtceError::ArrayNotExpanded {
                    reason: "the parameter arena is full".to_owned(),
                    path,
                });
            };
            parameters.push(Parameter {
                name: self.interner.intern(&name),
                qualified_name: qualified,
                space_system,
                type_id: leaf,
                short_description: None,
                long_description: None,
                initial_value: None,
            });
            out.push(Entry {
                kind: EntryKind::Parameter(ParamId::new(id)),
                location: None,
                repeat: None,
            });
        }
        Ok(Some(out))
    }

    /// Walks a type, appending `(name, type)` for every leaf it eventually contains.
    ///
    /// `visiting` holds the composite types on the current path. XTCE says circular member
    /// references are not allowed, but a file can still contain one, and following it would
    /// not terminate.
    fn collect_leaves(
        &mut self,
        type_id: TypeId,
        prefix: &str,
        subset: Option<&[ArrayDimension]>,
        walk: &mut Walk<'_>,
    ) -> Result<(), XtceError> {
        let Some(ty) = walk.types.get(type_id.index()) else {
            return Err(XtceError::ArrayNotExpanded {
                reason: "a member or element type does not resolve".to_owned(),
                path: walk.path.to_owned(),
            });
        };

        match &ty.kind {
            TypeKind::Array {
                element,
                dimensions,
            } => {
                let element = *element;
                let declared = dimensions.clone();
                let spans = match subset {
                    None => declared,
                    Some(chosen) => {
                        if chosen.len() != declared.len() {
                            return Err(XtceError::ArrayNotExpanded {
                                reason: format!(
                                    "the type has {} dimension(s) and the subset gives {}",
                                    declared.len(),
                                    chosen.len()
                                ),
                                path: walk.path.to_owned(),
                            });
                        }
                        for (one, whole) in chosen.iter().zip(&declared) {
                            if one.start < whole.start || one.end > whole.end || one.is_empty() {
                                return Err(XtceError::ArrayNotExpanded {
                                    reason: format!(
                                        "the subset {}..={} lies outside the declared {}..={}",
                                        one.start, one.end, whole.start, whole.end
                                    ),
                                    path: walk.path.to_owned(),
                                });
                            }
                        }
                        chosen.to_vec()
                    }
                };

                Self::enter(type_id, walk.visiting, walk.path)?;
                // Row-major, because XTCE says so: "the last dimension is assumed to be the
                // least significant — that is this dimension will cycle through its
                // combination before the next to last dimension changes."
                let count = spans
                    .iter()
                    .try_fold(1usize, |total, span| total.checked_mul(span.len()?));
                let Some(count) = count else {
                    return Err(XtceError::ArrayNotExpanded {
                        reason: "the element count overflows a usize".to_owned(),
                        path: walk.path.to_owned(),
                    });
                };
                let mut indices: Vec<i64> = spans.iter().map(|span| span.start).collect();
                for _ in 0..count {
                    let mut name = prefix.to_owned();
                    for index in &indices {
                        let _ = std::fmt::Write::write_fmt(&mut name, format_args!("[{index}]"));
                    }
                    self.collect_leaves(element, &name, None, walk)?;
                    for (axis, index) in indices.iter_mut().enumerate().rev() {
                        *index += 1;
                        if *index <= spans[axis].end {
                            break;
                        }
                        *index = spans[axis].start;
                    }
                }
                walk.visiting.pop();
            }

            TypeKind::Aggregate { members } => {
                let members = members.clone();
                Self::enter(type_id, walk.visiting, walk.path)?;
                for member in &members {
                    // "Each member may be addressed by the dot syntax similar to C such as
                    // P.voltage."
                    let name = format!("{prefix}.{}", self.interner.resolve(member.name));
                    self.collect_leaves(member.type_id, &name, None, walk)?;
                }
                walk.visiting.pop();
            }

            _ => {
                if walk.out.len() >= MAX_EXPANDED_FIELDS {
                    return Err(XtceError::ArrayNotExpanded {
                        reason: format!(
                            "more than {MAX_EXPANDED_FIELDS} fields, and each one becomes a \
                             parameter and a struct field"
                        ),
                        path: walk.path.to_owned(),
                    });
                }
                walk.out.push((prefix.to_owned(), type_id));
            }
        }
        Ok(())
    }

    /// Records that the expansion has descended into a composite type, refusing a cycle.
    fn enter(type_id: TypeId, visiting: &mut Vec<TypeId>, path: &str) -> Result<(), XtceError> {
        if visiting.contains(&type_id) {
            return Err(XtceError::ArrayNotExpanded {
                reason: "the type contains itself, so expanding it would not terminate".to_owned(),
                path: path.to_owned(),
            });
        }
        visiting.push(type_id);
        Ok(())
    }

    // --------------------------------------------------------------- match criteria

    /// Lowers the children of a `<RestrictionCriteria>` or `<ContextMatch>` element.
    fn lower_criteria_children(
        &mut self,
        holder: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Vec<MatchCriteria> {
        let mut out = Vec::new();
        for child in holder.children() {
            match child.tag() {
                Tag::Comparison => {
                    out.push(self.lower_comparison(child, space_system));
                }
                Tag::ComparisonList => {
                    for comparison in child.children_with(Tag::Comparison) {
                        out.push(self.lower_comparison(comparison, space_system));
                    }
                }
                Tag::BooleanExpression => {
                    out.push(match self.lower_boolean_expression(child, space_system) {
                        Some(expr) => MatchCriteria::Boolean(expr),
                        None => self.unsupported_criteria(child, "unrecognised BooleanExpression"),
                    });
                }
                Tag::CustomAlgorithm => {
                    out.push(self.unsupported_criteria(child, "CustomAlgorithm criteria"));
                }
                _ => {}
            }
        }
        out
    }

    /// One argument of `command`, by the bare name an `argumentRef` writes.
    fn lower_argument_lookup(&self, command: Option<MetaCommandId>, name: &str) -> Option<ParamId> {
        let name = self.interner.get(name.trim())?;
        self.command_arguments
            .get(command?.index())
            .and_then(|arguments| arguments.get(&name))
            .copied()
    }

    /// The criteria a command's `<ArgumentAssignmentList>` amounts to.
    ///
    /// Each assignment pins an argument of the *base* command to a value, so each becomes a
    /// comparison against that argument. `argumentValue` is documented as a
    /// "calibrated/engineering value", which is what `useCalibratedValue` defaulting to true
    /// means for a `<Comparison>` — so the criterion is built that way, and an assignment on
    /// an enumerated argument then compares labels, which the code generator refuses by name
    /// rather than compiling into something that disagrees with the interpreter.
    fn argument_assignments(
        &mut self,
        command: MetaCommandId,
    ) -> Result<Vec<MatchCriteria>, XtceError> {
        let Some(pending) = self.pending_commands.get(command.index()) else {
            return Ok(Vec::new());
        };
        let Some(base) = pending.element.child(Tag::BaseMetaCommand) else {
            return Ok(Vec::new());
        };
        let Some(list) = base.child(Tag::ArgumentAssignmentList) else {
            return Ok(Vec::new());
        };

        let assignments: Vec<Element<'d>> = list.children_with(Tag::ArgumentAssignment).collect();
        let mut out = Vec::with_capacity(assignments.len());
        for assignment in assignments {
            let Some(name) = assignment.attr(AttrKey::ArgumentName) else {
                return Err(XtceError::Missing {
                    what: "argumentName attribute",
                    path: assignment.path(),
                });
            };
            let parameter = self
                .lower_argument_lookup(Some(command), name)
                .ok_or_else(|| XtceError::UnresolvedReference {
                    kind: RefKind::Parameter,
                    reference: name.to_owned(),
                    path: assignment.path(),
                })?;
            let literal = assignment.attr(AttrKey::ArgumentValue).unwrap_or_default();
            let value = ComparisonValue::new(self.interner.intern(literal), literal);
            out.push(MatchCriteria::Comparison(Comparison {
                parameter,
                operator: CompareOp::Equal,
                value,
                use_calibrated: true,
            }));
        }
        Ok(out)
    }

    /// Every telecommand, once the containers behind them are lowered.
    fn lower_commands(&mut self) -> Vec<MetaCommand> {
        let pending = std::mem::take(&mut self.pending_commands);
        let out = pending
            .iter()
            .map(|command| MetaCommand {
                name: self
                    .interner
                    .intern(command.element.attr(AttrKey::Name).unwrap_or_default()),
                qualified_name: command.qualified_name,
                space_system: command.space_system,
                is_abstract: command
                    .element
                    .attr(AttrKey::Abstract)
                    .is_some_and(|text| text.eq_ignore_ascii_case("true")),
                base: command.base,
                container: command.container,
                arguments: command
                    .arguments
                    .iter()
                    .map(|&(_, parameter)| parameter)
                    .collect(),
                short_description: command
                    .element
                    .attr(AttrKey::ShortDescription)
                    .map(|text| self.interner.intern(text)),
                long_description: command
                    .element
                    .child(Tag::LongDescription)
                    .and_then(Element::text)
                    .map(|text| self.interner.intern(text)),
            })
            .collect();
        self.pending_commands = pending;
        out
    }

    fn lower_comparison(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> MatchCriteria {
        let reference = element.attr(AttrKey::ParameterRef).unwrap_or_default();
        let Some(parameter) = self.resolve_parameter_opt(reference, space_system) else {
            return self
                .unsupported_criteria(element, "comparison references an unknown parameter");
        };
        let operator = element
            .attr(AttrKey::ComparisonOperator)
            .and_then(CompareOp::parse)
            .unwrap_or(CompareOp::Equal);
        let literal = element.attr(AttrKey::Value).unwrap_or_default();
        let value = ComparisonValue::new(self.interner.intern(literal), literal);
        MatchCriteria::Comparison(Comparison {
            parameter,
            operator,
            value,
            use_calibrated: use_calibrated(element),
        })
    }

    fn lower_boolean_expression(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Option<BooleanExpr> {
        for child in element.children() {
            match child.tag() {
                Tag::Condition => {
                    return self
                        .lower_condition(child, space_system)
                        .map(BooleanExpr::Condition);
                }
                Tag::ANDedConditions => {
                    return Some(BooleanExpr::And(self.lower_expr_list(child, space_system)));
                }
                Tag::ORedConditions => {
                    return Some(BooleanExpr::Or(self.lower_expr_list(child, space_system)));
                }
                _ => {}
            }
        }
        None
    }

    fn lower_expr_list(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Vec<BooleanExpr> {
        let mut out = Vec::new();
        for child in element.children() {
            match child.tag() {
                Tag::Condition => {
                    if let Some(condition) = self.lower_condition(child, space_system) {
                        out.push(BooleanExpr::Condition(condition));
                    }
                }
                Tag::ANDedConditions => {
                    out.push(BooleanExpr::And(self.lower_expr_list(child, space_system)));
                }
                Tag::ORedConditions => {
                    out.push(BooleanExpr::Or(self.lower_expr_list(child, space_system)));
                }
                _ => {}
            }
        }
        out
    }

    fn lower_condition(
        &mut self,
        element: Element<'d>,
        space_system: SpaceSystemId,
    ) -> Option<Condition> {
        let mut operands = Vec::new();
        let mut operator = None;

        for child in element.children() {
            match child.tag() {
                Tag::ParameterInstanceRef => {
                    let reference = child.attr(AttrKey::ParameterRef).unwrap_or_default();
                    let parameter = self.resolve_parameter_opt(reference, space_system)?;
                    operands.push(Operand::Parameter {
                        parameter,
                        use_calibrated: use_calibrated(child),
                    });
                }
                Tag::Value => {
                    let text = child.text().unwrap_or_default();
                    operands.push(Operand::Literal(ComparisonValue::new(
                        self.interner.intern(text),
                        text,
                    )));
                }
                Tag::ComparisonOperator => {
                    operator = child.text().and_then(CompareOp::parse);
                }
                _ => {}
            }
        }

        let mut operands = operands.into_iter();
        Some(Condition {
            left: operands.next()?,
            operator: operator?,
            right: operands.next()?,
        })
    }

    fn unsupported_criteria(
        &mut self,
        element: Element<'d>,
        reason: &'static str,
    ) -> MatchCriteria {
        let name = element.name().to_owned();
        self.note_unsupported(&name, &element.path(), reason);
        MatchCriteria::Unsupported {
            element: self.interner.intern(&name),
        }
    }

    // ------------------------------------------------------------------- resolution

    fn resolve_parameter_opt(&mut self, reference: &str, from: SpaceSystemId) -> Option<ParamId> {
        self.resolve(reference, from, RefKind::Parameter)
            .map(ParamId::new)
    }

    /// Resolves an XTCE name reference to a raw index.
    ///
    /// XTCE reference syntax (CCSDS 660.1-G-2 §4.3.1) is path-like:
    ///
    /// A final fallback searches the whole document by unqualified name. That is not in the
    /// standard, but the reference implementation keys its lookup tables that way, and
    /// several shipped databases rely on it.
    fn resolve(&mut self, reference: &str, from: SpaceSystemId, kind: RefKind) -> Option<u32> {
        let reference = reference.trim();
        if reference.is_empty() {
            return None;
        }
        let is_path = reference.contains('/');

        // With a single space system — which is every file in `testdata`, and most databases
        // that are not assembled from several missions — the current system's table and the
        // document-wide leaf table hold exactly the same entries, so building and hashing a
        // qualified name would be pure overhead. This is not a different resolution rule,
        // just the same one arrived at directly.
        if !is_path && self.space_systems.len() == 1 {
            return self.lookup_leaf(reference, kind);
        }

        let mut scratch = std::mem::take(&mut self.scratch);
        let found = self.resolve_by_path(&mut scratch, reference, from, kind, is_path);
        self.scratch = scratch;
        found.or_else(|| self.lookup_leaf(last_segment(reference), kind))
    }

    fn resolve_by_path(
        &self,
        scratch: &mut String,
        reference: &str,
        from: SpaceSystemId,
        kind: RefKind,
        is_path: bool,
    ) -> Option<u32> {
        if reference.starts_with('/') {
            normalize_into(scratch, "", reference);
            return self.lookup_qualified(scratch, kind);
        }

        let mut cursor = Some(from);
        while let Some(system) = cursor {
            let base = self.ss_paths.get(system.index()).map_or("", String::as_str);
            normalize_into(scratch, base, reference);
            if let Some(id) = self.lookup_qualified(scratch, kind) {
                return Some(id);
            }
            if is_path {
                // Path-shaped references are tried relative to the current system and
                // absolutely; they do not walk up the tree.
                break;
            }
            cursor = self
                .space_systems
                .get(system.index())
                .and_then(|system| system.parent);
        }
        None
    }

    fn lookup_leaf(&self, leaf: &str, kind: RefKind) -> Option<u32> {
        let leaf_id = self.interner.get(leaf)?;
        match kind {
            RefKind::Parameter => self.param_by_leaf.get(&leaf_id).map(|id| id.raw()),
            RefKind::ParameterType => self.type_by_leaf.get(&leaf_id).map(|id| id.raw()),
            RefKind::ArgumentType => self.argument_type_by_leaf.get(&leaf_id).map(|id| id.raw()),
            RefKind::Container => self.container_by_leaf.get(&leaf_id).map(|id| id.raw()),
            RefKind::MetaCommand => self.command_by_leaf.get(&leaf_id).map(|id| id.raw()),
        }
    }

    fn lookup_qualified(&self, qualified: &str, kind: RefKind) -> Option<u32> {
        let id = self.interner.get(qualified)?;
        match kind {
            RefKind::Parameter => self.param_by_qualified.get(&id).map(|id| id.raw()),
            RefKind::ParameterType => self.type_by_qualified.get(&id).map(|id| id.raw()),
            RefKind::ArgumentType => self.argument_type_by_qualified.get(&id).map(|id| id.raw()),
            RefKind::Container => self.container_by_qualified.get(&id).map(|id| id.raw()),
            RefKind::MetaCommand => self.command_by_qualified.get(&id).map(|id| id.raw()),
        }
    }

    /// Records `reason` against `element` and puts an unsupported entry in its place.
    ///
    /// The entry is pushed rather than dropped: it keeps the place the definition gave it, so
    /// a caller reading the container sees something it cannot decode where the bits are,
    /// instead of a container that is quietly one entry shorter than the packet.
    fn push_unsupported_entry(
        &mut self,
        element: Element<'d>,
        reason: &'static str,
        location: Option<Location>,
        repeat: Option<u32>,
        out: &mut Vec<Entry>,
    ) {
        let name = element.name().to_owned();
        self.note_unsupported(&name, &element.path(), reason);
        out.push(Entry {
            kind: EntryKind::Unsupported {
                element: self.interner.intern(&name),
            },
            location,
            repeat,
        });
    }

    fn note_unsupported(&mut self, element: &str, path: &str, reason: &'static str) {
        self.unsupported.push(Unsupported {
            element: element.to_owned(),
            path: path.to_owned(),
            reason,
        });
    }
}

/// The `<LocationInContainerInBits>` an entry carries, if any.
fn entry_location(element: Element<'_>) -> Option<Location> {
    element
        .child(Tag::LocationInContainerInBits)
        .and_then(|node| {
            let offset = node
                .child(Tag::FixedValue)
                .and_then(Element::text)
                .or_else(|| node.text())
                .and_then(|text| text.trim().parse::<i64>().ok())?;
            Some(Location {
                reference: location_reference(node.attr(AttrKey::ReferenceLocation)),
                offset_in_bits: offset,
            })
        })
}

/// The repetition count an entry carries, when it is a plain `<FixedValue>`.
///
/// `None` covers both "no `<RepeatEntry>`" and "a `<RepeatEntry>` whose count comes from the
/// packet". [`entry_out_of_scope`] is what tells those two apart, because they are not the
/// same thing and decoding once is only right for the first.
fn entry_repeat(element: Element<'_>) -> Option<u32> {
    element
        .child(Tag::RepeatEntry)
        .and_then(|repeat| repeat.child(Tag::Count))
        .and_then(|count| count.child(Tag::FixedValue))
        .and_then(Element::text)
        .and_then(|text| text.trim().parse::<u32>().ok())
}

/// Why an entry cannot be read as written, if it cannot.
///
/// Both of these used to be dropped without a word, and dropping them is worse than it sounds:
/// the entry keeps its place in the container, so its bits are still claimed and every entry
/// behind it is still read at the offset that assumes them. The values that come out are wrong
/// rather than missing, and nothing says so.
fn entry_out_of_scope(element: Element<'_>, repeat: Option<u32>) -> Option<&'static str> {
    if element.child(Tag::IncludeCondition).is_some() {
        return Some(
            "an IncludeCondition, which decides at decode time whether the entry is present \
             at all; reading it unconditionally claims bits the packet may not have given it",
        );
    }
    if element.child(Tag::RepeatEntry).is_some() && repeat.is_none() {
        return Some(
            "a RepeatEntry whose Count is not a FixedValue; the count is in the packet and \
             this reader does not read it, so the entry would decode exactly once",
        );
    }
    None
}

#[derive(Clone, Copy)]
enum Definition {
    Type,
    /// A type from an `<ArgumentTypeSet>`, or a command's `<ParameterTypeSet>`: the two share
    /// a namespace with each other and not with the telemetry types.
    ArgumentType,
    Parameter,
    Container,
}

fn insert_unique<T: Copy>(
    table: &mut FxHashMap<NameId, T>,
    key: NameId,
    value: T,
    kind: RefKind,
    qualified: &str,
    element: &Element<'_>,
) -> Result<(), XtceError> {
    if table.insert(key, value).is_some() {
        return Err(XtceError::DuplicateDefinition {
            kind,
            name: qualified.to_owned(),
            path: element.path(),
        });
    }
    Ok(())
}

/// Writes `base/reference` into `out`, resolving `.` and `..` segments.
/// Writes `base/reference` into `out`, resolving `.` and `..` segments.
///
/// Almost every reference in a real database is a plain name or a plain path, so the common
/// case is a concatenation with no segment analysis and no allocation. The general case
/// falls back to walking segments, which needs a stack because `..` pops.
fn normalize_into(out: &mut String, base: &str, reference: &str) {
    out.clear();
    if !needs_normalising(reference) {
        if !reference.starts_with('/') {
            out.push_str(base);
        }
        if !reference.starts_with('/') {
            out.push('/');
        }
        out.push_str(reference);
        return;
    }

    let mut segments: Vec<&str> = Vec::new();
    if !reference.starts_with('/') {
        segments.extend(base.split('/').filter(|part| !part.is_empty()));
    }
    for part in reference.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }
    for segment in segments {
        out.push('/');
        out.push_str(segment);
    }
}

/// Whether a reference contains `.`, `..` or empty segments that need resolving.
fn needs_normalising(reference: &str) -> bool {
    if !reference.contains('.') && !reference.contains("//") {
        return false;
    }
    reference
        .split('/')
        .any(|part| part.is_empty() || part == "." || part == "..")
}

/// The part of a reference after the last `/`.
fn last_segment(reference: &str) -> &str {
    match reference.rsplit_once('/') {
        Some((_, leaf)) => leaf,
        None => reference,
    }
}

/// Folds a time parameter type's `<Encoding offset=.. scale=..>` into a polynomial
/// calibrator on its data encoding.
///
/// XTCE 4.3.2.4.8.3 expresses a time parameter's unit conversion as attributes rather than a
/// calibrator, but the two mean the same thing, so representing it as one keeps the decoder
/// from needing a special case. The offset term is emitted before the scale term: the terms
/// are summed in document order and floating-point addition is not associative, so the order
/// is part of the result.
fn apply_time_unit_scaler(type_element: Element<'_>, encoding: &mut DataEncoding) {
    let Some(element) = type_element.child(Tag::Encoding) else {
        return;
    };
    let offset = element.attr(AttrKey::Offset).and_then(parse_f64);
    let scale = element.attr(AttrKey::Scale).and_then(parse_f64);

    let mut terms = Vec::new();
    if let Some(offset) = offset {
        terms.push(PolynomialTerm {
            coefficient: offset,
            exponent: 0,
        });
    }
    match (scale, offset) {
        (Some(scale), _) => terms.push(PolynomialTerm {
            coefficient: scale,
            exponent: 1,
        }),
        // An offset with no scale still needs the identity term, or the raw value would be
        // dropped entirely.
        (None, Some(_)) => terms.push(PolynomialTerm {
            coefficient: 1.0,
            exponent: 1,
        }),
        (None, None) => return,
    }

    let calibrator = Some(Calibrator::Polynomial(terms));
    match encoding {
        DataEncoding::Integer(integer) => integer.default_calibrator = calibrator,
        DataEncoding::Float(float) => float.default_calibrator = calibrator,
        DataEncoding::String(_) | DataEncoding::Binary(_) | DataEncoding::None => {}
    }
}

fn integer_coding(text: &str) -> IntegerCoding {
    match text {
        // `twosCompliment` is a long-standing typo in the XTCE ecosystem and appears in
        // shipped databases; `signed` is informal but equally common.
        "twosComplement" | "twosCompliment" | "signed" => IntegerCoding::TwosComplement,
        "signMagnitude" => IntegerCoding::SignMagnitude,
        "onesComplement" | "onesCompliment" => IntegerCoding::OnesComplement,
        _ => IntegerCoding::Unsigned,
    }
}

fn float_coding(text: &str) -> FloatCoding {
    match text {
        "MILSTD_1750A" | "MIL-1750A" => FloatCoding::MilStd1750A,
        _ => FloatCoding::Ieee754,
    }
}

/// The state a leaf walk carries, which does not change as it descends.
///
/// Grouped because it is four things that travel together through a recursion, and passing
/// them one by one made the signature longer than the function.
struct Walk<'a> {
    types: &'a [ParameterType],
    out: &'a mut Vec<(String, TypeId)>,
    visiting: &'a mut Vec<TypeId>,
    path: &'a str,
}

/// How many leaf fields one entry may expand into.
const MAX_EXPANDED_FIELDS: usize = 4096;

/// A `<StartingIndex>` or `<EndingIndex>` that is a plain `<FixedValue>`.
///
/// `None` for the `DynamicValue` and `DiscreteLookupList` forms, which the caller refuses:
/// both make the count a property of the packet.
fn fixed_index(element: Option<Element<'_>>) -> Option<i64> {
    element?
        .child(Tag::FixedValue)
        .and_then(Element::text)
        .and_then(|text| text.trim().parse::<i64>().ok())
}

fn byte_order(text: Option<&str>) -> ByteOrder {
    match text {
        Some("leastSignificantByteFirst") => ByteOrder::LeastSignificantFirst,
        _ => ByteOrder::MostSignificantFirst,
    }
}

fn charset(text: &str) -> Charset {
    match text {
        "US-ASCII" => Charset::UsAscii,
        "ISO-8859-1" => Charset::Iso8859_1,
        "Windows-1252" => Charset::Windows1252,
        "UTF-16" | "UTF-16BE" | "UTF-16LE" => Charset::Utf16,
        "UTF-32" | "UTF-32BE" | "UTF-32LE" => Charset::Utf32,
        _ => Charset::Utf8,
    }
}

fn location_reference(text: Option<&str>) -> LocationReference {
    match text {
        Some("containerStart") => LocationReference::ContainerStart,
        Some("containerEnd") => LocationReference::ContainerEnd,
        Some("nextEntry") => LocationReference::NextEntry,
        _ => LocationReference::PreviousEntry,
    }
}

fn use_calibrated(element: Element<'_>) -> bool {
    element
        .attr(AttrKey::UseCalibratedValue)
        .is_none_or(|text| text.eq_ignore_ascii_case("true"))
}

fn linear_adjustment(element: Element<'_>) -> LinearAdjustment {
    LinearAdjustment {
        slope: element
            .attr(AttrKey::Slope)
            .and_then(parse_f64)
            .unwrap_or(0.0),
        intercept: element
            .attr(AttrKey::Intercept)
            .and_then(parse_f64)
            .unwrap_or(0.0),
    }
}

fn parse_f64(text: &str) -> Option<f64> {
    text.trim().parse::<f64>().ok()
}

fn parse_i128(text: &str) -> Option<i128> {
    let text = text.trim();
    if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
        return i128::from_str_radix(hex, 16).ok();
    }
    text.parse::<i128>().ok()
}

/// Parses a hex string such as `"58"` or `"5800"` into bytes, ignoring stray whitespace.
fn parse_hex(text: &str) -> Vec<u8> {
    let digits: Vec<u8> = text.bytes().filter(u8::is_ascii_hexdigit).collect();
    digits
        .chunks(2)
        .filter(|pair| pair.len() == 2)
        .filter_map(|pair| {
            let hi = (pair.first().copied()? as char).to_digit(16)?;
            let lo = (pair.get(1).copied()? as char).to_digit(16)?;
            u8::try_from(hi * 16 + lo).ok()
        })
        .collect()
}

/// Fills each container's `inheritors` list from the `base` links.
fn link_inheritors(containers: &mut [Container]) {
    let links: Vec<(ContainerId, ContainerId)> = containers
        .iter()
        .enumerate()
        .filter_map(|(index, container)| {
            let base = container.base?;
            let id = ContainerId::new(u32::try_from(index).unwrap_or(u32::MAX));
            Some((base, id))
        })
        .collect();
    for (base, child) in links {
        if let Some(container) = containers.get_mut(base.index()) {
            container.inheritors.push(child);
        }
    }
}

/// Rejects cyclic container inheritance.
///
/// Without this, a database where `A` extends `B` and `B` extends `A` would recurse until
/// the stack overflows on the first packet. Iterative three-colour marking keeps the check
/// itself stack-safe for arbitrarily deep hierarchies.
fn check_acyclic(containers: &[Container], interner: &Interner) -> Result<(), XtceError> {
    #[derive(Clone, Copy, PartialEq)]
    enum Mark {
        Unvisited,
        InProgress,
        Done,
    }

    let mut marks = vec![Mark::Unvisited; containers.len()];
    for start in 0..containers.len() {
        if marks.get(start).copied() != Some(Mark::Unvisited) {
            continue;
        }
        let mut chain: Vec<usize> = Vec::new();
        let mut cursor = Some(start);
        while let Some(index) = cursor {
            match marks.get(index).copied() {
                Some(Mark::InProgress) => {
                    let cycle_start = chain.iter().position(|&item| item == index).unwrap_or(0);
                    let names = chain
                        .get(cycle_start..)
                        .unwrap_or_default()
                        .iter()
                        .filter_map(|&item| containers.get(item))
                        .map(|container| interner.resolve(container.qualified_name).to_owned())
                        .collect::<Vec<_>>();
                    return Err(XtceError::InheritanceCycle { chain: names });
                }
                Some(Mark::Done) | None => break,
                Some(Mark::Unvisited) => {}
            }
            if let Some(mark) = marks.get_mut(index) {
                *mark = Mark::InProgress;
            }
            chain.push(index);
            cursor = containers
                .get(index)
                .and_then(|c| c.base)
                .map(super::ids::ContainerId::index);
        }
        for index in chain {
            if let Some(mark) = marks.get_mut(index) {
                *mark = Mark::Done;
            }
        }
    }
    Ok(())
}