ridl-ir 0.6.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
//! The size state of a payload, per core encoding: bounded with a byte
//! count, unbounded with a cause, or absent with a cause. A bound is an upper
//! bound: the largest legal value of the payload encodes to at most that many
//! bytes under the projection the wire backend emits (ADR-0017 for proto3,
//! ADR-0019 for FlatBuffers). Envelope and framing are excluded.
//! [`Encoding::ReprC`] has no state until the layout is defined
//! (driftsys/ridl#317).
//!
//! Only a payload that is one named type is sized, through the projections —
//! [`crate::projection::flatbuffers::max_size`] (ADR-0019 decision 8) in
//! `flatbuffers`, and ADR-0017's projection in `proto3`. This module holds the
//! context both sizers resolve names with, the string capacity, and the leaf
//! model `proto3` counts over; `flatbuffers` counts nothing of its own, it
//! reads the projection's bound and the codegen model's cause. A request of
//! zero or several parameters, an inline `T | E` reply and a stream payload
//! are absent with [`AbsentCause::EncodingUndefined`] until a record defines
//! their encoding (driftsys/ridl#336 for streams), as is every other shape
//! that is not one named type and whose encoding no codec defines;
//! [`AbsentCause`] lists every case of every cause.
//!
//! The absence is a state of its own, not a missing value: a consumer must be
//! able to tell "no bound exists" from "this toolchain computed none, for this
//! reason". `ridl-descriptor` writes no row for an absent state and a row for
//! each of the other two (`docs/design/catalog-descriptor.md`, the section
//! "The size states").

pub(crate) mod flatbuffers;
pub(crate) mod proto3;

use crate::projection::flatbuffers::Packages;
use crate::projection::proto3::{self as proto3_projection, Scalar};
use crate::v2::{
    ArrayType, Constraint, Decl, FieldType, MapType, Package, Param, PrimitiveType, ReturnType,
    StructDef, TupleType, TypeDef, UnionDef, backing, decl, field_type, return_type,
};

/// Why a declaration has no FlatBuffers bound: the attribution the codegen
/// model carries, which is the one attribution of a missing bound
/// ([`crate::codegen::fb_unbounded`]).
pub use crate::codegen::v1::FbUnboundedCause as UnboundedCause;

/// Name resolution over a package and the packages it imports, and the
/// projection's view of the same scope.
pub struct Ctx<'a> {
    packages: Packages<'a>,
    /// Every package of the scope, the root first, then `others` in order.
    /// A package in `others` with the root's name is kept here, but
    /// `packages_for` finds the root first, so the later one is never
    /// returned.
    scope: Vec<&'a Package>,
    /// For each package of `scope`, at the same position, the packages
    /// beside it, in `scope` order: what `packages_for` roots a `Packages`
    /// with. A package is never beside a package of its own name, so a
    /// package of `others` with the root's name is dropped from the root's
    /// list. In the list of any other package the root comes first, so the
    /// root shadows that package in name lookups.
    others_of: Vec<Vec<&'a Package>>,
}

impl<'a> Ctx<'a> {
    pub fn new(package: &'a Package, others: &'a [&'a Package]) -> Self {
        let scope: Vec<&'a Package> = std::iter::once(package)
            .chain(others.iter().copied())
            .collect();
        let others_of = scope
            .iter()
            .map(|home| {
                scope
                    .iter()
                    .copied()
                    .filter(|candidate| candidate.name != home.name)
                    .collect()
            })
            .collect();
        Self {
            packages: Packages { package, others },
            scope,
            others_of,
        }
    }

    /// The declaration `name` refers to, read from `home`, and the package
    /// that declares it — the package a bare name inside that declaration
    /// then resolves against. This is the projection's own name rule
    /// (`Packages::resolve`): a bare `Name` is looked up in `home`, a
    /// `pkg.Name` in the package called `pkg`, whichever package that is.
    pub fn resolve(&self, home: &'a Package, name: &str) -> Option<(&'a Decl, &'a Package)> {
        self.packages.resolve(home, name)
    }

    /// The projection's view of the scope, rooted at the package the catalog
    /// is built for: the home of a payload's type name.
    pub fn packages(&self) -> Packages<'a> {
        self.packages
    }

    /// The projection's view of the scope rooted at `declaring`, the package
    /// [`Ctx::resolve`] returned a declaration with. `max_size` resolves a
    /// bare name inside a declaration against the `package` of the
    /// `Packages` it is given, so a declaration from an imported package is
    /// sized with this, not with the home the name was read from — the way
    /// the codegen lowering roots its bound (`Lowering::payload` in
    /// `crate::codegen`). `None` when `declaring` is not a package of this
    /// scope.
    pub fn packages_for(&self, declaring: &Package) -> Option<Packages<'_>> {
        let position = self
            .scope
            .iter()
            .position(|candidate| candidate.name == declaring.name)?;
        Some(Packages {
            package: self.scope[position],
            others: &self.others_of[position],
        })
    }
}

/// What is being sized.
pub enum PayloadShape<'a> {
    /// A signal or event payload: a type name.
    Named(&'a str),
    /// A fixed payload.
    Field(&'a FieldType),
    /// A command or query request: the parameters.
    Params(&'a [Param]),
    /// A query response.
    Return(&'a ReturnType),
}

/// The one named type a payload is, or the cause of its absent state when
/// the payload is not one named type.
fn payload_name<'a>(shape: &PayloadShape<'a>) -> Result<&'a str, AbsentCause> {
    match shape {
        PayloadShape::Named(name) => Ok(name),
        PayloadShape::Field(ty) => named_field(ty),
        PayloadShape::Params([single]) => match single.r#type.as_ref() {
            Some(ty) => named_field(ty),
            None => Err(AbsentCause::EncodingUndefined),
        },
        // Zero parameters and several parameters: no codec defines the
        // encoding of either request shape.
        PayloadShape::Params(_) => Err(AbsentCause::EncodingUndefined),
        PayloadShape::Return(ret) => match ret.kind.as_ref() {
            Some(return_type::Kind::Value(ty)) => named_field(ty),
            Some(return_type::Kind::Fallible(_)) | None => Err(AbsentCause::EncodingUndefined),
        },
    }
}

/// The named type a field position is, or the cause of its absent state. A
/// `string` or `bytes` with no length bound and a type def with no width have
/// no size under any encoding, which is [`AbsentCause::NoBound`]; every other
/// shape that is not one named type has no defined encoding.
fn named_field(ty: &FieldType) -> Result<&str, AbsentCause> {
    match ty.kind.as_ref() {
        Some(field_type::Kind::Named(name)) => Ok(name),
        Some(field_type::Kind::Primitive(primitive)) => {
            Err(no_bound_or_undefined(leaf_of_primitive(*primitive)))
        }
        Some(field_type::Kind::InlineScalar(def)) => {
            Err(no_bound_or_undefined(leaf_of_type_def(def)))
        }
        Some(
            field_type::Kind::Tuple(_)
            | field_type::Kind::Array(_)
            | field_type::Kind::Map(_)
            | field_type::Kind::Stream(_),
        )
        | None => Err(AbsentCause::EncodingUndefined),
    }
}

/// A scalar position with no leaf is a value no proto3 leaf bounds, which is
/// a value with no size at all: `NoBound`. A scalar with a leaf has a size,
/// but no codec defines the encoding of a payload that is a bare scalar.
fn no_bound_or_undefined(leaf: Option<Leaf<'_>>) -> AbsentCause {
    match leaf {
        Some(_) => AbsentCause::EncodingUndefined,
        None => AbsentCause::NoBound,
    }
}

/// A core encoding a payload's size is stated for. No encoding is defined
/// for [`Encoding::ReprC`]: it has no layout until driftsys/ridl#317 lands,
/// and [`size_state`] answers [`AbsentCause::EncodingUndefined`] for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Encoding {
    Proto3,
    FlatBuffers,
    ReprC,
}

/// One payload's state under one encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeState {
    /// The maximum encoded size in bytes, envelope and framing excluded.
    Bounded(u32),
    /// No finite bound exists, with the attribution of the missing bound.
    /// FlatBuffers only: typl bounds every collection, so a proto3 message
    /// is bounded or absent.
    Unbounded(UnboundedCause),
    /// This toolchain states no size, with the reason it states none.
    Absent(AbsentCause),
}

/// Why a payload has no size state under an encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AbsentCause {
    /// No codec defines the encoding of the shape. Every case: the
    /// `repr(C)` encoding, whatever the shape; a request of zero or of
    /// several parameters; a parameter, a reply or a fixed payload that
    /// declares no type; a fallible `T | E` reply; a return type that
    /// declares no reply type; a payload, a parameter or a reply that is a
    /// tuple, an array, a map or a stream; and a payload, a parameter or a
    /// reply that is a bare scalar some proto3 leaf bounds, which has a size
    /// of its own but no defined payload encoding.
    EncodingUndefined,
    /// proto3 only: the type has no message of its own. ADR-0017 decision 1
    /// inlines a named scalar and an enum set into their field (decision 2
    /// rejects a wrapper message), and an enum is a declared `enum`.
    NoMessage,
    /// proto3 only: a failure inside the message other than the depth limit
    /// and an overflowing bound, which are [`AbsentCause::Overflow`]. Every
    /// case: a member the proto backend refuses, a name inside the message
    /// that does not resolve, a member no proto3 leaf bounds, an enum value
    /// outside int32, and a `u64` sum or product inside the walk that does
    /// not fit. This variant's text is the normative statement of the cause;
    /// the proto3 sizer's `state` implements it.
    RefusedMember,
    /// A `string` or `bytes` with no length bound, or a type def with no
    /// width: the value itself has no size.
    NoBound,
    /// The bound does not fit in a `u32`, or the nesting passes the sizer's
    /// depth limit.
    Overflow,
    /// The name does not resolve, or the declaration it names has no root
    /// form under the encoding: under FlatBuffers a declaration with no root
    /// table, under proto3 a declaration with no message at all, such as a
    /// constant or an interaction.
    Unresolved,
}

/// The state of `shape` under `encoding`, with the payload's type name read
/// from `home`.
///
/// `home` is the package the shape's bare type name resolves in, the same
/// package a caller resolves the payload's reference against. A caller that
/// reads a reference from one package and sizes it against another gets two
/// answers about one payload, so `home` is a parameter and not the root of
/// the `Ctx`.
///
/// A payload that is not one named type is absent under every encoding, with
/// the cause `payload_name` gives it: this module states a size for a named
/// type alone. `ReprC` is absent with [`AbsentCause::EncodingUndefined`]
/// whatever the shape. The `proto3` and `flatbuffers` submodules hold the
/// per-encoding rules, each in its own `state`.
pub fn size_state<'a>(
    home: &'a Package,
    shape: &PayloadShape<'_>,
    ctx: &Ctx<'a>,
    encoding: Encoding,
) -> SizeState {
    type Sizer<'a> = fn(&'a Package, &str, &Ctx<'a>) -> SizeState;
    let sizer: Sizer<'a> = match encoding {
        Encoding::Proto3 => proto3::state as Sizer<'a>,
        Encoding::FlatBuffers => flatbuffers::state as Sizer<'a>,
        Encoding::ReprC => return SizeState::Absent(AbsentCause::EncodingUndefined),
    };
    match payload_name(shape) {
        Ok(name) => sizer(home, name, ctx),
        Err(cause) => SizeState::Absent(cause),
    }
}

/// The byte capacity of a `string`: its bound in scalar values times four
/// (release-scope design §3.11). `None` when the constraint carries no
/// `len_max`: the FlatBuffers projection answers `None` for a whole type that
/// holds a string without a bound, and this function agrees with it on both
/// the multiplier and the absence
/// (`string_max_bytes_agrees_with_the_flatbuffers_projection`). The
/// compiler writes typl §4.4's `[0..256]` default into `len_max`, so a
/// compiled package never reaches the `None`. No `match` narrowing yet
/// (driftsys/ridl#665).
pub fn string_max_bytes(constraint: Option<&Constraint>) -> Option<u64> {
    constraint?.len_max?.checked_mul(4)
}

// The leaf model below is what the proto3 sizer counts over (`proto3`). The
// FlatBuffers sizer does not read it: the projection's `max_size` sizes a
// whole declaration.

/// A type resolved to what the proto3 sizer counts. A composite carries
/// `home`, the package a bare name inside it resolves against: the declaring
/// package of a named struct or union, the package of the field for an inline
/// tuple, array or map. A named struct or union also carries its declared
/// `name`, which with `home`'s name identifies the declaration: the key the
/// proto3 sizer remembers a derived bound under.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Leaf<'a> {
    /// A scalar with a largest encoding, as the proto backend spells it
    /// ([`crate::projection::proto3`]): never `string` or `bytes`, which are
    /// a [`Leaf::Blob`] when a constraint bounds them. An enum set is the
    /// scalar of its width (`enum_set_field_type` in the proto backend).
    Scalar(Scalar),
    /// A string or bytes value: its maximum byte length. The leaf model
    /// counts in `u64`, as the FlatBuffers projection does; a bounded
    /// [`SizeState`] is a `u32`, and [`proto3::state`] narrows the value when
    /// it answers, with [`AbsentCause::Overflow`] when it does not fit.
    Blob(u64),
    /// An enum: its smallest and largest live member values, both 0 when it
    /// has no member, which decide the varint length. `retired_in_int32` is
    /// false when a retired (`reserved`) value is outside proto3's int32
    /// range. A retired value is never encoded, but the proto backend
    /// refuses it as it refuses a live value outside int32 (`emit_enum`), and
    /// the sizer reproduces both refusals.
    Enum {
        min: i64,
        max: i64,
        retired_in_int32: bool,
    },
    Struct {
        name: &'a str,
        def: &'a StructDef,
        home: &'a Package,
    },
    Union {
        name: &'a str,
        def: &'a UnionDef,
        home: &'a Package,
    },
    Tuple {
        def: &'a TupleType,
        home: &'a Package,
    },
    Array {
        def: &'a ArrayType,
        home: &'a Package,
    },
    Map {
        def: &'a MapType,
        home: &'a Package,
    },
}

/// The leaf of a field type written in `home`.
pub(crate) fn leaf_of_field_type<'a>(
    ty: &'a FieldType,
    home: &'a Package,
    ctx: &Ctx<'a>,
) -> Option<Leaf<'a>> {
    match ty.kind.as_ref()? {
        field_type::Kind::Named(name) => leaf_of_name(name, home, ctx),
        field_type::Kind::Primitive(primitive) => leaf_of_primitive(*primitive),
        field_type::Kind::InlineScalar(def) => leaf_of_type_def(def),
        field_type::Kind::Tuple(def) => Some(Leaf::Tuple { def, home }),
        field_type::Kind::Array(def) => Some(Leaf::Array { def, home }),
        field_type::Kind::Map(def) => Some(Leaf::Map { def, home }),
        // A stream has no defined encoding, so its sizes are absent
        // (driftsys/ridl#336).
        field_type::Kind::Stream(_) => None,
    }
}

/// The leaf of a name written in `home`.
pub(crate) fn leaf_of_name<'a>(name: &str, home: &'a Package, ctx: &Ctx<'a>) -> Option<Leaf<'a>> {
    let (decl, declaring) = ctx.resolve(home, name)?;
    match decl.kind.as_ref()? {
        decl::Kind::TypeDef(def) => leaf_of_type_def(def),
        decl::Kind::StructDef(def) => Some(Leaf::Struct {
            name: &decl.name,
            def,
            home: declaring,
        }),
        decl::Kind::UnionDef(def) => Some(Leaf::Union {
            name: &decl.name,
            def,
            home: declaring,
        }),
        decl::Kind::EnumDef(def) => {
            let values = || def.values.iter().map(|v| v.value);
            Some(Leaf::Enum {
                min: values().min().unwrap_or(0),
                max: values().max().unwrap_or(0),
                retired_in_int32: def
                    .reserved
                    .iter()
                    .filter_map(|reserved| reserved.value)
                    .all(|retired| i32::try_from(retired).is_ok()),
            })
        }
        // The scalar of the width alone, as the proto backend resolves an
        // enum set at each use site (`enum_set_field_type`).
        decl::Kind::EnumSetDef(def) => {
            Some(Leaf::Scalar(proto3_projection::enum_set_scalar(def.width)))
        }
        decl::Kind::ConstDef(_)
        | decl::Kind::SignalDef(_)
        | decl::Kind::EventDef(_)
        | decl::Kind::CommandDef(_)
        | decl::Kind::QueryDef(_)
        | decl::Kind::FixedDef(_)
        | decl::Kind::ReservedSlot(_) => None,
    }
}

/// A bare primitive at a field position, as the proto backend projects it
/// (`proto_primitive`): an integer is `int64`, a float `double`. A bare
/// `string` or `bytes` carries no length bound, and the FlatBuffers
/// projection answers `None` for a whole type that holds one, so neither has
/// a leaf. The compiler keeps both out of a field position (TYPL-208); a map
/// key gets typl §4.4–§4.5's `[0..256]` default as an inline scalar, which
/// `leaf_of_type_def` sizes.
pub(crate) fn leaf_of_primitive<'a>(primitive: i32) -> Option<Leaf<'a>> {
    match proto3_projection::primitive(primitive) {
        Scalar::String | Scalar::Bytes => None,
        scalar => Some(Leaf::Scalar(scalar)),
    }
}

/// A named or inline scalar, as the proto backend projects it
/// (`proto_scalar`): by its width when one is set, otherwise by its backing.
/// A `string` or `bytes` is bounded by the `len_max` its constraint carries.
/// An integer or float backing without a width, a unit backing without a
/// derived width (typl §5.1) and a type def with no backing all project to
/// `string`, which no constraint bounds, so none has a leaf — the FlatBuffers
/// projection's `scalar_charge` answers `None` for the same types.
fn leaf_of_type_def<'a>(def: &'a TypeDef) -> Option<Leaf<'a>> {
    match proto3_projection::scalar(def) {
        // Like a string, a `bytes` without a `len_max` is unsizable, as the
        // FlatBuffers projection answers for the same type.
        Scalar::Bytes => def.constraint.as_ref()?.len_max.map(Leaf::Blob),
        Scalar::String => match def.backing.as_ref()?.kind.as_ref()? {
            backing::Kind::Primitive(primitive) if *primitive == PrimitiveType::String as i32 => {
                string_max_bytes(def.constraint.as_ref()).map(Leaf::Blob)
            }
            backing::Kind::Primitive(_) | backing::Kind::Unit(_) => None,
        },
        scalar => Some(Leaf::Scalar(scalar)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::projection::flatbuffers::max_size;
    use crate::v2::{
        Backing, CommandDef, ConstDef, EnumDef, EnumSetDef, EnumValue, EventDef, FallibleType,
        Field, FixedDef, FloatWidth, IntWidth, Package, Param, PrimitiveType, QueryDef, Reserved,
        ReturnType, SignalDef, StreamType, StructMember, TupleField, field_type, return_type,
        stream_type, struct_member, type_def,
    };

    fn constraint(len_max: Option<u64>, pattern: Option<&str>) -> Constraint {
        Constraint {
            len_max,
            pattern: pattern.map(str::to_owned),
            ..Default::default()
        }
    }

    fn named(name: &str) -> FieldType {
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::Named(name.to_owned())),
        }
    }

    fn primitive(primitive: PrimitiveType) -> FieldType {
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::Primitive(primitive as i32)),
        }
    }

    fn type_def(
        backing: backing::Kind,
        width: Option<type_def::Width>,
        constraint: Option<Constraint>,
    ) -> TypeDef {
        TypeDef {
            backing: Some(Backing {
                kind: Some(backing),
            }),
            constraint,
            width,
            ..Default::default()
        }
    }

    fn string_def(len_max: Option<u64>) -> TypeDef {
        type_def(
            backing::Kind::Primitive(PrimitiveType::String as i32),
            None,
            len_max.map(|n| constraint(Some(n), None)),
        )
    }

    fn bytes_def(len_max: Option<u64>) -> TypeDef {
        type_def(
            backing::Kind::Primitive(PrimitiveType::Bytes as i32),
            None,
            len_max.map(|n| constraint(Some(n), None)),
        )
    }

    fn decl(name: &str, kind: Option<decl::Kind>) -> Decl {
        Decl {
            name: name.to_owned(),
            kind,
            ..Default::default()
        }
    }

    /// A struct of one field, at ordinal 1 (typl ordinals start at 1).
    fn one_field_struct(ty: FieldType) -> StructDef {
        StructDef {
            members: vec![StructMember {
                member: Some(struct_member::Member::Field(Box::new(Field {
                    name: "f".to_owned(),
                    ordinal: 1,
                    r#type: Some(ty),
                    ..Default::default()
                }))),
            }],
            fixed_layout: false,
        }
    }

    fn package(name: &str, decls: Vec<Decl>) -> Package {
        Package {
            name: name.to_owned(),
            decls,
            ..Default::default()
        }
    }

    fn param(name: &str, ty: Option<FieldType>) -> Param {
        Param {
            name: name.to_owned(),
            r#type: ty,
            ..Default::default()
        }
    }

    fn enum_def(values: &[i64]) -> EnumDef {
        EnumDef {
            values: values
                .iter()
                .map(|&value| EnumValue {
                    name: format!("V{}", value.unsigned_abs()),
                    value,
                    doc: String::new(),
                    links: Vec::new(),
                    see: Vec::new(),
                    since: Vec::new(),
                })
                .collect(),
            reserved: Vec::new(),
        }
    }

    #[test]
    fn a_string_counts_four_bytes_per_scalar_value_whatever_its_pattern() {
        assert_eq!(string_max_bytes(None), None, "no constraint: unsizable");
        assert_eq!(
            string_max_bytes(Some(&constraint(None, None))),
            None,
            "no `len_max`: unsizable"
        );
        assert_eq!(
            string_max_bytes(Some(&constraint(Some(17), None))),
            Some(68)
        );
        // No `match` narrowing yet (driftsys/ridl#665).
        assert_eq!(
            string_max_bytes(Some(&constraint(Some(17), Some("^[A-Z0-9]{17}$")))),
            Some(68)
        );
        assert_eq!(
            string_max_bytes(Some(&constraint(Some(u64::MAX), None))),
            None,
            "the multiplication does not wrap"
        );
    }

    #[test]
    fn string_max_bytes_agrees_with_the_flatbuffers_projection() {
        // `max_size` adds the buffer header, the box table and the string's
        // own offset, terminator and alignment slack around the characters,
        // none of which depends on the length bound. The difference between
        // a 17-character string and a 0-character string is the per-character
        // charge alone, which is what `string_max_bytes` must agree with.
        let seventeen = decl("Seventeen", Some(decl::Kind::TypeDef(string_def(Some(17)))));
        let zero = decl("Zero", Some(decl::Kind::TypeDef(string_def(Some(0)))));
        let package = package("p", vec![seventeen.clone(), zero.clone()]);
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let bound_17 = max_size(ctx.packages(), &seventeen).expect("a bounded string");
        let bound_0 = max_size(ctx.packages(), &zero).expect("a bounded string");
        assert_eq!(
            Some(bound_17 - bound_0),
            string_max_bytes(Some(&constraint(Some(17), None)))
        );
        assert!(matches!(
            leaf_of_name("Seventeen", &package, &ctx),
            Some(Leaf::Blob(68))
        ));
    }

    #[test]
    fn an_unbounded_string_or_bytes_is_unsizable_as_in_the_projection() {
        // For an unbounded string or bytes, the leaf model answers `None`
        // exactly where the projection answers `None` for the type that holds
        // it, so the proto3 column cannot claim a bound the FlatBuffers column
        // refuses for the same type. The relation does not hold elsewhere: for
        // a bare `integer` or `float` at a field position, and for an enum set
        // of unspecified width, the projection answers `None` while proto3
        // emits `int64` or `double`, so a leaf exists there. A string or bytes
        // whose bound exceeds the projection's `MAX_ENCODABLE` also has a
        // leaf, while the projection answers `None`.
        let string_no_bound = decl("S", Some(decl::Kind::TypeDef(string_def(None))));
        let bytes_no_bound = decl("B", Some(decl::Kind::TypeDef(bytes_def(None))));
        let bytes_bound = decl("B32", Some(decl::Kind::TypeDef(bytes_def(Some(32)))));
        let bare_string = decl(
            "HoldsString",
            Some(decl::Kind::StructDef(one_field_struct(primitive(
                PrimitiveType::String,
            )))),
        );
        let bare_bytes = decl(
            "HoldsBytes",
            Some(decl::Kind::StructDef(one_field_struct(primitive(
                PrimitiveType::Bytes,
            )))),
        );
        let bare_bool = decl(
            "HoldsBool",
            Some(decl::Kind::StructDef(one_field_struct(primitive(
                PrimitiveType::Boolean,
            )))),
        );
        let package = package(
            "p",
            vec![
                string_no_bound.clone(),
                bytes_no_bound.clone(),
                bytes_bound.clone(),
                bare_string.clone(),
                bare_bytes.clone(),
                bare_bool.clone(),
            ],
        );
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);

        assert_eq!(max_size(ctx.packages(), &string_no_bound), None);
        assert!(leaf_of_name("S", &package, &ctx).is_none());
        assert_eq!(max_size(ctx.packages(), &bytes_no_bound), None);
        assert!(leaf_of_name("B", &package, &ctx).is_none());
        assert!(max_size(ctx.packages(), &bytes_bound).is_some());
        assert!(matches!(
            leaf_of_name("B32", &package, &ctx),
            Some(Leaf::Blob(32))
        ));

        // The bare primitives sit in a struct, the one position `max_size`
        // reaches a field from; the boolean shows the struct itself is sizable.
        assert!(max_size(ctx.packages(), &bare_bool).is_some());
        assert_eq!(max_size(ctx.packages(), &bare_string), None);
        assert!(leaf_of_field_type(&primitive(PrimitiveType::String), &package, &ctx).is_none());
        assert_eq!(max_size(ctx.packages(), &bare_bytes), None);
        assert!(leaf_of_field_type(&primitive(PrimitiveType::Bytes), &package, &ctx).is_none());
    }

    #[test]
    fn only_a_payload_that_is_one_named_type_is_sized() {
        let stream = FieldType {
            optional: false,
            kind: Some(field_type::Kind::Stream(StreamType {
                element: Some(stream_type::Element::Named("Point".to_owned())),
            })),
        };
        let primitive = primitive(PrimitiveType::Integer);
        let one = [Param {
            name: "at".to_owned(),
            r#type: Some(named("Point")),
            doc: String::new(),
            links: Vec::new(),
            see: Vec::new(),
            since: Vec::new(),
        }];
        let two = [
            one[0].clone(),
            Param {
                name: "flag".to_owned(),
                r#type: Some(primitive.clone()),
                doc: String::new(),
                links: Vec::new(),
                see: Vec::new(),
                since: Vec::new(),
            },
        ];
        let untyped_param = [Param {
            name: "at".to_owned(),
            r#type: None,
            doc: String::new(),
            links: Vec::new(),
            see: Vec::new(),
            since: Vec::new(),
        }];
        let value = ReturnType {
            kind: Some(return_type::Kind::Value(named("Point"))),
        };
        let fallible = ReturnType {
            kind: Some(return_type::Kind::Fallible(FallibleType {
                ok: "Point".to_owned(),
                err: "Coord".to_owned(),
            })),
        };
        let streamed = ReturnType {
            kind: Some(return_type::Kind::Value(stream.clone())),
        };
        let untyped = ReturnType { kind: None };

        assert_eq!(payload_name(&PayloadShape::Named("Point")), Ok("Point"));
        assert_eq!(
            payload_name(&PayloadShape::Field(&named("Point"))),
            Ok("Point")
        );
        assert_eq!(
            payload_name(&PayloadShape::Field(&primitive)),
            Err(AbsentCause::EncodingUndefined),
            "not a named type"
        );
        assert_eq!(
            payload_name(&PayloadShape::Field(&stream)),
            Err(AbsentCause::EncodingUndefined),
            "a stream: no codec defines its encoding"
        );
        assert_eq!(payload_name(&PayloadShape::Params(&one)), Ok("Point"));
        assert_eq!(
            payload_name(&PayloadShape::Params(&two)),
            Err(AbsentCause::EncodingUndefined),
            "several parameters"
        );
        assert_eq!(
            payload_name(&PayloadShape::Params(&[])),
            Err(AbsentCause::EncodingUndefined),
            "zero parameters"
        );
        assert_eq!(
            payload_name(&PayloadShape::Params(&untyped_param)),
            Err(AbsentCause::EncodingUndefined),
            "one parameter with no type"
        );
        assert_eq!(payload_name(&PayloadShape::Return(&value)), Ok("Point"));
        assert_eq!(
            payload_name(&PayloadShape::Return(&fallible)),
            Err(AbsentCause::EncodingUndefined),
            "an inline `T | E`"
        );
        assert_eq!(
            payload_name(&PayloadShape::Return(&streamed)),
            Err(AbsentCause::EncodingUndefined)
        );
        assert_eq!(
            payload_name(&PayloadShape::Return(&untyped)),
            Err(AbsentCause::EncodingUndefined)
        );
    }

    #[test]
    fn a_primitive_leaf_has_its_proto3_width() {
        match leaf_of_primitive(PrimitiveType::Integer as i32) {
            Some(Leaf::Scalar(s)) => assert_eq!(s.max_encoded_len(), Some(10)),
            other => panic!("integer is a scalar leaf, got {other:?}"),
        }
        // A bare `string` or `bytes` has no bound, so no leaf (the projection
        // answers `None` for the same field).
        assert!(leaf_of_primitive(PrimitiveType::String as i32).is_none());
        assert!(leaf_of_primitive(PrimitiveType::Bytes as i32).is_none());
    }

    #[test]
    fn every_primitive_is_a_leaf_or_unsizable() {
        // The scalar is the proto backend's (`proto_primitive`): `int64` for
        // a bare integer, `double` for a bare float.
        assert!(matches!(
            leaf_of_primitive(PrimitiveType::Boolean as i32),
            Some(Leaf::Scalar(Scalar::Bool))
        ));
        assert!(matches!(
            leaf_of_primitive(PrimitiveType::Integer as i32),
            Some(Leaf::Scalar(Scalar::Int64))
        ));
        assert!(matches!(
            leaf_of_primitive(PrimitiveType::Float as i32),
            Some(Leaf::Scalar(Scalar::Double))
        ));
        assert!(leaf_of_primitive(PrimitiveType::String as i32).is_none());
        assert!(leaf_of_primitive(PrimitiveType::Bytes as i32).is_none());
        assert!(leaf_of_primitive(PrimitiveType::Unspecified as i32).is_none());
        assert!(
            leaf_of_primitive(99).is_none(),
            "an enum tag the IR does not define"
        );
    }

    #[test]
    fn a_type_def_leaf_follows_its_backing_and_width() {
        // The scalar is the proto backend's (`proto_scalar`); the table itself
        // is pinned in [`crate::projection::proto3`]. What this test pins is
        // which types have a leaf at all, and which are a `Blob`.
        let prim = |p: PrimitiveType| backing::Kind::Primitive(p as i32);
        let int_width = |w: IntWidth| Some(type_def::Width::IntWidth(w as i32));
        let float_width = |w: FloatWidth| Some(type_def::Width::FloatWidth(w as i32));
        fn leaf(def: &TypeDef) -> Option<Leaf<'_>> {
            leaf_of_type_def(def)
        }

        assert!(matches!(
            leaf(&type_def(prim(PrimitiveType::Boolean), None, None)),
            Some(Leaf::Scalar(Scalar::Bool))
        ));
        assert!(matches!(
            leaf(&type_def(
                prim(PrimitiveType::Integer),
                int_width(IntWidth::I16),
                None
            )),
            Some(Leaf::Scalar(Scalar::Sint32))
        ));
        assert!(
            leaf(&type_def(prim(PrimitiveType::Integer), None, None)).is_none(),
            "an integer backing without a width projects to `string`, which no constraint bounds"
        );
        assert!(
            leaf(&type_def(prim(PrimitiveType::Float), None, None)).is_none(),
            "a float backing without a width projects to `string`, which no constraint bounds"
        );
        assert!(matches!(
            leaf(&type_def(
                prim(PrimitiveType::Float),
                float_width(FloatWidth::F32),
                None
            )),
            Some(Leaf::Scalar(Scalar::Float))
        ));
        assert!(matches!(leaf(&string_def(Some(17))), Some(Leaf::Blob(68))));
        assert!(
            leaf(&string_def(None)).is_none(),
            "no `len_max`: unsizable, as in the projection"
        );
        assert!(matches!(leaf(&bytes_def(Some(32))), Some(Leaf::Blob(32))));
        assert!(
            leaf(&bytes_def(None)).is_none(),
            "no `len_max`: unsizable, as in the projection"
        );
        assert!(leaf(&type_def(prim(PrimitiveType::Unspecified), None, None)).is_none());

        // `ridl-sem` never emits a backing that disagrees with its width, but
        // `from_binary` decodes an IR file without validating it. The width
        // decides the leaf, as the backends project by the width first.
        assert!(matches!(
            leaf(&type_def(
                prim(PrimitiveType::Boolean),
                int_width(IntWidth::U16),
                None
            )),
            Some(Leaf::Scalar(Scalar::Uint32))
        ));
        assert!(matches!(
            leaf(&type_def(
                prim(PrimitiveType::Integer),
                float_width(FloatWidth::F32),
                None
            )),
            Some(Leaf::Scalar(Scalar::Float))
        ));
        assert!(
            matches!(
                leaf(&type_def(
                    prim(PrimitiveType::String),
                    int_width(IntWidth::U8),
                    Some(constraint(Some(17), None))
                )),
                Some(Leaf::Scalar(Scalar::Uint32))
            ),
            "a string backing with a width is the width's scalar, not a blob"
        );

        let unit = || backing::Kind::Unit("km/h".to_owned());
        assert!(matches!(
            leaf(&type_def(unit(), int_width(IntWidth::U16), None)),
            Some(Leaf::Scalar(Scalar::Uint32))
        ));
        assert!(matches!(
            leaf(&type_def(unit(), float_width(FloatWidth::F64), None)),
            Some(Leaf::Scalar(Scalar::Double))
        ));
        assert!(
            leaf(&type_def(unit(), None, None)).is_none(),
            "the proto backend emits `string` for a unit without a width"
        );
        assert!(leaf(&TypeDef::default()).is_none(), "no backing");
        assert!(
            leaf(&type_def(
                prim(PrimitiveType::Bytes),
                None,
                Some(constraint(None, None))
            ))
            .is_none(),
            "a constraint without `len_max`: unsizable"
        );
        assert!(
            matches!(
                leaf(&type_def(
                    prim(PrimitiveType::Integer),
                    Some(type_def::Width::IntWidth(99)),
                    None
                )),
                Some(Leaf::Scalar(Scalar::Int64))
            ),
            "an integer width tag the IR does not define is `int64`, as the backend emits"
        );
        assert!(
            matches!(
                leaf(&type_def(
                    prim(PrimitiveType::Float),
                    Some(type_def::Width::FloatWidth(99)),
                    None
                )),
                Some(Leaf::Scalar(Scalar::Double))
            ),
            "a float width tag the IR does not define is `double`, as the backend emits"
        );
    }

    #[test]
    fn every_declaration_kind_resolves_to_a_leaf_or_none() {
        let home = package(
            "p",
            vec![
                decl("Speed", Some(decl::Kind::TypeDef(string_def(Some(3))))),
                decl("Point", Some(decl::Kind::StructDef(StructDef::default()))),
                decl("Shape", Some(decl::Kind::UnionDef(UnionDef::default()))),
                decl("Gear", Some(decl::Kind::EnumDef(enum_def(&[-3, 0, 7])))),
                decl("Mode", Some(decl::Kind::EnumDef(enum_def(&[0, 5])))),
                decl(
                    "Flags",
                    Some(decl::Kind::EnumSetDef(EnumSetDef {
                        width: IntWidth::U8 as i32,
                        ..Default::default()
                    })),
                ),
                decl("MAX", Some(decl::Kind::ConstDef(ConstDef::default()))),
                decl("speed", Some(decl::Kind::SignalDef(SignalDef::default()))),
                decl("tick", Some(decl::Kind::EventDef(EventDef::default()))),
                decl("go", Some(decl::Kind::CommandDef(CommandDef::default()))),
                decl("ask", Some(decl::Kind::QueryDef(QueryDef::default()))),
                decl("fixed", Some(decl::Kind::FixedDef(FixedDef::default()))),
                decl("gone", Some(decl::Kind::ReservedSlot(Reserved::default()))),
                decl("Untyped", None),
                decl("Empty", Some(decl::Kind::EnumDef(enum_def(&[])))),
                decl(
                    "OddFlags",
                    Some(decl::Kind::EnumSetDef(EnumSetDef {
                        width: 99,
                        ..Default::default()
                    })),
                ),
            ],
        );
        let other = package(
            "q",
            vec![decl(
                "Thing",
                Some(decl::Kind::UnionDef(UnionDef::default())),
            )],
        );
        let others = [&other];
        let ctx = Ctx::new(&home, &others);

        assert!(matches!(
            leaf_of_name("Speed", &home, &ctx),
            Some(Leaf::Blob(12))
        ));
        assert!(matches!(
            leaf_of_name("Point", &home, &ctx),
            Some(Leaf::Struct { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_name("Shape", &home, &ctx),
            Some(Leaf::Union { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_name("Gear", &home, &ctx),
            Some(Leaf::Enum {
                min: -3,
                max: 7,
                retired_in_int32: true
            })
        ));
        assert!(matches!(
            leaf_of_name("Mode", &home, &ctx),
            Some(Leaf::Enum {
                min: 0,
                max: 5,
                retired_in_int32: true
            })
        ));
        assert!(
            matches!(
                leaf_of_name("Flags", &home, &ctx),
                Some(Leaf::Scalar(Scalar::Uint32))
            ),
            "an enum set is its width's scalar, as `enum_set_field_type` emits"
        );
        assert!(
            matches!(
                leaf_of_name("Empty", &home, &ctx),
                Some(Leaf::Enum {
                    min: 0,
                    max: 0,
                    retired_in_int32: true
                })
            ),
            "an enum with no member has magnitude 0"
        );
        assert!(
            matches!(
                leaf_of_name("OddFlags", &home, &ctx),
                Some(Leaf::Scalar(Scalar::Int64))
            ),
            "a width tag the IR does not define is `int64`, as the backend emits"
        );
        for name in [
            "MAX", "speed", "tick", "go", "ask", "fixed", "gone", "Untyped",
        ] {
            assert!(
                leaf_of_name(name, &home, &ctx).is_none(),
                "{name} has no leaf"
            );
        }
        assert!(
            leaf_of_name("Nowhere", &home, &ctx).is_none(),
            "an unresolved name"
        );
        assert!(
            leaf_of_name("q.Nowhere", &home, &ctx).is_none(),
            "an unresolved member of a known package"
        );
        assert!(
            leaf_of_name("r.Thing", &home, &ctx).is_none(),
            "an unknown package"
        );

        // The projection's name rule: a `pkg.Name` resolves in the package
        // called `pkg`, which may be the root package itself; a bare name
        // resolves in the home package only.
        assert!(matches!(
            leaf_of_name("p.Point", &home, &ctx),
            Some(Leaf::Struct { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_name("q.Thing", &home, &ctx),
            Some(Leaf::Union { home: h, .. }) if h.name == "q"
        ));
        assert!(
            leaf_of_name("Thing", &home, &ctx).is_none(),
            "a foreign declaration does not resolve by its bare name from p"
        );
        assert!(matches!(
            leaf_of_name("Thing", &other, &ctx),
            Some(Leaf::Union { home: h, .. }) if h.name == "q"
        ));
        assert_eq!(ctx.packages().package.name, "p");
        assert_eq!(ctx.packages().others.len(), 1);
    }

    #[test]
    fn a_bare_name_inside_an_imported_declaration_resolves_in_its_own_package() {
        // `q.Thing` holds a field `Inner`, bare, so relative to q; the root
        // package declares a different `Inner`. The field must resolve to q's.
        let root = package(
            "p",
            vec![
                decl("Inner", Some(decl::Kind::StructDef(StructDef::default()))),
                decl(
                    "OnlyInRoot",
                    Some(decl::Kind::StructDef(StructDef::default())),
                ),
            ],
        );
        let imported = package(
            "q",
            vec![
                decl(
                    "Thing",
                    Some(decl::Kind::StructDef(one_field_struct(named("Inner")))),
                ),
                decl("Inner", Some(decl::Kind::EnumDef(enum_def(&[0, 1])))),
            ],
        );
        let others = [&imported];
        let ctx = Ctx::new(&root, &others);

        let (def, home) = match leaf_of_name("q.Thing", &root, &ctx) {
            Some(Leaf::Struct { def, home, .. }) => (def, home),
            other => panic!("q.Thing is a struct leaf, got {other:?}"),
        };
        assert_eq!(
            home.name, "q",
            "the composite carries its declaring package"
        );
        let field = match &def.members[0].member {
            Some(struct_member::Member::Field(field)) => field.r#type.as_ref().unwrap(),
            other => panic!("one field, got {other:?}"),
        };
        assert!(
            matches!(
                leaf_of_field_type(field, home, &ctx),
                Some(Leaf::Enum {
                    min: 0,
                    max: 1,
                    retired_in_int32: true
                })
            ),
            "resolved against q, the field is q's enum `Inner`"
        );
        // The same field read against the root package would be the root's
        // struct `Inner`: the home the leaf carries is what keeps the two
        // apart.
        assert!(matches!(
            leaf_of_field_type(field, &root, &ctx),
            Some(Leaf::Struct { home: h, .. }) if h.name == "p"
        ));
        assert!(
            leaf_of_name("OnlyInRoot", &imported, &ctx).is_none(),
            "a bare name only the root declares does not resolve from q"
        );
        assert!(matches!(
            leaf_of_name("OnlyInRoot", &root, &ctx),
            Some(Leaf::Struct { home: h, .. }) if h.name == "p"
        ));
    }

    #[test]
    fn packages_for_lists_the_root_first_then_the_others_in_order() {
        let root = package("p", vec![]);
        let second = package("q", vec![]);
        let third = package("r", vec![]);
        // Same name as the root, with a declaration the root lacks.
        let same_name = package(
            "p",
            vec![decl(
                "Shadowed",
                Some(decl::Kind::StructDef(StructDef::default())),
            )],
        );
        let others = [&second, &third, &same_name];
        let ctx = Ctx::new(&root, &others);
        let names = |packages: Packages<'_>| -> Vec<String> {
            std::iter::once(packages.package)
                .chain(packages.others.iter().copied())
                .map(|package| package.name.clone())
                .collect()
        };

        assert_eq!(names(ctx.packages_for(&root).unwrap()), ["p", "q", "r"]);
        assert_eq!(
            names(ctx.packages_for(&second).unwrap()),
            ["q", "p", "r", "p"]
        );
        assert_eq!(
            names(ctx.packages_for(&third).unwrap()),
            ["r", "p", "q", "p"]
        );
        // The root's own view drops the package that has the root's name, and
        // the root shadows it in every other view.
        assert!(
            ctx.packages_for(&root)
                .unwrap()
                .others
                .iter()
                .all(|other| !std::ptr::eq(*other, &same_name))
        );
        assert!(ctx.resolve(&second, "p.Shadowed").is_none());
    }

    #[test]
    fn every_field_type_kind_resolves_to_a_leaf_or_none() {
        let home = package(
            "p",
            vec![decl(
                "Point",
                Some(decl::Kind::StructDef(StructDef::default())),
            )],
        );
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&home, &others);
        let field = |kind: field_type::Kind| FieldType {
            optional: false,
            kind: Some(kind),
        };

        assert!(matches!(
            leaf_of_field_type(&named("Point"), &home, &ctx),
            Some(Leaf::Struct { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_field_type(&primitive(PrimitiveType::Boolean), &home, &ctx),
            Some(Leaf::Scalar(Scalar::Bool))
        ));
        assert!(matches!(
            leaf_of_field_type(
                &field(field_type::Kind::InlineScalar(Box::new(string_def(Some(
                    2
                ))))),
                &home,
                &ctx
            ),
            Some(Leaf::Blob(8))
        ));
        assert!(matches!(
            leaf_of_field_type(
                &field(field_type::Kind::Tuple(TupleType {
                    fields: vec![TupleField {
                        name: "x".to_owned(),
                        r#type: Some(named("Point")),
                    }],
                })),
                &home,
                &ctx
            ),
            Some(Leaf::Tuple { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_field_type(
                &field(field_type::Kind::Array(Box::new(ArrayType {
                    element: Some(Box::new(named("Point"))),
                    min: 0,
                    max: 4,
                }))),
                &home,
                &ctx
            ),
            Some(Leaf::Array { home: h, .. }) if h.name == "p"
        ));
        assert!(matches!(
            leaf_of_field_type(
                &field(field_type::Kind::Map(Box::new(MapType {
                    key: Some(Box::new(named("Point"))),
                    value: Some(Box::new(named("Point"))),
                    min: 0,
                    max: 4,
                }))),
                &home,
                &ctx
            ),
            Some(Leaf::Map { home: h, .. }) if h.name == "p"
        ));
        assert!(
            leaf_of_field_type(
                &field(field_type::Kind::Stream(StreamType {
                    element: Some(stream_type::Element::Named("Point".to_owned())),
                })),
                &home,
                &ctx
            )
            .is_none(),
            "a stream has no defined encoding, so its sizes are absent"
        );
        assert!(
            leaf_of_field_type(
                &FieldType {
                    optional: false,
                    kind: None
                },
                &home,
                &ctx
            )
            .is_none(),
            "no kind"
        );
    }

    #[test]
    fn repr_c_is_absent_with_encoding_undefined() {
        // `Point` resolves, so a `ReprC` arm routed to a sizer would reach
        // that sizer, and both sizers answer a bound for it; such a routing
        // fails this test.
        let package = package(
            "p",
            vec![decl(
                "Point",
                Some(decl::Kind::StructDef(one_field_struct(primitive(
                    PrimitiveType::Boolean,
                )))),
            )],
        );
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        assert_eq!(
            size_state(
                &package,
                &PayloadShape::Named("Point"),
                &ctx,
                Encoding::ReprC
            ),
            SizeState::Absent(AbsentCause::EncodingUndefined)
        );
    }

    /// The two encodings a state is defined for.
    const WIRE: [Encoding; 2] = [Encoding::Proto3, Encoding::FlatBuffers];

    #[test]
    fn the_home_decides_which_package_a_bare_payload_name_is_read_from() {
        // `Point` is declared in `q` alone. Read from `q` the bare name
        // resolves and both encodings answer a bound; read from the root `p`
        // it resolves nowhere. A sizer that read the name from the root of
        // the `Ctx` instead of its `home` answers the same state for both.
        let root = package("p", vec![]);
        let other = package(
            "q",
            vec![decl(
                "Point",
                Some(decl::Kind::StructDef(one_field_struct(primitive(
                    PrimitiveType::Boolean,
                )))),
            )],
        );
        let others = [&other];
        let ctx = Ctx::new(&root, &others);
        for encoding in WIRE {
            assert!(
                matches!(
                    size_state(&other, &PayloadShape::Named("Point"), &ctx, encoding),
                    SizeState::Bounded(_)
                ),
                "{encoding:?}, read from q"
            );
            assert_eq!(
                size_state(&root, &PayloadShape::Named("Point"), &ctx, encoding),
                SizeState::Absent(AbsentCause::Unresolved),
                "{encoding:?}, read from p"
            );
        }
    }

    #[test]
    fn a_named_scalar_has_no_proto3_message() {
        // ADR-0017 decision 1 inlines a named scalar into its field and
        // decision 2 rejects a wrapper message, so proto3 has no message to
        // size. ADR-0019 decision 8 gives the same scalar a box table, so
        // FlatBuffers does have a bound.
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let shape = PayloadShape::Named("Vin");
        assert_eq!(
            size_state(&package, &shape, &ctx, Encoding::Proto3),
            SizeState::Absent(AbsentCause::NoMessage)
        );
        assert!(matches!(
            size_state(&package, &shape, &ctx, Encoding::FlatBuffers),
            SizeState::Bounded(_)
        ));
    }

    #[test]
    fn a_stream_payload_is_undefined_in_both_encodings() {
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let stream = FieldType {
            optional: false,
            kind: Some(field_type::Kind::Stream(StreamType {
                element: Some(stream_type::Element::Named("Point".to_owned())),
            })),
        };
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Field(&stream), &ctx, encoding),
                SizeState::Absent(AbsentCause::EncodingUndefined),
                "{encoding:?}"
            );
        }
    }

    #[test]
    fn two_parameters_are_undefined_in_both_encodings() {
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let params = [param("at", Some(named("Point"))), param("to", None)];
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Params(&params), &ctx, encoding),
                SizeState::Absent(AbsentCause::EncodingUndefined),
                "{encoding:?}"
            );
            assert_eq!(
                size_state(&package, &PayloadShape::Params(&[]), &ctx, encoding),
                SizeState::Absent(AbsentCause::EncodingUndefined),
                "{encoding:?}, zero parameters"
            );
        }
    }

    #[test]
    fn a_fallible_reply_is_undefined_in_both_encodings() {
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let fallible = ReturnType {
            kind: Some(return_type::Kind::Fallible(FallibleType {
                ok: "Point".to_owned(),
                err: "Coord".to_owned(),
            })),
        };
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Return(&fallible), &ctx, encoding),
                SizeState::Absent(AbsentCause::EncodingUndefined),
                "{encoding:?}"
            );
        }
    }

    #[test]
    fn an_unbounded_string_has_no_bound() {
        // A `string` with no length bound has no size under either encoding:
        // neither the bare primitive nor an inline scalar that carries no
        // `len_max`.
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let bare = primitive(PrimitiveType::String);
        let inline = FieldType {
            optional: false,
            kind: Some(field_type::Kind::InlineScalar(Box::new(string_def(None)))),
        };
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Field(&bare), &ctx, encoding),
                SizeState::Absent(AbsentCause::NoBound),
                "{encoding:?}, a bare `string`"
            );
            assert_eq!(
                size_state(&package, &PayloadShape::Field(&inline), &ctx, encoding),
                SizeState::Absent(AbsentCause::NoBound),
                "{encoding:?}, an inline `string` with no bound"
            );
        }
    }

    #[test]
    fn an_unbounded_string_request_has_no_bound_rather_than_no_encoding() {
        // `command set(name: string)`. The one parameter is a scalar, so no
        // codec defines the request's encoding — but the value itself has no
        // size either, and the narrower cause is the one a consumer needs:
        // bounding the string would not give the shape an encoding, while
        // defining the encoding would not give the value a bound. A
        // `payload_name` that answered `EncodingUndefined` for this shape
        // fails here.
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let params = [param("name", Some(primitive(PrimitiveType::String)))];
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Params(&params), &ctx, encoding),
                SizeState::Absent(AbsentCause::NoBound),
                "{encoding:?}"
            );
        }
    }

    #[test]
    fn an_unbounded_string_reply_has_no_bound_rather_than_no_encoding() {
        // `query name() -> string`, the reply half of the shape above.
        let package = tests_support::fixture();
        let others: [&Package; 0] = [];
        let ctx = Ctx::new(&package, &others);
        let value = ReturnType {
            kind: Some(return_type::Kind::Value(primitive(PrimitiveType::String))),
        };
        for encoding in WIRE {
            assert_eq!(
                size_state(&package, &PayloadShape::Return(&value), &ctx, encoding),
                SizeState::Absent(AbsentCause::NoBound),
                "{encoding:?}"
            );
        }
    }

    #[test]
    fn max_size_over_an_imported_declaration_is_rooted_at_its_package() {
        // `q.Thing { f: Inner }` names q's `Inner`, a one-boolean struct;
        // the root package declares a wider `Inner`. A `Packages` rooted at
        // the root would size q's `Thing` with the root's `Inner`.
        let root = package(
            "p",
            vec![decl(
                "Inner",
                Some(decl::Kind::StructDef(one_field_struct(FieldType {
                    optional: false,
                    kind: Some(field_type::Kind::InlineScalar(Box::new(string_def(Some(
                        100,
                    ))))),
                }))),
            )],
        );
        let imported = package(
            "q",
            vec![
                decl(
                    "Thing",
                    Some(decl::Kind::StructDef(one_field_struct(named("Inner")))),
                ),
                decl(
                    "Inner",
                    Some(decl::Kind::StructDef(one_field_struct(primitive(
                        PrimitiveType::Boolean,
                    )))),
                ),
            ],
        );
        let others = [&imported];
        let ctx = Ctx::new(&root, &others);

        let (thing, declaring) = ctx.resolve(&root, "q.Thing").expect("q.Thing resolves");
        assert_eq!(declaring.name, "q");
        let rooted = ctx.packages_for(declaring).expect("q is in scope");
        assert_eq!(rooted.package.name, "q");
        assert_eq!(rooted.others.len(), 1);
        assert_eq!(rooted.others[0].name, "p");

        let expected = max_size(
            Packages {
                package: &imported,
                others: &[&root],
            },
            thing,
        )
        .expect("a one-boolean struct inside a struct is bounded");
        assert_eq!(max_size(rooted, thing), Some(expected));
        assert_ne!(
            max_size(ctx.packages(), thing),
            Some(expected),
            "rooted at p, the bare `Inner` is p's wider struct"
        );

        let at_root = ctx.packages_for(&root).expect("the root is in scope");
        assert_eq!(at_root.package.name, "p");
        assert_eq!(at_root.others.len(), 1);
        assert!(
            ctx.packages_for(&package("r", vec![])).is_none(),
            "a package outside the scope"
        );
    }

    #[test]
    fn an_inline_composite_leaf_carries_the_package_of_its_field() {
        let root = package("p", vec![]);
        let imported = package(
            "q",
            vec![decl(
                "Point",
                Some(decl::Kind::StructDef(StructDef::default())),
            )],
        );
        let others = [&imported];
        let ctx = Ctx::new(&root, &others);
        let field = |kind: field_type::Kind| FieldType {
            optional: false,
            kind: Some(kind),
        };
        let tuple = field(field_type::Kind::Tuple(TupleType {
            fields: vec![TupleField {
                name: "x".to_owned(),
                r#type: Some(named("Point")),
            }],
        }));
        let array = field(field_type::Kind::Array(Box::new(ArrayType {
            element: Some(Box::new(named("Point"))),
            min: 0,
            max: 4,
        })));
        let map = field(field_type::Kind::Map(Box::new(MapType {
            key: Some(Box::new(named("Point"))),
            value: Some(Box::new(named("Point"))),
            min: 0,
            max: 4,
        })));

        assert!(matches!(
            leaf_of_field_type(&tuple, &imported, &ctx),
            Some(Leaf::Tuple { home, .. }) if home.name == "q"
        ));
        assert!(matches!(
            leaf_of_field_type(&array, &imported, &ctx),
            Some(Leaf::Array { home, .. }) if home.name == "q"
        ));
        assert!(matches!(
            leaf_of_field_type(&map, &imported, &ctx),
            Some(Leaf::Map { home, .. }) if home.name == "q"
        ));
    }
}

#[cfg(test)]
pub(crate) mod tests_support {
    use crate::v2::{
        ArrayType, Backing, ConstDef, Constraint, Decl, Field, FieldType, IntWidth, MapType,
        Package, PrimitiveType, StructDef, StructMember, TypeDef, UnionArm, UnionDef, backing,
        decl, field_type, struct_member, type_def,
    };

    fn scalar_def(
        primitive: PrimitiveType,
        width: Option<IntWidth>,
        constraint: Option<Constraint>,
    ) -> TypeDef {
        TypeDef {
            backing: Some(Backing {
                kind: Some(backing::Kind::Primitive(primitive as i32)),
            }),
            constraint,
            width: width.map(|w| type_def::Width::IntWidth(w as i32)),
            ..Default::default()
        }
    }

    pub(crate) fn inline(def: TypeDef) -> FieldType {
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::InlineScalar(Box::new(def))),
        }
    }

    pub(crate) fn named(name: &str) -> FieldType {
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::Named(name.to_owned())),
        }
    }

    pub(crate) fn array_u8_max4() -> FieldType {
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::Array(Box::new(ArrayType {
                element: Some(Box::new(inline(scalar_def(
                    PrimitiveType::Integer,
                    Some(IntWidth::U8),
                    None,
                )))),
                min: 0,
                max: 4,
            }))),
        }
    }

    pub(crate) fn map_str8_u32_max2() -> FieldType {
        let key = inline(scalar_def(
            PrimitiveType::String,
            None,
            Some(Constraint {
                len_max: Some(8),
                ..Default::default()
            }),
        ));
        let value = inline(scalar_def(
            PrimitiveType::Integer,
            Some(IntWidth::U32),
            None,
        ));
        FieldType {
            optional: false,
            kind: Some(field_type::Kind::Map(Box::new(MapType {
                key: Some(Box::new(key)),
                value: Some(Box::new(value)),
                min: 0,
                max: 2,
            }))),
        }
    }

    /// `Coord = integer [-1000..1000]` (i16); `Point { x: Coord, y: Coord }`;
    /// `Vin = string [17..17] match /^[A-HJ-NPR-Z0-9]{17}$/`;
    /// `Bag { tag: Vin, flags: [u8; 0..4], index: {string [0..8]: u32; 0..2} }`;
    /// `Shape = Point | Coord`; `const LIMIT`.
    pub(crate) fn fixture() -> Package {
        let field = |name: &str, ordinal: u32, ty: FieldType| StructMember {
            member: Some(struct_member::Member::Field(Box::new(Field {
                name: name.to_owned(),
                ordinal,
                r#type: Some(ty),
                ..Default::default()
            }))),
        };
        let arm = |name: &str, ordinal: u32, type_ref: &str| UnionArm {
            name: name.to_owned(),
            ordinal,
            type_ref: type_ref.to_owned(),
            ..Default::default()
        };
        Package {
            name: "p".to_owned(),
            decls: vec![
                Decl {
                    name: "Coord".to_owned(),
                    kind: Some(decl::Kind::TypeDef(scalar_def(
                        PrimitiveType::Integer,
                        Some(IntWidth::I16),
                        None,
                    ))),
                    ..Default::default()
                },
                Decl {
                    name: "Point".to_owned(),
                    kind: Some(decl::Kind::StructDef(StructDef {
                        members: vec![field("x", 1, named("Coord")), field("y", 2, named("Coord"))],
                        fixed_layout: false,
                    })),
                    ..Default::default()
                },
                Decl {
                    name: "Vin".to_owned(),
                    kind: Some(decl::Kind::TypeDef(scalar_def(
                        PrimitiveType::String,
                        None,
                        Some(Constraint {
                            len_min: Some(17),
                            len_max: Some(17),
                            pattern: Some("/^[A-HJ-NPR-Z0-9]{17}$/".to_owned()),
                            ..Default::default()
                        }),
                    ))),
                    ..Default::default()
                },
                Decl {
                    name: "Bag".to_owned(),
                    kind: Some(decl::Kind::StructDef(StructDef {
                        members: vec![
                            field("tag", 1, named("Vin")),
                            field("flags", 2, array_u8_max4()),
                            field("index", 3, map_str8_u32_max2()),
                        ],
                        fixed_layout: false,
                    })),
                    ..Default::default()
                },
                Decl {
                    name: "Shape".to_owned(),
                    kind: Some(decl::Kind::UnionDef(UnionDef {
                        arms: vec![arm("a", 1, "Point"), arm("b", 2, "Coord")],
                        ..Default::default()
                    })),
                    ..Default::default()
                },
                Decl {
                    name: "LIMIT".to_owned(),
                    kind: Some(decl::Kind::ConstDef(ConstDef {
                        type_ref: Some("Coord".to_owned()),
                        value: "7".to_owned(),
                        regex: None,
                    })),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }
    }

    /// Two packages whose declarations share names, so a bare name inside a
    /// declaration of the imported package `q` resolves differently in `q`
    /// and in the root `p`. In `p`: `Inner { s: string [0..100] }` and
    /// `Hole { b: boolean }`, both bounded. In `q`: `Thing { f: Inner }` over
    /// a one-boolean `Inner`, and `Loose { f: Hole }` over a `Hole` that holds
    /// a bare `string`, which no projection bounds. Sized in `q`, `Thing` is
    /// small and `Loose` unbounded; sized in `p` by mistake, `Thing` is wide
    /// and `Loose` bounded.
    pub(crate) fn two_package_fixture() -> (Package, Package) {
        let one_field = |name: &str, ty: FieldType| StructDef {
            members: vec![StructMember {
                member: Some(struct_member::Member::Field(Box::new(Field {
                    name: name.to_owned(),
                    ordinal: 1,
                    r#type: Some(ty),
                    ..Default::default()
                }))),
            }],
            fixed_layout: false,
        };
        let structure = |name: &str, def: StructDef| Decl {
            name: name.to_owned(),
            kind: Some(decl::Kind::StructDef(def)),
            ..Default::default()
        };
        let boolean = FieldType {
            optional: false,
            kind: Some(field_type::Kind::Primitive(PrimitiveType::Boolean as i32)),
        };
        let bare_string = FieldType {
            optional: false,
            kind: Some(field_type::Kind::Primitive(PrimitiveType::String as i32)),
        };
        let string_100 = inline(scalar_def(
            PrimitiveType::String,
            None,
            Some(Constraint {
                len_max: Some(100),
                ..Default::default()
            }),
        ));
        let root = Package {
            name: "p".to_owned(),
            decls: vec![
                structure("Inner", one_field("s", string_100)),
                structure("Hole", one_field("b", boolean.clone())),
            ],
            ..Default::default()
        };
        let imported = Package {
            name: "q".to_owned(),
            decls: vec![
                structure("Thing", one_field("f", named("Inner"))),
                structure("Inner", one_field("b", boolean)),
                structure("Loose", one_field("f", named("Hole"))),
                structure("Hole", one_field("text", bare_string)),
            ],
            ..Default::default()
        };
        (root, imported)
    }

    /// `Open { text: string }` with no bound on the string: the one member
    /// the FlatBuffers projection cannot bound, so `max_size` answers `None`
    /// and the codegen model attributes the `Member` cause to it.
    pub(crate) fn unbounded_fixture() -> Package {
        Package {
            name: "q".to_owned(),
            decls: vec![Decl {
                name: "Open".to_owned(),
                kind: Some(decl::Kind::StructDef(StructDef {
                    members: vec![StructMember {
                        member: Some(struct_member::Member::Field(Box::new(Field {
                            name: "text".to_owned(),
                            ordinal: 1,
                            r#type: Some(FieldType {
                                optional: false,
                                kind: Some(field_type::Kind::Primitive(
                                    PrimitiveType::String as i32,
                                )),
                            }),
                            ..Default::default()
                        }))),
                    }],
                    fixed_layout: false,
                })),
                ..Default::default()
            }],
            ..Default::default()
        }
    }
}