ridl-ir 0.16.0

The RIDL intermediate representation: the typl surface plus the ridl interaction layer, generated from a versioned protobuf schema.
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
//! The lowering: one IR package, over a stated scope, into one
//! [`v1::Model`](super::v1::Model).
//!
//! Total by construction (design note D-1). Malformed IR is carried as a fact
//! — a [`TupleCollision`](super::v1::TupleCollision), an
//! [`FbUnbounded`](super::v1::FbUnbounded) with its attribution, a
//! [`Type`](super::v1::Type) with no kind — rather than turned into an error,
//! because every printer refuses those today with its own message and must
//! keep doing so byte for byte.
//!
//! Positional correspondence is an invariant: `declarations[i]` is lowered
//! from `Package.decls[i]`, `interfaces[i]` from the `i`-th shape of
//! `Package::shapes()`, a `Struct.slots[j]` from `StructDef.members[j]`, an
//! `Interface.slots[j]` from `Interface.interactions[j]`.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use super::clauses;
use super::docs::{doc_links, model_rules};
use super::facts::{Closures, Inits, scalar_class};
use super::flatbuffers;
use super::names::{dotted_name, joined_camel, spellings};
use super::path::{Root, Step};
use super::resolve::{Scope, is_foreign};
use super::v1;
use crate::name::camel_case;
use crate::projection::flatbuffers as fb;
use crate::projection::size::{self, AbsentCause, Ctx, Encoding, PayloadShape, SizeState};
use crate::rules::ItemRef;
use crate::v2;

/// Lowers one package over the scope `others` (design note D-1).
///
/// The scope is part of the model: the output of every backend depends on it,
/// and a plugin must be able to tell "this reference names a package I was
/// not given" from "this reference names nothing".
///
/// A tuple inside a declaration of another package is named as that package
/// names it, so the lowering also lowers each package in which it reaches
/// such a position, once, in claims-only mode: only the names of that
/// package's own tuples are kept (`Lowering::claims_of`).
pub fn lower(package: &v2::Package, others: &[&v2::Package]) -> v1::Model {
    lower_with(package, others, &[])
}

/// Lowers one package like [`lower`], and records `compatible` as the
/// catalog's list of compatible earlier catalog hashes, in the order given.
/// The list is carried through unchanged and never feeds the catalog hash.
pub fn lower_with(
    package: &v2::Package,
    others: &[&v2::Package],
    compatible: &[[u8; 32]],
) -> v1::Model {
    let scope = Scope { package, others };
    let mut lowering = Lowering::new(scope);

    let declarations = lowering.declarations();

    let interfaces = lowering.shapes();
    lowering.drain_tuples();

    let mut model = v1::Model {
        name: Some(dotted_name(&package.name)),
        scope: Some(v1::Scope {
            package: package.name.clone(),
            others: others.iter().map(|other| other.name.clone()).collect(),
        }),
        declarations,
        tuples: lowering
            .tuples
            .iter()
            .map(|entry| entry.lowered.clone().unwrap_or_default())
            .collect(),
        interfaces,
        services: lowering.services(),
        catalog: Some(lowering.catalog(compatible)),
        flatbuffers: None,
        foreign: lowering.foreign.clone(),
        tuple_collisions: lowering.collisions.clone(),
        podbuf: None,
    };

    // The FlatBuffers projection is its own walk over the IR, in the order the
    // `.fbs` emitter reaches its tables. It is handed the tuples the lowering
    // named rather than deriving them again, so that one name is built in one
    // place and every named tuple reaches a table (driftsys/ridl#713).
    let roots = root_tuples(&model);
    let named: Vec<flatbuffers::NamedTuple<'_>> = lowering
        .tuples
        .iter()
        .enumerate()
        .filter(|(_, entry)| entry.named)
        .map(|(index, entry)| flatbuffers::NamedTuple {
            index: index as u32,
            wire: entry.wire.as_str(),
            source: &entry.source,
            home: entry.home,
            root: roots.contains(&(index as u32)),
        })
        .collect();
    let projected = flatbuffers::project(scope, &named, &lowering.foreign_at);
    patch_flatbuffers(&mut model, &projected);
    model.flatbuffers = Some(projected.projection);
    // A head that cannot be laid out is listed in `refused` with its cause.
    // The walk finds the tuple at a position by the path to it, whether the
    // tuple is one of `Model.tuples` or one inside a foreign declaration.
    let mut keys = super::podbuf::TupleKeys::default();
    for (index, entry) in lowering.tuples.iter().enumerate() {
        for key in &entry.keys {
            if entry.named {
                keys.local.insert(key.clone(), index as u32);
            } else {
                keys.foreign.insert(
                    key.clone(),
                    super::podbuf::ForeignTuple {
                        package: entry.home.name.clone(),
                        wire: entry.wire.clone(),
                        entry: index as u32,
                    },
                );
            }
        }
    }
    model.podbuf = Some(super::podbuf::project(
        scope,
        &named,
        &lowering.foreign_at,
        &keys,
    ));
    model
}

/// The tuples that cross the wire on their own, which is what makes each one
/// a FlatBuffers root: a call's induced argument struct and a query's induced
/// reply struct. The model already names them on the interaction that induced
/// them, so the set is read off the model rather than derived again.
fn root_tuples(model: &v1::Model) -> HashSet<u32> {
    let mut roots = HashSet::new();
    for interface in &model.interfaces {
        for slot in &interface.slots {
            let Some(v1::interaction_slot::Occupant::Interaction(interaction)) =
                slot.occupant.as_ref()
            else {
                continue;
            };
            match interaction.shape.as_ref() {
                Some(v1::interaction::Shape::Command(command)) => {
                    roots.extend(command.request_tuple.as_ref().map(|tuple| tuple.index));
                }
                Some(v1::interaction::Shape::Query(query)) => {
                    roots.extend(query.request_tuple.as_ref().map(|tuple| tuple.index));
                    roots.extend(query.reply_tuple.as_ref().map(|tuple| tuple.index));
                }
                _ => {}
            }
        }
    }
    roots
}

/// The path that reached one type position: where the model records the
/// origin of a tuple found there, and the two induced names it would take.
#[derive(Clone)]
pub(super) struct Path {
    base: Base,
    segments: Vec<String>,
    /// The position as the podbuf walk spells it too (`super::path`). The
    /// walk looks a tuple up by this path (`super::podbuf::TupleKeys`).
    /// `None` for a position reached from an interaction, where the walk
    /// starts at no root: the tuples it reaches there are keyed under the
    /// induced tuple (`drain_tuples`).
    pub(super) key: Option<Vec<Step>>,
    rust: String,
    wire: String,
    visibility: i32,
    /// False where no backend has a naming rule for the origin, which is a
    /// position inside a declaration of another package.
    named: bool,
}

#[derive(Clone, Copy)]
enum Base {
    Declaration(u32),
    Interaction(u32, u32),
    /// Reached inside a declaration of another package, which has no index in
    /// `Model.declarations` to name.
    Foreign,
}

impl Path {
    pub(super) fn declaration(index: u32, decl: &v2::Decl, owner: &str) -> Self {
        Self {
            base: Base::Declaration(index),
            segments: Vec::new(),
            key: Some(vec![Step::Root(Root::Declaration(owner.to_string()))]),
            rust: camel_case(owner),
            wire: owner.to_string(),
            visibility: decl.visibility,
            named: true,
        }
    }

    /// A declaration of another package. The podbuf walk reaches it under
    /// its qualified name.
    pub(super) fn foreign(package: &str, owner: &str, visibility: i32) -> Self {
        Self {
            base: Base::Foreign,
            segments: Vec::new(),
            key: Some(vec![Step::Root(Root::Foreign {
                package: package.to_string(),
                name: owner.to_string(),
            })]),
            rust: camel_case(owner),
            wire: owner.to_string(),
            visibility,
            named: false,
        }
    }

    /// An interaction position. The induced name starts at the interface's
    /// name and the interaction's, which is unique in the package because
    /// an induced struct is emitted at the package's own scope: an interface
    /// name is unique in a package, and an interaction name is unique in an
    /// interface (ADR-0016).
    ///
    /// The owner is the declared interface name, or the owning service's
    /// dotted name for a service's inline shape, so the Rust name composes
    /// both transforms: `joined_camel` joins the dotted segments, and
    /// `camel_case` removes any underscore.
    fn interaction(
        interface: u32,
        slot: u32,
        visibility: i32,
        owner: &str,
        member: &str,
        segments: Vec<String>,
    ) -> Self {
        Self {
            base: Base::Interaction(interface, slot),
            segments,
            key: None,
            rust: format!("{}{}", camel_case(&joined_camel(owner)), camel_case(member)),
            wire: format!("{}{}", joined_camel(owner), joined_camel(member)),
            visibility,
            named: true,
        }
    }

    /// A struct field, where both induced names begin.
    pub(super) fn field(&self, name: &str) -> Self {
        let mut segments = self.segments.clone();
        segments.push(name.to_string());
        let key = self.key_with(Some(Step::Field(name.to_string())));
        Self {
            base: self.base,
            segments,
            key,
            rust: format!("{}{}", self.rust, camel_case(name)),
            wire: format!("{}{}", self.wire, joined_camel(name)),
            visibility: self.visibility,
            named: self.named,
        }
    }

    /// A positional word: `Element`, `Key`, `Value`, or an interaction's
    /// role word. The walk path takes a map's `key` and `value`, and nothing
    /// for an array element or a role word (an interaction position has no
    /// walk path).
    pub(super) fn step(&self, word: &str) -> Self {
        let mut segments = self.segments.clone();
        segments.push(word.to_string());
        let key = self.key_with(match word {
            "Key" => Some(Step::Key),
            "Value" => Some(Step::Value),
            _ => None,
        });
        Self {
            base: self.base,
            segments,
            key,
            rust: format!("{}{word}", self.rust),
            wire: format!("{}{word}", self.wire),
            visibility: self.visibility,
            named: self.named,
        }
    }

    /// This position's walk path extended by `step`, if it has one.
    fn key_with(&self, step: Option<Step>) -> Option<Vec<Step>> {
        self.key.as_ref().map(|key| {
            let mut key = key.clone();
            key.extend(step);
            key
        })
    }

    /// A tuple field: the Rust name extends by the field's CamelCase, the
    /// wire name by the position (design note D-2).
    pub(super) fn tuple_field(&self, name: &str, position: usize) -> Self {
        let mut segments = self.segments.clone();
        segments.push(name.to_string());
        let key = self.key_with(Some(Step::Position(position as u32)));
        Self {
            base: self.base,
            segments,
            key,
            rust: format!("{}{}", self.rust, camel_case(name)),
            wire: format!("{}Field{position}", self.wire),
            visibility: self.visibility,
            named: self.named,
        }
    }

    fn origin(&self) -> Option<v1::induced_tuple::Origin> {
        match self.base {
            Base::Declaration(index) => {
                Some(v1::induced_tuple::Origin::Declaration(v1::TuplePath {
                    declaration: index,
                    segments: self.segments.clone(),
                }))
            }
            Base::Interaction(interface, slot) => Some(v1::induced_tuple::Origin::Interaction(
                v1::InteractionPath {
                    interface,
                    slot,
                    segments: self.segments.clone(),
                },
            )),
            Base::Foreign => None,
        }
    }
}

/// One tuple lifted out of the type graph, before its own fields are lowered.
struct TupleEntry<'a> {
    source: v2::TupleType,
    home: &'a v2::Package,
    path: Path,
    rust: String,
    wire: String,
    named: bool,
    /// Every walk path that reaches this tuple (`Path::key`): the path it was
    /// lifted at, and the path of each position whose claim it serves again.
    /// A position reached from an interaction has no walk path and adds none.
    keys: Vec<Vec<Step>>,
    /// What each field is documented with, in declaration order. Empty for
    /// every tuple but an induced argument struct, whose fields stand for the
    /// parameters of a call.
    docs: Vec<FieldDoc>,
    lowered: Option<v1::InducedTuple>,
}

/// What a parameter documents, carried onto the field induced from it. A
/// tuple field carries no doc in the IR, so an induced argument struct would
/// otherwise document none of its fields, while a generated item renders the
/// doc its source item has (ADR-0028).
#[derive(Clone, Default)]
struct FieldDoc {
    doc: String,
    links: Vec<v1::DocLink>,
    see: Vec<v1::DocLink>,
    since: Vec<String>,
}

impl FieldDoc {
    fn of_param(param: &v2::Param) -> Self {
        Self {
            doc: param.doc.clone(),
            links: doc_links(&param.links),
            see: doc_links(&param.see),
            since: param.since.clone(),
        }
    }
}

struct Lowering<'a> {
    scope: Scope<'a>,
    /// The `deps` of `rules::rules`: the lowered package, then the others.
    deps: Vec<&'a v2::Package>,
    sizes: Ctx<'a>,
    inits: Inits<'a>,
    closures: Closures<'a>,
    foreign: Vec<v1::ForeignDeclaration>,
    foreign_at: HashMap<(String, String), u32>,
    tuples: Vec<TupleEntry<'a>>,
    /// The entry each induced Rust name claims, by home package and name, for
    /// a position of the lowered package: a position of the same shape that
    /// spells a claimed name reuses the entry.
    tuple_at: HashMap<(String, String), usize>,
    /// The named tuples of another package's own lowering, by package name,
    /// filled the first time a position inside one of its declarations is
    /// reached. A position inside a declaration of another package takes its
    /// wire name from these, so that the name is the one the declaring
    /// package gives the tuple, whatever order this package reaches that
    /// package's declarations in (driftsys/ridl#1150).
    claims_memo: Memo,
    /// Whether this lowering computes the claims of its own package for
    /// another lowering (`claims_of`). A foreign position is then lifted
    /// with no wire name and no package is lowered for it, so a lowering in
    /// this mode starts none: two packages that reference each other by
    /// qualified name would otherwise be lowered without end.
    claims_only: bool,
    /// The entries lifted for the positions inside declarations of other
    /// packages, by declaring package and induced Rust name. A position of
    /// the same shape and visibility as a listed entry is the same tuple and
    /// reuses the entry; a collision between two such positions is the
    /// declaring package's to record, so each shape gets its own entry here.
    foreign_tuple_at: HashMap<(String, String), Vec<usize>>,
    collisions: Vec<v1::TupleCollision>,
}

/// One named tuple of a package's own lowering, as an importing lowering
/// reads it: the shape and the visibility a position matches by, under the
/// induced Rust name the claims are keyed by, and the wire name it takes.
struct TupleClaim {
    source: v2::TupleType,
    visibility: i32,
    wire: String,
}

/// The claims of one package, by induced Rust name.
type Claims = HashMap<String, Vec<TupleClaim>>;

/// The claims of every declaring package lowered so far by one lowering.
type Memo = Rc<RefCell<HashMap<String, Rc<Claims>>>>;

#[cfg(test)]
thread_local! {
    /// How many lowerings of a declaring package this thread has started:
    /// one per package reached, when the memo holds.
    pub(super) static DECLARING_LOWERINGS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

impl<'a> Lowering<'a> {
    fn new(scope: Scope<'a>) -> Self {
        Self::with_mode(scope, false)
    }

    fn with_mode(scope: Scope<'a>, claims_only: bool) -> Self {
        Self {
            scope,
            deps: scope.packages().collect(),
            sizes: Ctx::new(scope.package, scope.others),
            inits: Inits::new(scope),
            closures: Closures::new(scope),
            foreign: Vec::new(),
            foreign_at: HashMap::new(),
            tuples: Vec::new(),
            tuple_at: HashMap::new(),
            claims_memo: Memo::default(),
            claims_only,
            foreign_tuple_at: HashMap::new(),
            collisions: Vec::new(),
        }
    }

    // -----------------------------------------------------------------
    // Declarations
    // -----------------------------------------------------------------

    /// The declarations of the lowered package, in order, and then every
    /// tuple they reach.
    fn declarations(&mut self) -> Vec<v1::Declaration> {
        let package = self.scope.package;
        let declarations = package
            .decls
            .iter()
            .enumerate()
            .map(|(index, decl)| {
                let path = Path::declaration(index as u32, decl, &decl.name);
                self.declaration(package, decl, Some(path))
            })
            .collect();
        self.drain_tuples();
        declarations
    }

    fn declaration(
        &mut self,
        home: &'a v2::Package,
        decl: &v2::Decl,
        path: Option<Path>,
    ) -> v1::Declaration {
        let is_constant = matches!(decl.kind, Some(v2::decl::Kind::ConstDef(_)));
        v1::Declaration {
            name: Some(spellings(&decl.name)),
            visibility: decl.visibility,
            is_error: decl.is_error,
            doc: decl.doc.clone(),
            labels: decl.labels.clone(),
            deprecated: decl.deprecated.clone(),
            links: doc_links(&decl.links),
            see: doc_links(&decl.see),
            since: decl.since.clone(),
            rules: model_rules(home, &self.deps, ItemRef::Decl(decl)),
            closure: (!is_constant).then(|| self.closures.declaration(home, decl)),
            init: (!is_constant).then(|| self.inits.declaration(home, decl)),
            proto3: (!is_constant).then(|| {
                self.size_state(
                    home,
                    &PayloadShape::Named(&decl.name),
                    Some(&decl.name),
                    Encoding::Proto3,
                )
            }),
            podbuf: (!is_constant).then(|| {
                self.size_state(
                    home,
                    &PayloadShape::Named(&decl.name),
                    Some(&decl.name),
                    Encoding::Podbuf,
                )
            }),
            kind: self.declaration_kind(home, decl, path),
        }
    }

    fn declaration_kind(
        &mut self,
        home: &'a v2::Package,
        decl: &v2::Decl,
        path: Option<Path>,
    ) -> Option<v1::declaration::Kind> {
        let path = path.unwrap_or_else(|| Path::foreign(&home.name, &decl.name, decl.visibility));
        match decl.kind.as_ref()? {
            v2::decl::Kind::TypeDef(td) => {
                Some(v1::declaration::Kind::Scalar(self.scalar(td, true)))
            }
            v2::decl::Kind::ConstDef(cd) => {
                Some(v1::declaration::Kind::Constant(self.constant(home, cd)))
            }
            v2::decl::Kind::StructDef(def) => Some(v1::declaration::Kind::Struct(v1::Struct {
                slots: def
                    .members
                    .iter()
                    .map(|member| self.slot(home, member, &path))
                    .collect(),
                fixed_layout: def.fixed_layout,
            })),
            v2::decl::Kind::EnumDef(def) => Some(v1::declaration::Kind::Enum(enum_body(def))),
            v2::decl::Kind::EnumSetDef(def) => {
                Some(v1::declaration::Kind::EnumSet(self.enum_set(home, def)))
            }
            v2::decl::Kind::UnionDef(def) => {
                Some(v1::declaration::Kind::Union(self.union(home, def)))
            }
            // An interaction rides `Interface.interactions`, never a package
            // declaration, and a reserved slot is not a declaration either.
            _ => None,
        }
    }

    fn slot(&mut self, home: &'a v2::Package, member: &v2::StructMember, path: &Path) -> v1::Slot {
        match &member.member {
            Some(v2::struct_member::Member::Field(field)) => v1::Slot {
                ordinal: field.ordinal,
                occupant: Some(v1::slot::Occupant::Field(Box::new(
                    self.field(home, field, path),
                ))),
            },
            Some(v2::struct_member::Member::Reserved(reserved)) => v1::Slot {
                ordinal: reserved.ordinal,
                occupant: Some(v1::slot::Occupant::Retired(retired(reserved))),
            },
            None => v1::Slot {
                ordinal: 0,
                occupant: None,
            },
        }
    }

    fn field(&mut self, home: &'a v2::Package, field: &v2::Field, path: &Path) -> v1::Field {
        let at = path.field(&field.name);
        v1::Field {
            name: Some(spellings(&field.name)),
            r#type: field.r#type.as_ref().map(|ty| self.type_at(home, ty, &at)),
            declared_init: field.declared_init.clone(),
            init: Some(self.inits.field(home, field)),
            doc: field.doc.clone(),
            labels: field.labels.clone(),
            deprecated: field.deprecated.clone(),
            links: doc_links(&field.links),
            see: doc_links(&field.see),
            since: field.since.clone(),
            rules: model_rules(home, &self.deps, ItemRef::Field(field)),
        }
    }

    /// A named scalar, or the shape of an inline one. An inline scalar's
    /// `declared_init` stays unset: the enclosing field's is authoritative
    /// (`ir.proto`, `FieldType.inline_scalar`).
    fn scalar(&mut self, td: &v2::TypeDef, declared: bool) -> v1::Scalar {
        v1::Scalar {
            class: scalar_class(td) as i32,
            unit: match td
                .backing
                .as_ref()
                .and_then(|backing| backing.kind.as_ref())
            {
                Some(v2::backing::Kind::Unit(unit)) => Some(unit.clone()),
                _ => None,
            },
            constraint: td.constraint.as_ref().map(constraint),
            vacuous: crate::v2::constraint_is_vacuous(td.constraint.as_ref()),
            declared_init: declared.then(|| td.declared_init.clone()).flatten(),
            width: td.width.as_ref().map(|width| match width {
                v2::type_def::Width::IntWidth(value) => v1::scalar::Width::IntWidth(*value),
                v2::type_def::Width::FloatWidth(value) => v1::scalar::Width::FloatWidth(*value),
            }),
        }
    }

    fn constant(&mut self, home: &'a v2::Package, cd: &v2::ConstDef) -> v1::Constant {
        let typed = match (cd.regex.as_deref(), cd.type_ref.as_deref()) {
            (Some(regex), _) => Some(v1::constant::Typed::RegexBody(
                strip_regex_delimiters(regex).to_string(),
            )),
            (None, Some(reference)) => Some(match primitive_keyword(reference) {
                Some(primitive) => v1::constant::Typed::Primitive(primitive as i32),
                None => match self.type_ref(home, reference) {
                    reference if reference.resolved => v1::constant::Typed::Named(reference),
                    reference => v1::constant::Typed::Unresolved(reference.reference),
                },
            }),
            (None, None) => None,
        };
        v1::Constant {
            value: cd.value.clone(),
            typed,
        }
    }

    fn enum_set(&mut self, home: &'a v2::Package, def: &v2::EnumSetDef) -> v1::EnumSet {
        let mask = def.bits.iter().fold(0i64, |mask, bit| {
            if (0..=63).contains(&bit.value) {
                mask | (1i64 << bit.value)
            } else {
                mask
            }
        });
        v1::EnumSet {
            backing_enum: def
                .backing_enum
                .as_deref()
                .map(|reference| self.type_ref(home, reference)),
            bits: def.bits.iter().map(enum_value).collect(),
            width: def.width,
            declared_mask: mask,
            open: def.open,
        }
    }

    fn union(&mut self, home: &'a v2::Package, def: &v2::UnionDef) -> v1::Union {
        v1::Union {
            arms: def
                .arms
                .iter()
                .map(|arm| v1::Arm {
                    name: Some(spellings(&arm.name)),
                    ordinal: arm.ordinal,
                    r#type: Some(self.type_ref(home, &arm.type_ref)),
                    doc: arm.doc.clone(),
                    discriminant: fb::union_arm_discriminant(arm),
                    // Patched once the projection has its table indices.
                    flatbuffers_box: None,
                    links: doc_links(&arm.links),
                    see: doc_links(&arm.see),
                    since: arm.since.clone(),
                    // `rules::rules` has no item for a union arm.
                    rules: Vec::new(),
                })
                .collect(),
            retired: def.reserved.iter().map(retired).collect(),
            is_result: def.is_result,
        }
    }

    // -----------------------------------------------------------------
    // Type positions
    // -----------------------------------------------------------------

    fn type_at(&mut self, home: &'a v2::Package, ty: &v2::FieldType, at: &Path) -> v1::Type {
        v1::Type {
            optional: ty.optional,
            kind: self.type_kind(home, ty, at),
        }
    }

    fn type_kind(
        &mut self,
        home: &'a v2::Package,
        ty: &v2::FieldType,
        at: &Path,
    ) -> Option<v1::r#type::Kind> {
        match ty.kind.as_ref()? {
            v2::field_type::Kind::Named(reference) => {
                Some(v1::r#type::Kind::Named(self.type_ref(home, reference)))
            }
            v2::field_type::Kind::Primitive(primitive) => {
                Some(v1::r#type::Kind::Primitive(*primitive))
            }
            v2::field_type::Kind::InlineScalar(td) => {
                Some(v1::r#type::Kind::Inline(self.scalar(td, false)))
            }
            v2::field_type::Kind::Tuple(tuple) => {
                let index = self.tuple_ref(home, tuple, at);
                Some(v1::r#type::Kind::Tuple(v1::TupleRef { index }))
            }
            v2::field_type::Kind::Array(array) => {
                let element = array
                    .element
                    .as_deref()
                    .map(|element| self.type_at(home, element, &at.step("Element")));
                Some(v1::r#type::Kind::Array(Box::new(v1::ArrayType {
                    element: element.map(Box::new),
                    min: array.min,
                    max: array.max,
                })))
            }
            v2::field_type::Kind::Map(map) => {
                let key = map
                    .key
                    .as_deref()
                    .map(|key| self.type_at(home, key, &at.step("Key")));
                let value = map
                    .value
                    .as_deref()
                    .map(|value| self.type_at(home, value, &at.step("Value")));
                Some(v1::r#type::Kind::Map(Box::new(v1::MapType {
                    key: key.map(Box::new),
                    value: value.map(Box::new),
                    min: map.min,
                    max: map.max,
                    // Patched once the projection has its table indices.
                    flatbuffers_entry_table: None,
                })))
            }
            v2::field_type::Kind::Stream(stream) => {
                Some(v1::r#type::Kind::Stream(self.stream(home, stream)))
            }
        }
    }

    fn stream(&mut self, home: &'a v2::Package, stream: &v2::StreamType) -> v1::StreamType {
        v1::StreamType {
            element: stream.element.as_ref().map(|element| match element {
                v2::stream_type::Element::Named(reference) => {
                    v1::stream_type::Element::Named(self.type_ref(home, reference))
                }
                v2::stream_type::Element::Primitive(primitive) => {
                    v1::stream_type::Element::Primitive(*primitive)
                }
            }),
        }
    }

    /// A resolved reference, flat: the declaring package, whether it is
    /// foreign, the index the declaration sits at, and its kind. A reference
    /// that names a constant is not resolved as a type.
    ///
    /// `foreign` and `index` follow one rule: the declaring package against
    /// the package being lowered. The reference text cannot decide it, because
    /// a foreign declaration is lowered with `home` set to its own package, so
    /// a reference inside it is spelled bare while it names a declaration
    /// outside the scope's package (driftsys/ridl#586). An unresolved
    /// reference has no declaring package, so its flag is the only evidence
    /// left: whether the text is dotted.
    fn type_ref(&mut self, home: &'a v2::Package, reference: &str) -> v1::TypeRef {
        let Some((decl, declaring)) = self.scope.resolve(home, reference) else {
            return v1::TypeRef {
                reference: reference.to_string(),
                resolved: false,
                package: String::new(),
                foreign: is_foreign(reference),
                index: 0,
                kind: v1::DeclKind::Unspecified as i32,
            };
        };
        let kind = decl_kind(decl);
        let local = declaring.name == self.scope.package.name;
        let index = if local {
            declaring
                .decls
                .iter()
                .position(|candidate| candidate.name == decl.name)
                .unwrap_or(0) as u32
        } else {
            self.foreign_declaration(declaring, decl)
        };
        v1::TypeRef {
            reference: reference.to_string(),
            resolved: kind != v1::DeclKind::Constant,
            package: declaring.name.clone(),
            foreign: !local,
            index,
            kind: kind as i32,
        }
    }

    /// A copy of one foreign declaration, added to `Model.foreign` the first
    /// time this package reaches it.
    fn foreign_declaration(&mut self, declaring: &'a v2::Package, decl: &v2::Decl) -> u32 {
        let key = (declaring.name.clone(), decl.name.clone());
        if let Some(index) = self.foreign_at.get(&key) {
            return *index;
        }
        let index = self.foreign.len() as u32;
        self.foreign_at.insert(key, index);
        self.foreign.push(v1::ForeignDeclaration {
            package: declaring.name.clone(),
            declaration: None,
        });
        let lowered = self.declaration(declaring, decl, None);
        self.foreign[index as usize].declaration = Some(lowered);
        index
    }

    // -----------------------------------------------------------------
    // Induced tuples
    // -----------------------------------------------------------------

    /// Lifts one tuple position into `Model.tuples`, returning its index.
    ///
    /// A tuple whose induced Rust name is already claimed by a tuple of the
    /// same shape and the same visibility is the same generated type, so the
    /// claim is reused. A position of this package whose claim is held by a
    /// tuple of a different shape or a different visibility is a collision,
    /// recorded as a fact for the printer to refuse with its own message. A
    /// position inside a declaration of another package is matched against
    /// that package's own claims instead (`foreign_tuple_ref`).
    fn tuple_ref(&mut self, home: &'a v2::Package, tuple: &v2::TupleType, at: &Path) -> u32 {
        if !at.named {
            return self.foreign_tuple_ref(home, tuple, at);
        }
        let claim = (home.name.clone(), at.rust.clone());
        if let Some(index) = self.tuple_at.get(&claim).copied() {
            let existing = &self.tuples[index];
            // One name is one generated type, so the claim is reused only
            // when the shape *and* the visibility match. A tuple has no
            // visibility of its own — it carries the one of the declaration
            // that reached it — so two paths that spell one name from
            // declarations of different visibility have no sound answer
            // either, and each printer refuses that pair the way it refuses
            // two different shapes.
            if existing.source == *tuple && existing.path.visibility == at.visibility {
                self.tuples[index].keys.extend(at.key.clone());
                return index as u32;
            }
            self.collisions.push(v1::TupleCollision {
                name: at.rust.clone(),
                first_fields: existing
                    .source
                    .fields
                    .iter()
                    .map(|field| field.name.clone())
                    .collect(),
                second_fields: tuple
                    .fields
                    .iter()
                    .map(|field| field.name.clone())
                    .collect(),
            });
        }
        // A colliding entry keeps the claim.
        let index = self.lift(home, tuple, at, at.wire.clone());
        self.tuple_at.entry(claim).or_insert(index);
        index as u32
    }

    /// A position inside a declaration of another package, `home`. The tuple
    /// there is one of `home`'s own named tuples, found among `home`'s claims
    /// by the position's induced Rust name, its shape and its visibility, and
    /// the entry takes that tuple's wire name. Two positions of one shape and
    /// one visibility under one Rust name are one tuple and share one entry;
    /// a collision between them is `home`'s to record, and the podbuf walk
    /// refuses two entries of `home` under one wire name when it meets both.
    ///
    /// Every position inside a declaration of `home` has a claim, because
    /// `home`'s own lowering reaches the same positions under the same names.
    /// A position with no claim is an internal error: its entry gets no wire
    /// name, which the podbuf walk refuses, rather than a name derived here.
    /// In claims-only mode no claim is looked up, and every such entry has no
    /// wire name.
    fn foreign_tuple_ref(
        &mut self,
        home: &'a v2::Package,
        tuple: &v2::TupleType,
        at: &Path,
    ) -> u32 {
        let key = (home.name.clone(), at.rust.clone());
        let existing = self.foreign_tuple_at.get(&key).and_then(|entries| {
            entries.iter().copied().find(|&index| {
                let entry = &self.tuples[index];
                entry.source == *tuple && entry.path.visibility == at.visibility
            })
        });
        if let Some(index) = existing {
            self.tuples[index].keys.extend(at.key.clone());
            return index as u32;
        }
        let wire = if self.claims_only {
            None
        } else {
            self.claims_of(home)
                .get(&at.rust)
                .and_then(|claims| {
                    claims
                        .iter()
                        .find(|claim| claim.source == *tuple && claim.visibility == at.visibility)
                })
                .map(|claim| claim.wire.clone())
        };
        let index = self.lift(home, tuple, at, wire.unwrap_or_default());
        self.foreign_tuple_at.entry(key).or_default().push(index);
        index as u32
    }

    /// The claims of `declaring`: the named tuples of its own lowering, over
    /// the rest of the scope. Lowered once per memo, in claims-only mode, the
    /// first time a position inside one of its declarations is reached. The
    /// entries of other packages that lowering lifts are left out: they are
    /// not `declaring`'s tuples, and in claims-only mode they carry no name.
    fn claims_of(&mut self, declaring: &'a v2::Package) -> Rc<Claims> {
        if let Some(claims) = self.claims_memo.borrow().get(&declaring.name) {
            return Rc::clone(claims);
        }
        #[cfg(test)]
        DECLARING_LOWERINGS.with(|count| count.set(count.get() + 1));
        let others = self.scope.projection_others(declaring);
        let mut lowering = Lowering::with_mode(
            Scope {
                package: declaring,
                others: &others,
            },
            true,
        );
        lowering.declarations();
        let mut claims = Claims::new();
        for entry in lowering.tuples.iter().filter(|entry| entry.named) {
            claims
                .entry(entry.rust.clone())
                .or_default()
                .push(TupleClaim {
                    source: entry.source.clone(),
                    visibility: entry.path.visibility,
                    wire: entry.wire.clone(),
                });
        }
        let claims = Rc::new(claims);
        self.claims_memo
            .borrow_mut()
            .insert(declaring.name.clone(), Rc::clone(&claims));
        claims
    }

    /// A new entry for the tuple at `at`, under the wire name `wire`.
    fn lift(
        &mut self,
        home: &'a v2::Package,
        tuple: &v2::TupleType,
        at: &Path,
        wire: String,
    ) -> usize {
        let index = self.tuples.len();
        self.tuples.push(TupleEntry {
            source: tuple.clone(),
            home,
            path: at.clone(),
            rust: at.rust.clone(),
            wire,
            named: at.named,
            keys: at.key.clone().into_iter().collect(),
            docs: Vec::new(),
            lowered: None,
        });
        index
    }

    /// Lowers every tuple the walk reached, in discovery order; lowering one
    /// tuple's fields can reach another, which is appended and picked up by a
    /// later pass of the same loop.
    fn drain_tuples(&mut self) {
        let mut index = 0;
        while index < self.tuples.len() {
            if self.tuples[index].lowered.is_some() {
                index += 1;
                continue;
            }
            let source = self.tuples[index].source.clone();
            let home = self.tuples[index].home;
            let mut path = self.tuples[index].path.clone();
            let named = self.tuples[index].named;
            // The podbuf walk fills a named tuple as a root of its own, so a
            // tuple inside it is reached under that root; a tuple inside a
            // foreign declaration's tuple is reached under the declaration.
            if named {
                path.key = Some(vec![Step::Root(Root::Tuple(index as u32))]);
            }
            let docs = self.tuples[index].docs.clone();
            let (rust, wire) = (
                self.tuples[index].rust.clone(),
                self.tuples[index].wire.clone(),
            );
            let fields: Vec<v1::Field> = source
                .fields
                .iter()
                .enumerate()
                .map(|(position, field)| {
                    let at = path.tuple_field(&field.name, position + 1);
                    // A tuple field carries no doc in the IR; the one an
                    // induced argument struct has comes from the parameter at
                    // the same position, which `docs` holds.
                    let documented = docs.get(position).cloned().unwrap_or_default();
                    v1::Field {
                        name: Some(spellings(&field.name)),
                        r#type: field.r#type.as_ref().map(|ty| self.type_at(home, ty, &at)),
                        declared_init: None,
                        init: Some(self.inits.tuple_field(home, field)),
                        doc: documented.doc,
                        labels: Vec::new(),
                        deprecated: None,
                        links: documented.links,
                        see: documented.see,
                        since: documented.since,
                        // `rules::rules` has no item for a tuple field.
                        rules: Vec::new(),
                    }
                })
                .collect();
            let lowered = v1::InducedTuple {
                name: Some(v1::InducedName {
                    rust: if named { rust } else { String::new() },
                    wire: if named { wire } else { String::new() },
                }),
                fields,
                visibility: path.visibility,
                closure: Some(self.closures.tuple(home, &source)),
                init: Some(self.inits.tuple(home, &source)),
                // Patched once the projection has its table indices.
                flatbuffers_table: None,
                origin: path.origin(),
            };
            self.tuples[index].lowered = Some(lowered);
            index += 1;
        }
    }

    // -----------------------------------------------------------------
    // Interfaces, services, the catalog
    // -----------------------------------------------------------------

    fn shapes(&mut self) -> Vec<v1::Interface> {
        let package = self.scope.package;
        let shapes: Vec<v2::InterfaceShape<'a>> = package.shapes().collect();
        shapes
            .iter()
            .enumerate()
            .map(|(index, shape)| self.interface(package, index as u32, shape))
            .collect()
    }

    fn interface(
        &mut self,
        home: &'a v2::Package,
        index: u32,
        shape: &v2::InterfaceShape<'a>,
    ) -> v1::Interface {
        let interface = shape.interface;
        let visibility = shape.visibility();
        let owner = match shape.service {
            Some(service) => service.name.clone(),
            None => interface.name.clone(),
        };
        let mut row = 0u32;
        let slots: Vec<v1::InteractionSlot> = interface
            .interactions
            .iter()
            .enumerate()
            .map(|(slot, decl)| {
                let ordinal = decl.ordinal;
                match decl.kind.as_ref() {
                    Some(v2::decl::Kind::ReservedSlot(reserved)) => v1::InteractionSlot {
                        ordinal,
                        occupant: Some(v1::interaction_slot::Occupant::Retired(retired(reserved))),
                    },
                    _ => {
                        let this_row = row;
                        row += 1;
                        v1::InteractionSlot {
                            ordinal,
                            occupant: Some(v1::interaction_slot::Occupant::Interaction(Box::new(
                                self.interaction(
                                    home,
                                    decl,
                                    index,
                                    slot as u32,
                                    this_row,
                                    visibility,
                                    &owner,
                                ),
                            ))),
                        }
                    }
                }
            })
            .collect();
        let table_budget = budget(&slots);
        let inline_of_service = shape.service.and_then(|service| {
            home.services
                .iter()
                .position(|candidate| candidate.name == service.name)
                .map(|position| position as u32)
        });
        v1::Interface {
            number: interface.number,
            provisional: interface.provisional,
            visibility,
            doc: interface.doc.clone(),
            labels: interface.labels.clone(),
            deprecated: interface.deprecated.clone(),
            links: doc_links(&interface.links),
            see: doc_links(&interface.see),
            since: interface.since.clone(),
            // `rules::rules` has no item for an interface.
            rules: Vec::new(),
            slots,
            table_budget: Some(table_budget),
            inline_of_service,
            identity: Some(match shape.service {
                Some(service) => v1::interface::Identity::Service(dotted_name(&service.name)),
                None => v1::interface::Identity::Declared(spellings(&interface.name)),
            }),
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn interaction(
        &mut self,
        home: &'a v2::Package,
        decl: &v2::Decl,
        interface: u32,
        slot: u32,
        row: u32,
        visibility: i32,
        owner: &str,
    ) -> v1::Interaction {
        let (kind, timing, shape, payloads, family) = match decl.kind.as_ref() {
            Some(v2::decl::Kind::SignalDef(signal)) => {
                let payload = self.payload(home, &signal.payload);
                let payloads = vec![("payload", signal.payload.clone(), payload.sizes.clone())];
                (
                    v1::Kind::Signal,
                    signal.timing.as_ref(),
                    Some(v1::interaction::Shape::Signal(v1::SignalShape {
                        payload: Some(payload),
                        declared_init: signal.declared_init.clone(),
                        init: Some(
                            self.inits
                                .signal(signal.init.as_ref(), signal.declared_init.is_some()),
                        ),
                    })),
                    Some(payloads),
                    signal.family,
                )
            }
            Some(v2::decl::Kind::EventDef(event)) => {
                let payload = self.payload(home, &event.payload);
                let payloads = vec![("payload", event.payload.clone(), payload.sizes.clone())];
                (
                    v1::Kind::Event,
                    event.timing.as_ref(),
                    Some(v1::interaction::Shape::Event(v1::EventShape {
                        payload: Some(payload),
                    })),
                    Some(payloads),
                    event.family,
                )
            }
            Some(v2::decl::Kind::CommandDef(command)) => {
                let params = self.params(
                    home,
                    &command.params,
                    interface,
                    slot,
                    visibility,
                    owner,
                    decl.name.as_str(),
                );
                let request = single_param_type(&command.params)
                    .map(|reference| self.payload(home, reference));
                let request_tuple = self.request_tuple(
                    home,
                    &command.params,
                    interface,
                    slot,
                    visibility,
                    owner,
                    decl.name.as_str(),
                );
                let request_induced = params_as_tuple(&command.params);
                let request_sizes = self.sizes(
                    home,
                    &request_shape(&command.params, request_induced.as_ref()),
                    single_param_type(&command.params),
                );
                let clauses = self.clauses(home, &command.contracts, &command.params, None);
                let payloads = vec![(
                    "request",
                    params_text(&command.params),
                    Some(request_sizes.clone()),
                )];
                (
                    v1::Kind::Command,
                    command.timing.as_ref(),
                    Some(v1::interaction::Shape::Command(v1::CommandShape {
                        params,
                        request,
                        clauses,
                        request_sizes: Some(request_sizes),
                        shape: command.shape,
                        request_tuple,
                    })),
                    Some(payloads),
                    command.family,
                )
            }
            Some(v2::decl::Kind::QueryDef(query)) => {
                let params = self.params(
                    home,
                    &query.params,
                    interface,
                    slot,
                    visibility,
                    owner,
                    decl.name.as_str(),
                );
                let request =
                    single_param_type(&query.params).map(|reference| self.payload(home, reference));
                let request_tuple = self.request_tuple(
                    home,
                    &query.params,
                    interface,
                    slot,
                    visibility,
                    owner,
                    decl.name.as_str(),
                );
                let reply_named = query_reply_type(query);
                let reply = query.return_type.as_ref().map(|ret| {
                    // The same path the induced reply struct takes: a tuple
                    // written inside the return type is the tuple this arm
                    // induces, so both reach one name and the claim is
                    // reused rather than recorded as a collision.
                    let at = Path::interaction(
                        interface,
                        slot,
                        visibility,
                        owner,
                        decl.name.as_str(),
                        Vec::new(),
                    )
                    .step("Reply");
                    self.reply(home, ret, &at)
                });
                let request_induced = params_as_tuple(&query.params);
                let request_sizes = self.sizes(
                    home,
                    &request_shape(&query.params, request_induced.as_ref()),
                    single_param_type(&query.params),
                );
                let reply_induced = match reply_named {
                    Some(_) => None,
                    None => reply_as_tuple(query.return_type.as_ref()),
                };
                let reply_sizes = match (&reply_induced, query.return_type.as_ref()) {
                    (Some(tuple), _) => self.sizes(home, &PayloadShape::Tuple(tuple), None),
                    (None, Some(ret)) => self.sizes(home, &PayloadShape::Return(ret), reply_named),
                    (None, None) => absent_sizes(),
                };
                let mut payloads = vec![(
                    "request",
                    params_text(&query.params),
                    Some(request_sizes.clone()),
                )];
                // A streamed reply has no response payload: its chunks are not
                // held by the call table, and the member's limit bounds each
                // of them (ADR-0032 decision 14). So it reserves nothing, as
                // the size table the Rust backend emits has no row for it.
                if !query.return_type.as_ref().is_some_and(returns_stream) {
                    payloads.push((
                        "reply",
                        query
                            .return_type
                            .as_ref()
                            .map_or_else(|| "()".to_string(), return_text),
                        Some(reply_sizes.clone()),
                    ));
                }
                let reply_payload = reply_named.map(|reference| self.payload(home, reference));
                let reply_tuple = match reply_named {
                    Some(_) => None,
                    None => reply_as_tuple(query.return_type.as_ref()).map(|tuple| {
                        let at = Path::interaction(
                            interface,
                            slot,
                            visibility,
                            owner,
                            decl.name.as_str(),
                            Vec::new(),
                        )
                        .step("Reply");
                        v1::TupleRef {
                            index: self.tuple_ref(home, &tuple, &at),
                        }
                    }),
                };
                let clauses = self.clauses(home, &query.contracts, &query.params, reply_named);
                (
                    v1::Kind::Query,
                    query.timing.as_ref(),
                    Some(v1::interaction::Shape::Query(Box::new(v1::QueryShape {
                        params,
                        request,
                        reply,
                        reply_payload,
                        clauses,
                        request_sizes: Some(request_sizes),
                        reply_sizes: Some(reply_sizes),
                        request_tuple,
                        reply_tuple,
                    }))),
                    Some(payloads),
                    query.family,
                )
            }
            Some(v2::decl::Kind::FixedDef(fixed)) => {
                let at = Path::interaction(
                    interface,
                    slot,
                    visibility,
                    owner,
                    decl.name.as_str(),
                    vec!["payload".to_string()],
                );
                let payload = fixed.payload.as_ref().map(|ty| self.type_at(home, ty, &at));
                let named = fixed
                    .payload
                    .as_ref()
                    .and_then(named_type)
                    .map(|reference| self.payload(home, reference));
                (
                    v1::Kind::Fixed,
                    None,
                    Some(v1::interaction::Shape::Fixed(v1::FixedShape {
                        payload,
                        named,
                    })),
                    // A fixed is provisioned, never in flight, so it reserves
                    // nothing and adds nothing to the table budget, whatever
                    // its payload. The runtime's `Sizes` row carries 0 for a
                    // fixed for the same reason, and the two sums describe
                    // the same interface (driftsys/ridl#852).
                    Some(Vec::new()),
                    // A fixed is family-neutral (ADR-0012 decision 4), so the
                    // model carries the zero value for it.
                    v2::Family::Dispatch as i32,
                )
            }
            _ => (
                v1::Kind::Unspecified,
                None,
                None,
                None,
                v2::Family::Dispatch as i32,
            ),
        };
        let member = decl.name.as_str();
        let reservation = reserve(member, payloads.as_deref());
        let streams = self.streams(home, decl);
        v1::Interaction {
            name: Some(spellings(&decl.name)),
            kind: kind as i32,
            row,
            doc: decl.doc.clone(),
            labels: decl.labels.clone(),
            deprecated: decl.deprecated.clone(),
            timing: timing.map(timing_of),
            reservation: Some(reservation),
            family,
            shape,
            links: doc_links(&decl.links),
            see: doc_links(&decl.see),
            since: decl.since.clone(),
            rules: model_rules(home, &self.deps, ItemRef::Decl(decl)),
            limit: decl.limit,
            streams,
        }
    }

    /// The streams of a call: the reply stream of a query as number 0, then
    /// each stream parameter, counted from 1 in declaration order.
    fn streams(&mut self, home: &'a v2::Package, decl: &v2::Decl) -> Vec<v1::StreamShape> {
        let (params, reply) = match decl.kind.as_ref() {
            Some(v2::decl::Kind::CommandDef(command)) => (&command.params, None),
            Some(v2::decl::Kind::QueryDef(query)) => {
                let reply = query.return_type.as_ref().and_then(|ret| match &ret.kind {
                    Some(v2::return_type::Kind::Value(ty)) => Some(ty),
                    _ => None,
                });
                (&query.params, reply)
            }
            _ => return Vec::new(),
        };
        fn carried(ty: &v2::FieldType) -> Option<&v2::StreamType> {
            match ty.kind.as_ref() {
                Some(v2::field_type::Kind::Stream(stream)) => Some(stream),
                _ => None,
            }
        }
        // The model numbers streams as a `u32`, the field's type; the
        // descriptor and `ridl_rt::port::StreamNo` hold a `u8`, so a stream
        // parameter past the 255th has no descriptor entry and no `StreamNo`.
        // No source declares that many, and no diagnostic reports it.
        let mut streams = Vec::new();
        let mut number = 0;
        if let Some(stream) = reply.and_then(carried) {
            streams.extend(self.stream_shape(home, number, stream));
        }
        for stream in params
            .iter()
            .filter_map(|param| param.r#type.as_ref().and_then(carried))
        {
            number += 1;
            streams.extend(self.stream_shape(home, number, stream));
        }
        streams
    }

    fn stream_shape(
        &mut self,
        home: &'a v2::Package,
        no: u32,
        stream: &v2::StreamType,
    ) -> Option<v1::StreamShape> {
        match stream.element.as_ref()? {
            v2::stream_type::Element::Named(reference) => {
                let payload = self.payload(home, reference);
                Some(v1::StreamShape {
                    no,
                    form: v1::StreamForm::Elements as i32,
                    element: payload.r#type,
                    sizes: payload.sizes,
                })
            }
            v2::stream_type::Element::Primitive(primitive) => {
                let form = match v2::PrimitiveType::try_from(*primitive).ok()? {
                    v2::PrimitiveType::Bytes => v1::StreamForm::Bytes,
                    v2::PrimitiveType::String => v1::StreamForm::Text,
                    _ => return None,
                };
                Some(v1::StreamShape {
                    no,
                    form: form as i32,
                    element: None,
                    sizes: Some(absent_sizes()),
                })
            }
        }
    }

    /// The induced argument struct for a call's parameters, written where the
    /// parameters are not exactly one named type — that one shape is the
    /// payload the face sends as it is, and induces nothing
    /// (driftsys/ridl#713).
    #[allow(clippy::too_many_arguments)]
    fn request_tuple(
        &mut self,
        home: &'a v2::Package,
        params: &[v2::Param],
        interface: u32,
        slot: u32,
        visibility: i32,
        owner: &str,
        member: &str,
    ) -> Option<v1::TupleRef> {
        if single_param_type(params).is_some() {
            return None;
        }
        let tuple = params_as_tuple(params)?;
        // `Path::step` appends the role word to the segments and to both
        // induced names at once, which gives segments `["Params"]` and the
        // Rust name `<Interface><Interaction>Params`.
        let at = Path::interaction(interface, slot, visibility, owner, member, Vec::new())
            .step("Params");
        let index = self.tuple_ref(home, &tuple, &at);
        // The struct's fields stand for the parameters, in declaration order,
        // so each one is documented with the parameter it was induced from
        // (ADR-0028).
        self.tuples[index as usize].docs = params
            .iter()
            .filter(|param| !param.r#type.as_ref().is_some_and(is_stream))
            .map(FieldDoc::of_param)
            .collect();
        Some(v1::TupleRef { index })
    }

    #[allow(clippy::too_many_arguments)]
    fn params(
        &mut self,
        home: &'a v2::Package,
        params: &[v2::Param],
        interface: u32,
        slot: u32,
        visibility: i32,
        owner: &str,
        member: &str,
    ) -> Vec<v1::Param> {
        params
            .iter()
            .map(|param| {
                // The singular role distinguishes a parameter's tuple from
                // the request wrapper, including a parameter named `params`.
                let at = Path::interaction(interface, slot, visibility, owner, member, Vec::new())
                    .step("Param")
                    .field(&param.name);
                v1::Param {
                    name: Some(spellings(&param.name)),
                    r#type: param.r#type.as_ref().map(|ty| self.type_at(home, ty, &at)),
                    doc: param.doc.clone(),
                    links: doc_links(&param.links),
                    see: doc_links(&param.see),
                    since: param.since.clone(),
                    rules: model_rules(home, &self.deps, ItemRef::Param(param)),
                }
            })
            .collect()
    }

    fn reply(&mut self, home: &'a v2::Package, ret: &v2::ReturnType, at: &Path) -> v1::Reply {
        v1::Reply {
            kind: ret.kind.as_ref().map(|kind| match kind {
                v2::return_type::Kind::Value(value) => {
                    v1::reply::Kind::Value(self.type_at(home, value, at))
                }
                v2::return_type::Kind::Fallible(fallible) => {
                    v1::reply::Kind::Fallible(v1::Fallible {
                        ok: Some(self.type_ref(home, &fallible.ok)),
                        err: Some(self.type_ref(home, &fallible.err)),
                    })
                }
            }),
        }
    }

    fn clauses(
        &mut self,
        home: &'a v2::Package,
        contracts: &[v2::Contract],
        params: &[v2::Param],
        reply_named: Option<&str>,
    ) -> Vec<v1::Clause> {
        contracts
            .iter()
            .map(|contract| {
                let reply = match v2::ContractKind::try_from(contract.kind) {
                    Ok(v2::ContractKind::Ensure) => reply_named,
                    _ => None,
                };
                v1::Clause {
                    kind: contract.kind,
                    source: contract.source.clone(),
                    signal_refs: contract.signal_refs.clone(),
                    param_refs: contract.param_refs.clone(),
                    uses_result: contract.uses_result,
                    observer_id: contract.observer_id.clone(),
                    translation: Some(clauses::translate(
                        self.scope,
                        home,
                        &contract.source,
                        params,
                        reply,
                    )),
                }
            })
            .collect()
    }

    /// One payload: its resolved reference and the FlatBuffers bound the
    /// codec emits as `MAX_SIZE`, computed over the declaring package with
    /// the rest of the scope beside it.
    fn payload(&mut self, home: &'a v2::Package, reference: &str) -> v1::Payload {
        let max_size = self
            .scope
            .resolve(home, reference)
            .and_then(|(decl, declaring)| {
                let others = self.scope.projection_others(declaring);
                fb::max_size(
                    fb::Packages {
                        package: declaring,
                        others: &others,
                    },
                    decl,
                )
            });
        v1::Payload {
            r#type: Some(self.type_ref(home, reference)),
            flatbuffers_max_size: max_size.map(|size| u32::try_from(size).unwrap_or(u32::MAX)),
            sizes: Some(self.sizes(home, &PayloadShape::Named(reference), Some(reference))),
        }
    }

    /// The states of `shape` under both wire encodings. `reference` is the
    /// one named type the shape is, when it is one; an unbounded state
    /// takes its attribution from it.
    fn sizes(
        &self,
        home: &'a v2::Package,
        shape: &PayloadShape<'_>,
        reference: Option<&str>,
    ) -> v1::PayloadSizes {
        v1::PayloadSizes {
            proto3: Some(self.size_state(home, shape, reference, Encoding::Proto3)),
            flatbuffers: Some(self.size_state(home, shape, reference, Encoding::FlatBuffers)),
            podbuf: Some(self.size_state(home, shape, reference, Encoding::Podbuf)),
        }
    }

    /// The state of `shape` under `encoding`, from the one sizer. An
    /// unbounded FlatBuffers state carries the same attribution a root
    /// carries. `home` is the package `reference` is read from, for both
    /// halves: the sizer resolves the payload's type name in it, and the
    /// attribution resolves the same name in it.
    fn size_state(
        &self,
        home: &'a v2::Package,
        shape: &PayloadShape<'_>,
        reference: Option<&str>,
        encoding: Encoding,
    ) -> v1::SizeState {
        let state = match size::size_state(home, shape, &self.sizes, encoding) {
            SizeState::Bounded(size) => v1::size_state::State::Bounded(size),
            SizeState::Unbounded(cause) => {
                let attribution = reference
                    .and_then(|reference| self.scope.resolve(home, reference))
                    .map(|(decl, declaring)| super::fb_unbounded(declaring, decl))
                    .unwrap_or_else(|| v1::FbUnbounded {
                        cause: cause as i32,
                        ..Default::default()
                    });
                v1::size_state::State::Unbounded(attribution)
            }
            SizeState::Absent(cause) => v1::size_state::State::Absent(v1::SizeAbsent {
                cause: absent_cause(cause) as i32,
                detail: None,
            }),
        };
        v1::SizeState { state: Some(state) }
    }

    fn services(&mut self) -> Vec<v1::Service> {
        let package = self.scope.package;
        let shapes: Vec<&str> = package.shapes().map(|shape| shape.name).collect();
        package
            .services
            .iter()
            .map(|service| {
                let interface_refs: Vec<String> = service
                    .shapes
                    .iter()
                    .filter_map(|slot| match slot.kind.as_ref()? {
                        v2::service_shape::Kind::InterfaceRef(reference) => Some(reference.clone()),
                        v2::service_shape::Kind::Inline(_) => None,
                    })
                    .collect();
                let inline = service.shapes.iter().any(|slot| {
                    matches!(slot.kind.as_ref(), Some(v2::service_shape::Kind::Inline(_)))
                });
                let inline_shape = inline
                    .then(|| {
                        shapes
                            .iter()
                            .position(|name| *name == service.name)
                            .map(|position| position as u32)
                    })
                    .flatten();
                v1::Service {
                    name: Some(dotted_name(&service.name)),
                    visibility: service.visibility,
                    doc: service.doc.clone(),
                    labels: service.labels.clone(),
                    deprecated: service.deprecated.clone(),
                    interface_refs,
                    inline_shape,
                    links: doc_links(&service.links),
                    see: doc_links(&service.see),
                    since: service.since.clone(),
                    // `rules::rules` has no item for a service.
                    rules: Vec::new(),
                }
            })
            .collect()
    }

    /// The catalog of the unit the package belongs to: the unit name, the
    /// unit's hash (ADR-0014 decision 15) over the same scope the model is
    /// lowered over, the unit's retired entries, and the `compatible` hashes as
    /// given. The hash does not read `compatible`. The package is listed before
    /// the scope's others, which may hold it too; the hash and the retired list
    /// read a package named twice once.
    fn catalog(&mut self, compatible: &[[u8; 32]]) -> v1::Catalog {
        let unit = v2::unit_of(self.scope.package);
        let packages: Vec<&v2::Package> = std::iter::once(self.scope.package)
            .chain(self.scope.others.iter().copied())
            .collect();
        v1::Catalog {
            package: unit.to_owned(),
            hash: crate::catalog_hash::catalog_hash(unit, &packages).to_vec(),
            retired: v2::unit_retired(unit, &packages)
                .into_iter()
                .map(|entry| v1::RetiredInterface {
                    name: entry.name,
                    number: entry.number,
                })
                .collect(),
            compatible: compatible.iter().map(|hash| hash.to_vec()).collect(),
        }
    }
}

// ---------------------------------------------------------------------
// Patching the projection's table indices back into the model
// ---------------------------------------------------------------------

fn patch_flatbuffers(model: &mut v1::Model, projected: &flatbuffers::Projected) {
    for tuple in &mut model.tuples {
        let wire = tuple
            .name
            .as_ref()
            .map(|name| name.wire.clone())
            .unwrap_or_default();
        tuple.flatbuffers_table = projected.tuple_tables.get(&wire).copied();
        for (position, field) in tuple.fields.iter_mut().enumerate() {
            let hint = format!("{wire}Field{}", position + 1);
            if let Some(ty) = field.r#type.as_mut() {
                patch_type(ty, &hint, projected);
            }
        }
    }
    for (index, declaration) in model.declarations.iter_mut().enumerate() {
        let owner = declaration
            .name
            .as_ref()
            .map(|name| name.declared.clone())
            .unwrap_or_default();
        match declaration.kind.as_mut() {
            Some(v1::declaration::Kind::Struct(def)) => {
                for slot in &mut def.slots {
                    if let Some(v1::slot::Occupant::Field(field)) = slot.occupant.as_mut() {
                        let hint = format!(
                            "{owner}{}",
                            joined_camel(
                                field
                                    .name
                                    .as_ref()
                                    .map(|name| name.declared.as_str())
                                    .unwrap_or_default()
                            )
                        );
                        if let Some(ty) = field.r#type.as_mut() {
                            patch_type(ty, &hint, projected);
                        }
                    }
                }
            }
            Some(v1::declaration::Kind::Union(def)) => {
                for (arm_index, arm) in def.arms.iter_mut().enumerate() {
                    arm.flatbuffers_box = projected
                        .arm_boxes
                        .get(&(index as u32, arm_index as u32))
                        .copied();
                }
            }
            _ => {}
        }
    }
}

/// The entry table of every map this type reaches, by the wire induced name
/// of the map's own position — which is the name the walk that built the
/// tables recorded it under.
fn patch_type(ty: &mut v1::Type, hint: &str, projected: &flatbuffers::Projected) {
    match ty.kind.as_mut() {
        Some(v1::r#type::Kind::Array(array)) => {
            if let Some(element) = array.element.as_mut() {
                patch_type(element, &format!("{hint}Element"), projected);
            }
        }
        Some(v1::r#type::Kind::Map(map)) => {
            map.flatbuffers_entry_table = projected.entry_tables.get(hint).copied();
            if let Some(key) = map.key.as_mut() {
                patch_type(key, &format!("{hint}Key"), projected);
            }
            if let Some(value) = map.value.as_mut() {
                patch_type(value, &format!("{hint}Value"), projected);
            }
        }
        _ => {}
    }
}

// ---------------------------------------------------------------------
// Small conversions
// ---------------------------------------------------------------------

fn constraint(source: &v2::Constraint) -> v1::Constraint {
    v1::Constraint {
        min: source.min.clone(),
        max: source.max.clone(),
        step: source.step.clone(),
        len_min: source.len_min,
        len_max: source.len_max,
        pattern: source
            .pattern
            .as_deref()
            .map(|pattern| strip_regex_delimiters(pattern).to_string()),
        pattern_const: source.pattern_const.clone(),
    }
}

/// One payload of a member: its role, the type as text, and its sizes.
pub(super) type MemberPayload = (&'static str, String, Option<v1::PayloadSizes>);

/// The type of a call's request as text: the one named type, or the
/// parameter names in parentheses.
fn params_text(params: &[v2::Param]) -> String {
    single_param_type(params).map_or_else(
        || {
            let names: Vec<&str> = params
                .iter()
                .filter(|param| !param.r#type.as_ref().is_some_and(is_stream))
                .map(|param| param.name.as_str())
                .collect();
            format!("({})", names.join(", "))
        },
        str::to_string,
    )
}

/// A field type as text: the reference of a named type, and the kind of any
/// other type (an array also names its element).
fn field_text(ty: &v2::FieldType) -> String {
    use v2::field_type::Kind;
    match ty.kind.as_ref() {
        Some(Kind::Named(name)) => name.clone(),
        Some(Kind::Primitive(_)) => "primitive".to_string(),
        Some(Kind::InlineScalar(_)) => "inline scalar".to_string(),
        Some(Kind::Tuple(_)) => "tuple".to_string(),
        Some(Kind::Array(array)) => format!(
            "array of {}",
            array
                .element
                .as_ref()
                .map_or_else(|| "no type".to_string(), |e| field_text(e))
        ),
        Some(Kind::Map(_)) => "map".to_string(),
        Some(Kind::Stream(_)) => "stream".to_string(),
        None => "no type".to_string(),
    }
}

fn return_text(ret: &v2::ReturnType) -> String {
    match ret.kind.as_ref() {
        Some(v2::return_type::Kind::Value(value)) => field_text(value),
        Some(v2::return_type::Kind::Fallible(fallible)) => {
            format!("{} | {}", fallible.ok, fallible.err)
        }
        None => "()".to_string(),
    }
}

/// A member's reservation under each encoding. `payloads` is `None` for a
/// member of a kind this lowering does not know; its reservation is then
/// unsized, naming the member.
pub(super) fn reserve(member: &str, payloads: Option<&[MemberPayload]>) -> v1::Reservation {
    let state = |pick: fn(&v1::PayloadSizes) -> &Option<v1::SizeState>| {
        let Some(payloads) = payloads else {
            return unsized_reservation(format!("{member}: no known payload shape"));
        };
        let mut total = 0u64;
        for (role, text, sizes) in payloads {
            let state = sizes
                .as_ref()
                .and_then(|sizes| pick(sizes).as_ref())
                .and_then(|state| state.state.as_ref());
            match state {
                Some(v1::size_state::State::Bounded(size)) => {
                    total = total.saturating_add(u64::from(*size));
                }
                Some(v1::size_state::State::Unbounded(_) | v1::size_state::State::Absent(_))
                | None => return unsized_reservation(format!("{member}.{role}: {text}")),
            }
        }
        v1::ReservationState {
            state: Some(v1::reservation_state::State::Bytes(total)),
        }
    };
    v1::Reservation {
        proto3: Some(state(|sizes| &sizes.proto3)),
        flatbuffers: Some(state(|sizes| &sizes.flatbuffers)),
        podbuf: Some(state(|sizes| &sizes.podbuf)),
    }
}

fn unsized_reservation(by: String) -> v1::ReservationState {
    v1::ReservationState {
        state: Some(v1::reservation_state::State::Unsized(by)),
    }
}

/// The table budget of an interface: the saturating sum of the reservations
/// of its live members in `MEMBERS` order, unsized naming the first member
/// whose reservation is. A tombstone adds nothing.
fn budget(slots: &[v1::InteractionSlot]) -> v1::Reservation {
    let state = |pick: fn(&v1::Reservation) -> &Option<v1::ReservationState>| {
        let mut total = 0u64;
        for slot in slots {
            let Some(v1::interaction_slot::Occupant::Interaction(member)) = slot.occupant.as_ref()
            else {
                continue;
            };
            let state = member
                .reservation
                .as_ref()
                .and_then(|reservation| pick(reservation).as_ref())
                .and_then(|state| state.state.as_ref());
            match state {
                Some(v1::reservation_state::State::Bytes(size)) => {
                    total = total.saturating_add(*size);
                }
                Some(v1::reservation_state::State::Unsized(_)) | None => {
                    let name = member
                        .name
                        .as_ref()
                        .map_or("", |name| name.declared.as_str());
                    return unsized_reservation(name.to_string());
                }
            }
        }
        v1::ReservationState {
            state: Some(v1::reservation_state::State::Bytes(total)),
        }
    };
    v1::Reservation {
        proto3: Some(state(|reservation| &reservation.proto3)),
        flatbuffers: Some(state(|reservation| &reservation.flatbuffers)),
        podbuf: Some(state(|reservation| &reservation.podbuf)),
    }
}

/// Both encodings absent because no codec defines the shape. A query with
/// no return type takes this state, so that a reader can tell an undefined
/// shape from a toolchain too old to report one.
fn absent_sizes() -> v1::PayloadSizes {
    let state = || v1::SizeState {
        state: Some(v1::size_state::State::Absent(v1::SizeAbsent {
            cause: v1::AbsentCause::EncodingUndefined as i32,
            detail: None,
        })),
    };
    v1::PayloadSizes {
        proto3: Some(state()),
        flatbuffers: Some(state()),
        podbuf: Some(state()),
    }
}

fn retired(reserved: &v2::Reserved) -> v1::Retired {
    v1::Retired {
        name: reserved.name.as_deref().map(spellings),
        value: reserved.value,
    }
}

fn enum_value(value: &v2::EnumValue) -> v1::EnumValue {
    v1::EnumValue {
        name: Some(spellings(&value.name)),
        value: value.value,
        doc: value.doc.clone(),
        links: doc_links(&value.links),
        see: doc_links(&value.see),
        since: value.since.clone(),
        // `rules::rules` has no item for an enum value.
        rules: Vec::new(),
    }
}

/// The zero member and the init member (typl §5.8): the value 0 if declared,
/// else the lowest declared value.
fn enum_body(def: &v2::EnumDef) -> v1::Enum {
    let zero = crate::zero::enum_zero_member(&def.values);
    let lowest = def
        .values
        .iter()
        .enumerate()
        .min_by_key(|(_, value)| value.value)
        .map(|(index, _)| index);
    v1::Enum {
        values: def.values.iter().map(enum_value).collect(),
        retired: def.reserved.iter().map(retired).collect(),
        zero_member: zero.map(|index| index as u32),
        init_member: zero.or(lowest).map(|index| index as u32),
        open: def.open,
    }
}

fn timing_of(timing: &v2::Timing) -> v1::Timing {
    v1::Timing {
        mode: timing.mode,
        min_us: timing.min_us.clone(),
        max_us: timing.max_us.clone(),
        default_applied: timing.default_applied,
    }
}

fn decl_kind(decl: &v2::Decl) -> v1::DeclKind {
    match decl.kind {
        Some(v2::decl::Kind::TypeDef(_)) => v1::DeclKind::Scalar,
        Some(v2::decl::Kind::ConstDef(_)) => v1::DeclKind::Constant,
        Some(v2::decl::Kind::StructDef(_)) => v1::DeclKind::Struct,
        Some(v2::decl::Kind::EnumDef(_)) => v1::DeclKind::Enum,
        Some(v2::decl::Kind::EnumSetDef(_)) => v1::DeclKind::EnumSet,
        Some(v2::decl::Kind::UnionDef(_)) => v1::DeclKind::Union,
        _ => v1::DeclKind::Unspecified,
    }
}

/// The parameter list as a tuple: the shape of the induced argument struct,
/// one field per declared parameter in declaration order. A stream parameter
/// is not part of the request: it has no field, and travels as a stream of
/// its own. A parameter with no declared type has no struct field, so a list
/// holding one induces nothing (interaction face design, the request-shape
/// rule).
pub fn params_as_tuple(params: &[v2::Param]) -> Option<v2::TupleType> {
    let mut fields = Vec::with_capacity(params.len());
    for param in params {
        let ty = param.r#type.as_ref()?;
        if is_stream(ty) {
            continue;
        }
        fields.push(v2::TupleField {
            name: param.name.clone(),
            r#type: Some(ty.clone()),
        });
    }
    Some(v2::TupleType { fields })
}

/// The reply as a tuple, for the two product-shaped replies: a tuple reply is
/// itself, and a query with no declared return type is the empty tuple. A
/// fallible `T | E` reply, a named reply, and every other return form give
/// `None` — a named reply keeps `reply_payload`, and a fallible reply is a
/// sum this toolchain does not induce.
pub fn reply_as_tuple(ret: Option<&v2::ReturnType>) -> Option<v2::TupleType> {
    let Some(ret) = ret else {
        return Some(v2::TupleType::default());
    };
    match ret.kind.as_ref()? {
        v2::return_type::Kind::Value(ty) => match ty.kind.as_ref()? {
            v2::field_type::Kind::Tuple(tuple) => Some(tuple.clone()),
            _ => None,
        },
        _ => None,
    }
}

/// What a call's request is sized as: the induced argument struct when the
/// call has one, otherwise the single named non-stream parameter.
pub fn request_shape<'a>(
    params: &'a [v2::Param],
    induced: Option<&'a v2::TupleType>,
) -> PayloadShape<'a> {
    match (induced, single_param_type(params)) {
        (Some(tuple), None) => PayloadShape::Tuple(tuple),
        // Beside a stream parameter, the list is not the request.
        (_, Some(name)) if params.len() > 1 => PayloadShape::Named(name),
        _ => PayloadShape::Params(params),
    }
}

/// Whether a field type is a stream.
fn is_stream(ty: &v2::FieldType) -> bool {
    matches!(ty.kind, Some(v2::field_type::Kind::Stream(_)))
}

/// Whether a query's return type is a stream: a streamed reply.
fn returns_stream(ret: &v2::ReturnType) -> bool {
    matches!(&ret.kind, Some(v2::return_type::Kind::Value(ty)) if is_stream(ty))
}

/// The single declared non-stream parameter's named type — the one call shape
/// whose payload the generated face sends as it is. A stream parameter is
/// not part of the request, so it does not count.
fn single_param_type(params: &[v2::Param]) -> Option<&str> {
    let mut requested = params
        .iter()
        .filter(|param| !param.r#type.as_ref().is_some_and(is_stream));
    let param = requested.next()?;
    if requested.next().is_some() {
        return None;
    }
    named_type(param.r#type.as_ref()?)
}

pub fn query_reply_type(query: &v2::QueryDef) -> Option<&str> {
    match query.return_type.as_ref()?.kind.as_ref()? {
        v2::return_type::Kind::Value(value) => named_type(value),
        v2::return_type::Kind::Fallible(_) => None,
    }
}

fn named_type(ty: &v2::FieldType) -> Option<&str> {
    match ty.kind.as_ref()? {
        v2::field_type::Kind::Named(name) => Some(name),
        _ => None,
    }
}

fn primitive_keyword(reference: &str) -> Option<v1::PrimitiveType> {
    match reference {
        "boolean" => Some(v1::PrimitiveType::Boolean),
        "integer" => Some(v1::PrimitiveType::Integer),
        "float" => Some(v1::PrimitiveType::Float),
        "string" => Some(v1::PrimitiveType::String),
        "bytes" => Some(v1::PrimitiveType::Bytes),
        _ => None,
    }
}

/// Strips a regex literal's surrounding `/…/`, leaving the pattern body — the
/// form `strip_regex_delimiters` leaves in two backends today.
fn strip_regex_delimiters(regex: &str) -> &str {
    regex
        .strip_prefix('/')
        .and_then(|rest| rest.strip_suffix('/'))
        .unwrap_or(regex)
}

/// The model's spelling of a sizer cause.
pub(super) fn absent_cause(cause: AbsentCause) -> v1::AbsentCause {
    match cause {
        AbsentCause::EncodingUndefined => v1::AbsentCause::EncodingUndefined,
        AbsentCause::NoMessage => v1::AbsentCause::NoMessage,
        AbsentCause::RefusedMember => v1::AbsentCause::RefusedMember,
        AbsentCause::NoBound => v1::AbsentCause::NoBound,
        AbsentCause::Overflow => v1::AbsentCause::Overflow,
        AbsentCause::Unresolved => v1::AbsentCause::Unresolved,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A position inside a declaration of another package that matches no
    /// claim of that package keeps an empty wire name: the name the importer
    /// would derive for it (`ST`) is never used. No input to `lower` reaches
    /// this case, because the declaring package's own lowering reaches every
    /// position under the same name, shape and visibility; the rule is
    /// pinned on the function.
    #[test]
    fn a_foreign_position_with_no_claim_keeps_an_empty_wire_name() {
        let a = v2::Package {
            name: "a".to_string(),
            decls: vec![v2::Decl {
                name: "S".to_string(),
                visibility: v2::Visibility::Public as i32,
                kind: Some(v2::decl::Kind::StructDef(v2::StructDef::default())),
                ..Default::default()
            }],
            ..Default::default()
        };
        let b = v2::Package {
            name: "b".to_string(),
            ..Default::default()
        };
        let others = [&a];
        let mut lowering = Lowering::new(Scope {
            package: &b,
            others: &others,
        });
        let at = Path::foreign("a", "S", v2::Visibility::Public as i32).field("t");
        assert_eq!(at.wire, "ST");
        let tuple = v2::TupleType {
            fields: vec![v2::TupleField {
                name: "x".to_string(),
                r#type: None,
            }],
        };
        let index = lowering.foreign_tuple_ref(&a, &tuple, &at) as usize;
        assert_eq!(lowering.tuples[index].wire, "");
    }
}