prebindgen-flat 0.5.0

The prebindgen flat model: the parser from captured #[prebindgen] records to a flat namespace of elements
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
//! The acceptance matrix: source spelling → element, or a diagnosis naming the
//! item and the component that could not be expressed.
//!
//! Ported from #212/#226 and extended to functions, consts and item kinds.

use super::*;

fn kind(ty: proc_macro2::TokenStream) -> TypeKind {
    lower(ty).expect("in the language").kind
}

fn reason(ty: proc_macro2::TokenStream) -> UnsupportedTypeReason {
    lower(ty).expect_err("outside the language").reason
}

// ── Types ──────────────────────────────────────────────────────────────

#[test]
fn scalars_and_strings() {
    assert!(matches!(
        kind(quote::quote!(u8)),
        TypeKind::Scalar(ScalarKind::U8)
    ));
    assert!(matches!(
        kind(quote::quote!(bool)),
        TypeKind::Scalar(ScalarKind::Bool)
    ));
    assert!(matches!(
        kind(quote::quote!(f64)),
        TypeKind::Scalar(ScalarKind::F64)
    ));
    assert!(matches!(kind(quote::quote!(String)), TypeKind::String));
    assert!(matches!(kind(quote::quote!(())), TypeKind::Unit));
}

/// `str` and `String` are two Rust types, so they are two kinds. That they are
/// one *string* to every destination language is a destination's reading, and
/// the adapters make it — the model reports what the source wrote.
///
/// Neither is a nominal type: both are in the grammar, so no adapter goes
/// looking for a declared item named `str` to resolve.
#[test]
fn the_two_string_types_stay_two() {
    assert!(matches!(kind(quote::quote!(str)), TypeKind::Str));
    assert!(matches!(kind(quote::quote!(String)), TypeKind::String));
    for (spelling, owned) in [(quote::quote!(&str), false), (quote::quote!(&String), true)] {
        let TypeKind::Ref { mutable, inner, .. } = kind(spelling) else {
            panic!("a borrow");
        };
        assert!(!mutable);
        assert_eq!(matches!(inner.kind, TypeKind::String), owned);
        assert_eq!(matches!(inner.kind, TypeKind::Str), !owned);
    }
}

#[test]
fn the_builtin_generics() {
    assert!(matches!(
        kind(quote::quote!(Option<u8>)),
        TypeKind::Optional(_)
    ));
    assert!(matches!(kind(quote::quote!(Vec<u8>)), TypeKind::Vec(_)));
    assert!(matches!(
        kind(quote::quote!(Result<u8, Error>)),
        TypeKind::Fallible { .. }
    ));
}

/// A `Box<T>` **is a `Box<T>`** in the model. That no destination language can
/// tell it from `T` is true and is the adapters' to act on: `unwrapped` is where
/// that reading is taken, and it is taken on purpose, at a call site.
#[test]
fn a_box_is_a_box_until_a_consumer_unwraps_it() {
    let ty = lower(quote::quote!(Box<String>)).expect("in the language");
    let TypeKind::Boxed(inner) = &ty.kind else {
        panic!("a box");
    };
    assert!(matches!(inner.kind, TypeKind::String));
    assert_eq!(tokens(ty.origin.as_syn()), "Box < String >");
    // The reading a destination takes.
    assert!(matches!(ty.unwrapped().kind(), TypeKind::String));

    // And it composes: the nullable heap string of a `#[repr(C)]` struct field
    // is an optional string, spelled with its `Box`. `optional_inner` reads
    // through the wrapper, so the layer accessors answer as they always did.
    let ty = lower(quote::quote!(Option<Box<String>>)).expect("in the language");
    let inner = ty.optional_inner().expect("an option");
    assert!(matches!(inner.kind, TypeKind::Boxed(_)));
    assert!(matches!(inner.unwrapped().kind(), TypeKind::String));
    assert_eq!(tokens(inner.origin.as_syn()), "Box < String >");
}

/// The erasure, stated as something the model can be **asked**: what was taken
/// off, and what is left under it.
///
/// The invariant is not "the loop peels until it stops" — it is that
/// [`TypeRef::stripped_syntax`] is *the spelling whose own lowering yields the
/// kind [`TypeRef::unwrapped`] reaches*. That is what makes it a safe base for a
/// reconstruction, and it is why the peel must run to a **fixed point**:
/// `Box<Box<T>>` unwraps to `T`, so one strip leaves a `Box<T>` that does not
/// match.
#[test]
fn the_stripped_spelling_is_the_one_that_lowers_to_this_kind() {
    // The property, asserted as a property: strip, lower again, get the same
    // classification. A one-layer implementation fails the nested rows.
    for spelling in [
        quote::quote!(Box<Option<Sample>>),
        quote::quote!(Box<Box<String>>),
        quote::quote!(Box<Box<Box<Vec<u8>>>>),
        quote::quote!(Box<Cow<'_, [u8]>>),
        quote::quote!(Cow<'_, str>),
        // The control: nothing erased, so stripping is the identity and the
        // comparison cannot pass by both sides being trivially equal elsewhere.
        quote::quote!(Option<Sample>),
    ] {
        let ty = lower(spelling).expect("in the language");
        let stripped = ty.stripped_syntax();
        assert_eq!(
            format!("{:?}", kind(quote::quote!(#stripped))),
            format!("{:?}", ty.unwrapped().kind()),
            "`{}` strips to `{}`, which must classify identically",
            tokens(ty.origin.as_syn()),
            tokens(&stripped),
        );
    }

    // The wrappers themselves, outermost first — the list a rebuild applies in
    // reverse. `Box<Cow<..>>` is two DIFFERENT operations, which is why one
    // name and a count would not do.
    let wrappers =
        |t: proc_macro2::TokenStream| lower(t).expect("in the language").erased_wrappers();
    assert_eq!(wrappers(quote::quote!(Box<Box<String>>)), ["Box", "Box"]);
    assert_eq!(wrappers(quote::quote!(Box<Cow<'_, [u8]>>)), ["Box", "Cow"]);
    assert_eq!(wrappers(quote::quote!(Option<Sample>)), [] as [&str; 0]);

    // Unwrapped, the stripped spelling is the spelling — token-identical, not
    // merely equivalent, since it is what generated Rust would emit.
    let plain = lower(quote::quote!(Option<Sample>)).expect("in the language");
    assert_eq!(
        tokens(&plain.stripped_syntax()),
        tokens(plain.origin.as_syn())
    );
    assert_eq!(
        tokens(
            &lower(quote::quote!(Box<Box<Option<Sample>>>))
                .expect("in the language")
                .stripped_syntax()
        ),
        "Option < Sample >"
    );
}

/// **An erasure sits outside the layer it wraps**, so the question has to be
/// asked on the way *down* — at every layer — and never once at the top.
///
/// This is the pair that pins it, and each row is invisible to the other's
/// vantage point: `Box<&Vec<T>>` classifies as `Ref`, so a consumer that
/// interprets `kind` first is left holding a clean `Vec<T>` with the `Box`
/// unreachable; `&Box<Vec<T>>` puts the wrapper on the referent, where a
/// question asked of a `syn::Type::Reference` cannot see it.
#[test]
fn a_wrapper_is_found_only_at_the_layer_that_spells_it() {
    let outside = lower(quote::quote!(Box<&Vec<Sample>>)).expect("in the language");
    assert_eq!(outside.erased_wrappers(), ["Box"]);
    let referent = outside.borrow_target().expect("a borrow");
    assert_eq!(
        referent.erased_wrappers(),
        [] as [&str; 0],
        "peeling `kind` first reaches a clean `Vec<T>` — the `Box` is only \
         visible before the peel"
    );

    let inside = lower(quote::quote!(&Box<Vec<Sample>>)).expect("in the language");
    assert_eq!(
        inside.erased_wrappers(),
        [] as [&str; 0],
        "a reference cannot be peeled as a transparent wrapper"
    );
    assert_eq!(
        inside.borrow_target().expect("a borrow").erased_wrappers(),
        ["Box"],
        "the wrapper is on the referent, after the peel"
    );

    // Both classify the same shape, which is the whole reason neither check
    // alone is enough: the difference between them lives in a spelling, and the
    // classification is exactly the thing it is missing from.
    for ty in [&outside, &inside] {
        let TypeKind::Ref { mutable, inner, .. } = ty.unwrapped().kind() else {
            panic!("a borrow");
        };
        assert!(!mutable);
        let TypeKind::Vec(elem) = inner.unwrapped().kind() else {
            panic!("a run");
        };
        assert!(matches!(elem.kind, TypeKind::Named { .. }));
    }
}

/// A builtin must be spelled BARE **after normalization**: the real std path
/// reduces and classifies, while a path-qualified lookalike is a foreign type
/// that merely shares the name, and collapsing it would silently retype the
/// field.
/// The prelude: every name the language pre-declares reaches the same kind however
/// it is spelled. This is the drift guard — adding a builtin arm to `lower_path`
/// and forgetting its prelude entry fails here, which is exactly how `MaybeUninit`
/// slipped through and worked only when the source happened to `use` it.
#[test]
fn the_prelude_reaches_every_builtin_by_either_spelling() {
    use crate::flat::spelling::Normalization;

    // Each entry, bare against fully qualified. `MaybeUninit` needs a `&mut` to
    // mean anything, so it is checked separately below.
    for (path, name) in Normalization::PRELUDE {
        if *name == "MaybeUninit" {
            continue;
        }
        let bare: proc_macro2::TokenStream = match *name {
            "Result" => quote::quote!(Result<u8, Error>),
            "String" => quote::quote!(String),
            // `Cow` needs a lifetime and an unsized target to be valid Rust.
            "Cow" => quote::quote!(Cow<'_, [u8]>),
            _ => {
                let n = quote::format_ident!("{name}");
                quote::quote!(#n<u8>)
            }
        };
        let qualified: proc_macro2::TokenStream = {
            let p: syn::Path = syn::parse_str(path).expect("a prelude path");
            match *name {
                "Result" => quote::quote!(#p<u8, Error>),
                "String" => quote::quote!(#p),
                "Cow" => quote::quote!(#p<'_, [u8]>),
                _ => quote::quote!(#p<u8>),
            }
        };
        assert_eq!(
            format!("{:?}", kind(bare)),
            format!("{:?}", kind(qualified)),
            "`{name}` must classify the same as `{path}`"
        );
    }

    // `core` and `alloc` are re-exports of the same items, so either root works.
    assert!(matches!(
        kind(quote::quote!(core::option::Option<u8>)),
        TypeKind::Optional(_)
    ));
    assert!(matches!(
        kind(quote::quote!(alloc::string::String)),
        TypeKind::String
    ));

    // The bug: qualified `MaybeUninit` used to fall through to an unresolvable
    // nominal type, so an out-parameter worked only if the source `use`d it.
    let TypeKind::Ref { mutable, inner, .. } =
        kind(quote::quote!(&mut std::mem::MaybeUninit<Sample>))
    else {
        panic!("a borrow");
    };
    assert!(mutable);
    assert!(matches!(inner.kind, TypeKind::Uninit(_)));
}

/// A `#[prebindgen] pub type` is a **one-way road**: it brings a foreign type into
/// the flat API under a name, and that name is thereafter the only way to spell it.
///
/// It is a *declaration*, not an equivalence. Treating it as a reduction rule broke
/// the contract normalization actually has — choose among spellings of one type,
/// never change what a type is — because `type Bytes = Vec<u8>` would make `Vec<u8>`
/// an extern. So a qualified spelling stays refused even when an alias names exactly
/// that type.
#[test]
fn an_alias_is_a_declaration_not_an_equivalence() {
    let items: Vec<syn::Item> = vec![
        syn::parse_quote!(
            pub type Session = zenoh::Session;
        ),
        syn::parse_quote!(
            pub fn by_name(s: &Session) {}
        ),
        syn::parse_quote!(
            pub fn by_path(s: &zenoh::Session) {}
        ),
    ];
    let flat = Flat::builder()
        .items(items.into_iter().map(|i| (i, loc())))
        .build()
        .expect("a refusal is deferred, not fatal");

    // The declared name works.
    let f = flat.function("by_name").expect("declared");
    let inner = f.params[0].ty.borrow_target().expect("a borrow");
    let TypeKind::Named { id, .. } = &inner.kind else {
        panic!("a nominal type");
    };
    assert_eq!(id.name, "Session");

    // The path it aliases does NOT, and the diagnosis says to use the name.
    assert!(flat.function("by_path").is_none());
    let u = flat.unsupported().next().expect("one refusal");
    assert!(matches!(
        &*u.error,
        ItemError::UnresolvedType { name } if name == "zenoh::Session"
    ));
    assert!(
        u.error.to_string().contains("refer to that"),
        "the diagnosis must point at the declared name: {}",
        u.error
    );

    // And the declaration itself still records what it points at.
    let Type::Extern(e) = flat.declared_type("Session").expect("declared") else {
        panic!("an extern");
    };
    assert_eq!(e.target.as_deref(), Some("zenoh :: Session"));
}

/// An alias cannot retype anything, whatever its target's arguments — the property
/// that made key-shape bugs possible in the first place, now unreachable because an
/// alias is not an equivalence at all.
///
/// Covers the reported cases: a concrete generic target (`Vec<u8>`, which shadowed
/// the prelude), and a const-generic pair (`Wrap<4>` / `Wrap<8>`, which collided
/// because a key kept only type arguments).
#[test]
fn an_alias_never_retypes_a_spelling() {
    let flat = Flat::builder()
        .items(
            vec![
                syn::parse_quote!(
                    pub type Bytes = std::vec::Vec<u8>;
                ),
                syn::parse_quote!(
                    pub type Small = zenoh::Wrap<4>;
                ),
                syn::parse_quote!(
                    pub type Big = zenoh::Wrap<8>;
                ),
                syn::parse_quote!(
                    pub fn strings(xs: std::vec::Vec<String>) {}
                ),
                syn::parse_quote!(
                    pub fn bytes(xs: std::vec::Vec<u8>) {}
                ),
                syn::parse_quote!(
                    pub fn by_name(b: Bytes) {}
                ),
                syn::parse_quote!(
                    pub fn small(w: Small) {}
                ),
                syn::parse_quote!(
                    pub fn big(w: Big) {}
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("parses");

    let param = |name: &str| {
        flat.function(name)
            .unwrap_or_else(|| panic!("{name} survives"))
            .params[0]
            .ty
            .kind
            .clone()
    };

    // A prelude type keeps its grammar meaning at every instantiation, whatever an
    // unrelated alias happens to target.
    for f in ["strings", "bytes"] {
        assert!(
            matches!(param(f), TypeKind::Vec(_)),
            "`{f}`: the grammar's spelling stays canonical"
        );
    }

    // Each alias is usable by its own name, and they cannot collide: a bare path is
    // never reduced, so the name IS the identity.
    for (f, expected) in [("by_name", "Bytes"), ("small", "Small"), ("big", "Big")] {
        let TypeKind::Named { id, .. } = param(f) else {
            panic!("{f}: a nominal type");
        };
        assert_eq!(id.name, expected, "{f}");
        assert!(matches!(
            flat.declared_type(expected).expect(expected),
            Type::Extern(_)
        ));
    }
}

#[test]
fn a_qualified_builtin_is_a_named_type() {
    assert!(matches!(
        kind(quote::quote!(std::option::Option<u8>)),
        TypeKind::Optional(_)
    ));

    // Not an `Option` — and, being path-qualified, it cannot name a flat-API item
    // either, so it is refused as unresolved rather than silently retyped.
    let element = {
        let mut items = fixture_types();
        let n = items.len();
        items.push(syn::parse_quote!(
            pub struct S {
                pub f: foreign::Option<u8>,
            }
        ));
        parse(items).remove(n)
    };
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnresolvedType { name } if name == "foreign::Option"
    ));
}

#[test]
fn references() {
    assert!(matches!(
        kind(quote::quote!(&Sample)),
        TypeKind::Ref { mutable: false, .. }
    ));
    assert!(matches!(
        kind(quote::quote!(&mut Sample)),
        TypeKind::Ref { mutable: true, .. }
    ));
    // The lifetime is part of the type, so the model keeps it.
    let TypeKind::Ref { lifetime, .. } = kind(quote::quote!(&'a Sample)) else {
        panic!("a borrow");
    };
    assert_eq!(lifetime.expect("a lifetime").ident, "a");
}

/// `Vec<T>` and `[T]` are two Rust forms, so two kinds — and one *run of values*
/// to a consumer, which is what [`TypeRef::sequence_elem`] answers. That reading
/// is what the pipeline is built on (one `Shape::Iterable` covers both, and
/// jnigen rewrites a `&[T]` input into the `Vec<_>` pattern outright); the model
/// no longer has to lose the difference to provide it.
#[test]
fn a_run_of_values_is_read_through_either_spelling() {
    assert!(matches!(kind(quote::quote!(Vec<u8>)), TypeKind::Vec(_)));
    // Bare, as a callback argument is written: `impl Fn([T])`.
    assert!(matches!(kind(quote::quote!([u8])), TypeKind::Slice(_)));
    let TypeKind::Ref { inner, .. } = kind(quote::quote!(&[u8])) else {
        panic!("a reference");
    };
    assert!(matches!(inner.kind, TypeKind::Slice(_)));

    // One reading over both, plus a wrapper over either.
    for spelling in [
        quote::quote!(Vec<u8>),
        quote::quote!([u8]),
        quote::quote!(Box<Vec<u8>>),
        quote::quote!(Cow<'_, [u8]>),
    ] {
        let ty = lower(spelling).expect("in the language");
        assert!(
            matches!(
                ty.sequence_elem().expect("a run").kind(),
                TypeKind::Scalar(ScalarKind::U8)
            ),
            "`{}` is a run of `u8`",
            tokens(ty.origin.as_syn())
        );
    }
}

/// A `Cow<'_, T>` keeps its own kind, its lifetime included, and reads as the
/// `T` it borrows — the same treatment `Box<T>` gets, taken at the consumer
/// rather than during lowering.
///
/// Both adapters act on that reading — cbindgen lowers `Cow<'_, [T]>` "just like
/// `Vec<T>` outputs", and jnigen's converter is `byte_array_from_slice(&v)`, which
/// works by deref and is identical to the `Vec<u8>` one — and now both can also
/// see the `Cow` they are seeing through.
#[test]
fn a_cow_reads_as_what_it_borrows() {
    // The reading the whole treatment rests on: indistinguishable from the owned
    // spelling of the same thing, once a consumer says it does not care.
    let cow = lower(quote::quote!(Cow<'_, [u8]>)).expect("in the language");
    assert_eq!(
        format!("{:?}", cow.unwrapped().kind()),
        format!("{:?}", kind(quote::quote!([u8]))),
        "a byte Cow reads exactly as the byte slice it borrows"
    );
    let TypeKind::Cow { lifetime, .. } = &cow.kind else {
        panic!("a cow");
    };
    assert_eq!(lifetime.ident, "_");
    assert!(matches!(
        lower(quote::quote!(Cow<'_, str>))
            .expect("in the language")
            .unwrapped()
            .kind(),
        TypeKind::Str
    ));

    // The `Cow` survives where codegen reads it: a generated signature must spell
    // `Cow<'_, [u8]>`, which is not interchangeable with `Vec<u8>` in Rust.
    assert_eq!(tokens(cow.origin.as_syn()), "Cow < '_ , [u8] >");

    // Transparent for any target, as `Box` is: whether it can actually cross is the
    // adapter's call, and both already restrict which elements they accept.
    let elem = lower(quote::quote!(Cow<'_, [Sample]>))
        .expect("in the language")
        .sequence_elem()
        .expect("a run")
        .clone();
    assert!(matches!(elem.kind, TypeKind::Named { .. }));

    // A lifetime argument is expected on `Cow` alone. On any other builtin it is
    // still not a shape the language has, so the exception is exactly one name wide:
    // `Vec<'a, u8>` is a nominal `Vec` nobody declared, and the item is refused.
    let element = {
        let mut items = fixture_types();
        let n = items.len();
        items.push(syn::parse_quote!(
            pub struct S {
                pub f: Vec<'a, u8>,
            }
        ));
        parse(items).remove(n)
    };
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnresolvedType { name } if name == "Vec"
    ));
}

/// `Cow` is the one builtin whose signature carries a lifetime, so it is the one
/// whose **whole argument list** is checked rather than its type-argument count.
///
/// Counting types alone accepts three spellings that are not `Cow`s: the review
/// case `Cow<u8, 'a>`, a second lifetime, and no lifetime at all. Each has
/// exactly one type argument, so each passed — and then reconstructed as
/// `Cow<'a, u8>`, quietly breaking the property
/// [`syntax_is_recoverable_from_kind`] asserts. A model that keeps only the
/// first lifetime cannot spell any of them back, which is the reason to refuse
/// them rather than the consequence of doing so.
#[test]
fn a_cow_takes_a_lifetime_and_a_type_in_that_order() {
    // The accepted shape, either way the lifetime is written.
    for spelling in [quote::quote!(Cow<'_, [u8]>), quote::quote!(Cow<'a, str>)] {
        let ty = lower(spelling).expect("in the language");
        assert!(matches!(ty.kind, TypeKind::Cow { .. }));
        // And it spells back, which is what the refusals below protect.
        assert_eq!(tokens(&ty.kind().to_syn()), tokens(ty.as_syn()));
    }

    // Everything else is refused by shape, and named as such.
    for spelling in [
        // No lifetime: `Cow<T>` is not Rust, so no source crate compiles it.
        quote::quote!(Cow<u8>),
        // The review case: the arguments are there, in the wrong order.
        quote::quote!(Cow<u8, 'a>),
        // Two lifetimes, where `Cow` takes one.
        quote::quote!(Cow<'a, 'b, u8>),
        // Two types.
        quote::quote!(Cow<'a, u8, u8>),
    ] {
        let rendered = spelling.to_string();
        assert_eq!(
            reason(spelling),
            UnsupportedTypeReason::WrongGenericArguments {
                expected: "Cow<'a, T>"
            },
            "`{rendered}` is not a `Cow`"
        );
    }
}

/// The signature that motivated this: zenoh-flat's `zbytes_to_bytes`. It was refused
/// under the closed API because a lifetime argument sent `Cow` to an undeclared
/// nominal type.
#[test]
fn a_cow_returning_accessor_resolves() {
    let flat = Flat::builder()
        .items(
            vec![
                syn::parse_quote!(
                    pub type ZBytes = zenoh::bytes::ZBytes;
                ),
                syn::parse_quote!(
                    pub fn zbytes_to_bytes(z: &ZBytes) -> Cow<'_, [u8]> {}
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("parses");

    assert_eq!(flat.unsupported().count(), 0, "no longer refused");
    let f = flat.function("zbytes_to_bytes").expect("survives");
    assert!(matches!(f.ret.kind, TypeKind::Cow { .. }));
    assert!(f.ret.sequence_elem().is_some(), "and it reads as a run");
    // And the return still spells its `Cow`, so an adapter can emit the signature.
    assert_eq!(tokens(f.ret.origin.as_syn()), "Cow < '_ , [u8] >");
}

/// A raw pointer is not in the language. A `#[prebindgen]` crate is idiomatic
/// Rust and the adapter owns the lowering to pointers — no adapter has a
/// selection arm for one, so accepting it would only defer the failure to a
/// late "unresolved type".
#[test]
fn a_raw_pointer_is_not_in_the_language() {
    assert_eq!(
        reason(quote::quote!(*const u8)),
        UnsupportedTypeReason::UnsupportedForm
    );
    assert_eq!(
        reason(quote::quote!(*mut Sample)),
        UnsupportedTypeReason::UnsupportedForm
    );
}

/// Generic arguments are accepted and not modelled — a reference is a *name*, and
/// the spelling keeps the rest.
///
/// Nothing could read retained arguments: a surviving reference resolves to a
/// declared type, and no declaration takes type parameters. They are still lowered,
/// so a bad type inside one is diagnosed.
#[test]
fn generic_arguments_are_spelling_only() {
    let ty = lower(quote::quote!(Foo<'a, u8>)).expect("in the language");
    let TypeKind::Named { id, .. } = &ty.kind else {
        panic!("a named type");
    };
    assert_eq!(id.name, "Foo");
    assert_eq!(tokens(ty.origin.as_syn()), "Foo < 'a , u8 >");

    // Lowered, so still checked: a tuple inside a generic argument is refused.
    assert_eq!(
        reason(quote::quote!(Foo<(u8, u8)>)),
        UnsupportedTypeReason::UnsupportedTuple
    );
}

#[test]
fn the_callback_form() {
    let TypeKind::Callback { args } =
        kind(quote::quote!(impl Fn(&Sample, u32) + Send + Sync + 'static))
    else {
        panic!("a callback");
    };
    assert_eq!(args.len(), 2);
}

/// A callback returns nothing, and that is **checked**. `TypeKind::Callback` has
/// no slot for a return, so accepting `impl Fn() -> u8` would drop a fact a
/// destination language needs — silently, which is worse than the refusal.
#[test]
fn a_callback_must_return_nothing() {
    // Written out, `-> ()` is the same callback.
    let TypeKind::Callback { args } =
        kind(quote::quote!(impl Fn(u32) -> () + Send + Sync + 'static))
    else {
        panic!("a callback");
    };
    assert_eq!(args.len(), 1);

    // Anything else is not the accepted `impl Trait` form.
    for spelling in [
        quote::quote!(impl Fn() -> u8 + Send + Sync + 'static),
        quote::quote!(impl Fn(u32) -> Sample + Send + Sync + 'static),
        quote::quote!(impl Fn() -> Option<u8> + Send + Sync + 'static),
    ] {
        assert_eq!(
            reason(spelling),
            UnsupportedTypeReason::DisallowedImplTrait,
            "a returning callback is refused, not silently truncated"
        );
    }
}

#[test]
fn types_outside_the_language() {
    assert_eq!(
        reason(quote::quote!((u8, u8))),
        UnsupportedTypeReason::UnsupportedTuple
    );
    assert_eq!(
        reason(quote::quote!(<Holder as Trait>::Assoc)),
        UnsupportedTypeReason::AssociatedType
    );
    assert_eq!(
        reason(quote::quote!(Option<u8, u16>)),
        UnsupportedTypeReason::WrongGenericArity { expected: 1 }
    );
    assert_eq!(
        reason(quote::quote!(Result<u8>)),
        UnsupportedTypeReason::WrongGenericArity { expected: 2 }
    );
    assert_eq!(
        reason(quote::quote!(impl Iterator<Item = u8>)),
        UnsupportedTypeReason::DisallowedImplTrait
    );
    assert_eq!(
        reason(quote::quote!(dyn Fn(u8))),
        UnsupportedTypeReason::UnsupportedForm
    );
    assert_eq!(
        reason(quote::quote!(!)),
        UnsupportedTypeReason::UnsupportedForm
    );
}

// ── Array extents ──────────────────────────────────────────────────────

fn extent_reason(ty: proc_macro2::TokenStream) -> ArrayLenReason {
    match reason(ty) {
        UnsupportedTypeReason::BadArrayExtent(e) => e.reason,
        other => panic!("expected an extent diagnosis, got {other:?}"),
    }
}

#[test]
fn extents_outside_the_subgrammar() {
    assert_eq!(
        extent_reason(quote::quote!([u8; TAG_LEN + 1])),
        ArrayLenReason::NotLiteralOrName
    );
    assert_eq!(
        extent_reason(quote::quote!([u8; crate::limits::MAX])),
        ArrayLenReason::NotABareName
    );
    assert_eq!(
        extent_reason(quote::quote!([u8; UNMARKED])),
        ArrayLenReason::NotAMarkedConst
    );
    // Expression forms that BIND a local, which is the dangerous family: a length
    // is qualified against its source module, so a local shadowing a marked item
    // would be rewritten into it. Scope tracking is the general answer; none of
    // these has a place in a boundary type, so the whole family is refused.
    // (Moved here from the jnigen suite: the subgrammar is the frontend's.)
    assert_eq!(
        extent_reason(quote::quote!(
            [u8; const {
                let n = 3;
                n
            }]
        )),
        ArrayLenReason::NotLiteralOrName
    );
    assert_eq!(
        extent_reason(quote::quote!(
            [u8; match 3 {
                n => n,
            }]
        )),
        ArrayLenReason::NotLiteralOrName
    );
    assert_eq!(
        extent_reason(quote::quote!([u8; if let n = 3 { n } else { 0 }])),
        ArrayLenReason::NotLiteralOrName
    );
    // A CALL is not a name either, however const the callee.
    assert_eq!(
        extent_reason(quote::quote!([u8; array_len()])),
        ArrayLenReason::NotLiteralOrName
    );
    assert_eq!(
        extent_reason(quote::quote!([u8; 'c'])),
        ArrayLenReason::NotAnIntegerLiteral
    );
}

/// A const may be declared after the item that uses it: the const index is
/// built before anything is lowered.
#[test]
fn an_extent_may_name_a_const_declared_later() {
    let elements = parse(vec![
        syn::parse_quote!(
            pub struct Marker {
                pub tag: [u8; TAG_LEN],
            }
        ),
        tag_len_const(),
    ]);
    assert_eq!(
        as_struct(&elements[0]).fields[0]
            .ty
            .array_extent()
            .expect("an extent")
            .value,
        4
    );
}

/// An extent carries three facts for three questions, and they come apart. No
/// blanket equality could serve all three, which is why the type provides none:
/// a consumer projects the one it needs.
#[test]
fn the_three_extent_projections_are_independent() {
    // `A` and `TAG_LEN` are both 4; `0x04` and `4` are the same literal value
    // spelled differently.
    let elements = parse(vec![
        syn::parse_quote!(
            pub struct Marker {
                pub by_const: [u8; TAG_LEN],
                pub by_other_const: [u8; ALSO_FOUR],
                pub by_literal: [u8; 4],
                pub by_hex_literal: [u8; 0x04],
                pub longer: [u8; 8],
            }
        ),
        tag_len_const(),
        syn::parse_quote!(
            pub const ALSO_FOUR: usize = 4;
        ),
    ]);
    let fields = &as_struct(&elements[0]).fields;
    let at = |i: usize| fields[i].ty.array_extent().expect("an extent");
    let (by_const, by_other_const, by_literal, by_hex, longer) =
        (at(0), at(1), at(2), at(3), at(4));

    // Type identity is the evaluated value: all four fours are ONE type and one
    // converter, however they were addressed or spelled.
    for e in [by_const, by_other_const, by_literal, by_hex] {
        assert_eq!(e.value, 4);
    }
    assert_ne!(longer.value, by_literal.value);

    // Declaration spelling is per occurrence, and distinguishes cases the value
    // cannot: `4` is not `0x04`, and neither is `TAG_LEN`.
    assert_eq!(tokens(by_literal.origin.as_syn()), "4");
    assert_eq!(tokens(by_hex.origin.as_syn()), "0x04");
    assert_eq!(tokens(by_const.origin.as_syn()), "TAG_LEN");

    // Header dependency is the named const, and distinguishes cases the
    // spelling groups together and the value does not see at all.
    assert_eq!(
        by_const.const_id().expect("a const dependency").name,
        "TAG_LEN"
    );
    assert_eq!(
        by_other_const.const_id().expect("a const dependency").name,
        "ALSO_FOUR"
    );
    assert!(by_literal.const_id().is_none());
    assert!(by_hex.const_id().is_none());

    // The three really are orthogonal: each pair below agrees on one projection
    // and differs on another.
    assert!(by_const.value == by_literal.value && by_const.const_id() != by_literal.const_id());
    assert!(
        by_literal.value == by_hex.value
            && tokens(by_literal.origin.as_syn()) != tokens(by_hex.origin.as_syn())
    );
    assert!(
        by_const.const_id() != by_other_const.const_id() && by_const.value == by_other_const.value
    );
}

/// A const whose own initializer is not a literal cannot be a length —
/// `build.rs` cannot evaluate it — but it is still a perfectly good const.
#[test]
fn a_computed_const_is_indexed_but_is_not_a_length() {
    let elements = parse(vec![
        syn::parse_quote!(
            pub const COMPUTED: usize = 2 * 2;
        ),
        syn::parse_quote!(
            pub struct Marker {
                pub tag: [u8; COMPUTED],
            }
        ),
    ]);
    assert_eq!(as_const(&elements[0]).name, "COMPUTED");
    match as_unsupported(&elements[1]) {
        ItemError::FieldType {
            source:
                UnsupportedType {
                    reason: UnsupportedTypeReason::BadArrayExtent(e),
                    ..
                },
            ..
        } => assert_eq!(e.reason, ArrayLenReason::ConstIsNotALiteral),
        other => panic!("expected an extent diagnosis, got {other}"),
    }
}

// ── Item kinds ─────────────────────────────────────────────────────────

/// A struct is a product of fields, or opaque. A tuple struct is the opaque
/// one: usable as a handle, its fields deliberately not lowered, because no
/// adapter has ever crossed them and lowering would turn types that are ignored
/// today into errors. A unit struct is the empty product, not a handle — the
/// delimiters are spelling, and `spell` reads them off the syntax.
#[test]
fn struct_shapes() {
    let named = parse_one(syn::parse_quote!(
        pub struct A {
            pub x: u8,
        }
    ));
    assert_eq!(as_struct(&named).fields.len(), 1);

    // A tuple struct is a handle, so its fields are never lowered — which is why
    // a field type outside the grammar is not an error here.
    let tuple = parse_one(syn::parse_quote!(
        pub struct B(SomethingUnexpressible<'_, dyn Trait>);
    ));
    assert_eq!(as_extern(&tuple).name, "B");

    let unit = parse_one(syn::parse_quote!(
        pub struct C;
    ));
    assert!(
        as_struct(&unit).fields.is_empty(),
        "an empty product, not a handle"
    );
}

/// A variant's index is its declaration order and is never its discriminant:
/// one is where the source *put* it, the other is the value Rust *assigns* it.
/// The two numberings are independent, and this is the pair that proves it.
#[test]
fn tags_are_declaration_order() {
    let element = parse_one(syn::parse_quote!(
        pub enum E {
            A = 5,
            B = 9,
        }
    ));
    let e = as_enum(&element);
    assert_eq!(
        e.values.iter().map(|v| v.index).collect::<Vec<_>>(),
        vec![0, 1]
    );
    assert_eq!(
        e.discriminant_values()
            .expect("literals")
            .into_iter()
            .map(|(_, v)| v)
            .collect::<Vec<_>>(),
        vec![5, 9]
    );
}

/// The two enum shapes are two entities, and the classification is decided once:
/// any alternative with a field makes it a sum.
///
/// They are not one model with a dead field each. A sum has no discriminant slot,
/// because its alternatives are identified by position — the mirror an adapter
/// builds numbers its own arms — and a fieldless enum's identity is exactly the
/// value Rust assigns.
#[test]
fn the_two_enum_shapes_are_two_entities() {
    let fieldless = parse_one(syn::parse_quote!(
        pub enum E {
            A,
            B = 7,
        }
    ));
    let e = as_enum(&fieldless);
    assert_eq!(e.values.len(), 2);
    assert_eq!(e.values[1].discriminant, Some(7));

    // Empty delimiters are still fieldless — the group question, not the syntax
    // one — so this is an enum, and `spell` keeps the delimiters.
    let empty_groups = parse_one(syn::parse_quote!(
        pub enum E {
            A,
            B(),
            C {},
        }
    ));
    assert_eq!(as_enum(&empty_groups).values.len(), 3);

    // One field anywhere makes it a sum.
    let sum = parse_one(syn::parse_quote!(
        pub enum E {
            A,
            B(u32),
            C { x: u8 },
        }
    ));
    let v = as_variant(&sum);
    assert_eq!(v.alternatives.len(), 3);
    assert!(v.alternatives[0].is_empty(), "a sum may mix");
    assert_eq!(v.alternatives[1].fields.len(), 1);
    assert_eq!(
        v.alternatives.iter().map(|a| a.index).collect::<Vec<_>>(),
        vec![0, 1, 2]
    );

    // No alternatives at all: nothing carries a payload, so it is the degenerate
    // enum rather than an empty sum.
    let empty = parse_one(syn::parse_quote!(
        pub enum E {}
    ));
    assert!(as_enum(&empty).values.is_empty());
}

/// A field is addressed by name or by position, and the model says which
/// without anyone reading `syn::Fields`.
#[test]
fn field_members_follow_the_addressing() {
    let element = parse_one(syn::parse_quote!(
        pub enum Reading {
            Exact(i64, i64),
            Range { low: i64 },
        }
    ));
    let v = as_variant(&element);
    assert!(matches!(
        v.alternatives[0].fields[1].member(),
        syn::Member::Unnamed(i) if i.index == 1
    ));
    assert!(matches!(
        v.alternatives[1].fields[0].member(),
        syn::Member::Named(id) if id == "low"
    ));
}

#[test]
fn consts_carry_their_type_and_value() {
    let element = parse_one(tag_len_const());
    let c = as_const(&element);
    assert_eq!(c.name, "TAG_LEN");
    assert!(matches!(c.ty.kind, TypeKind::Scalar(ScalarKind::Usize)));
    assert_eq!(tokens(&c.origin.as_syn().expr), "4");
}

/// An unnamed const is a `Guard`, not a `Constant`: nothing can name it, so it
/// is not part of the API. Several coexist because none has an address to
/// collide on — which is what lets a binding ingest two source crates, each
/// injecting its own feature check.
#[test]
fn an_unnamed_const_is_a_guard() {
    let elements = parse(vec![
        syn::parse_quote!(
            const _: () = ();
        ),
        syn::parse_quote!(
            const _: () = ();
        ),
    ]);
    assert!(elements.iter().all(|e| matches!(e, Element::Guard(_))));
    assert!(elements.iter().all(|e| e.name().is_none()));
    // A guard writes no type slot, so a consumer walking the API never reaches
    // one — the reason it carries no `TypeRef`.
    assert!(!elements.iter().any(|e| matches!(e, Element::Constant(_))));
}

/// An item kind the language does not model is diagnosed, not carried: a
/// `#[prebindgen]` crate marks what crosses the boundary and leaves the code
/// around it to the consumer. The proc-macro refuses to mark a `use` at all, and
/// a type alias now *declares* an opaque handle — so a `union` is the only kind
/// left that reaches here.
#[test]
fn an_unmodelled_item_kind_is_diagnosed() {
    let element = parse_one(syn::parse_quote!(
        pub union U {
            a: u8,
        }
    ));
    assert!(element.name().is_some(), "keeps its address");
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnsupportedItemKind { kind } if *kind == "a union"
    ));
}

/// A marked type alias DECLARES an opaque handle — the way a foreign or
/// crate-private type gets a name in the flat API. That is what lets references
/// be required to resolve, so it is the keystone of the whole model.
#[test]
fn a_marked_alias_declares_an_extern() {
    let element = parse_one(syn::parse_quote!(
        pub type Session = zenoh::Session;
    ));
    let e = as_extern(&element);
    assert_eq!(e.name, "Session");
    // What it points at is a modelled fact, so an adapter can recognise a target
    // without taking the syntax apart. Not classified: a std type may hide behind a
    // foreign alias, as `Error = zenoh::Error` does.
    assert_eq!(e.target.as_deref(), Some("zenoh :: Session"));
    // The whole item survives, so a consumer can still read what it aliased.
    assert_eq!(
        tokens(e.origin.as_syn()),
        "pub type Session = zenoh :: Session ;"
    );

    // A std target is recorded the same way — nothing here decides it is special.
    let element = parse_one(syn::parse_quote!(
        pub type Duration = std::time::Duration;
    ));
    assert_eq!(
        as_extern(&element).target.as_deref(),
        Some("std :: time :: Duration")
    );

    // A tuple struct points at nothing: it IS the definition.
    let element = parse_one(syn::parse_quote!(
        pub struct Handle(Whatever);
    ));
    let e = as_extern(&element);
    assert_eq!(e.name, "Handle");
    assert_eq!(e.target, None);

    // And it satisfies a reference, which is the point.
    let mut items = fixture_types();
    items.push(syn::parse_quote!(
        pub type Session = zenoh::Session;
    ));
    let n = items.len();
    items.push(syn::parse_quote!(
        pub fn session_close(s: Session) {}
    ));
    let elements = parse(items);
    assert!(matches!(elements[n], Element::Function(_)));
}

// ── Functions ──────────────────────────────────────────────────────────

#[test]
fn function_signatures() {
    let element = parse_one(syn::parse_quote!(
        pub fn put(key: &KeyExpr, payload: Vec<u8>) -> Result<(), Error> {
            unimplemented!()
        }
    ));
    let f = as_fn(&element);
    assert_eq!(f.name, "put");
    assert_eq!(
        f.params
            .iter()
            .map(|p| p.name.to_string())
            .collect::<Vec<_>>(),
        vec!["key", "payload"]
    );
    assert!(matches!(f.ret.kind, TypeKind::Fallible { .. }));
}

/// An elided return and a written `-> ()` are the same function. Nothing in the
/// pipeline distinguishes them — every consumer normalizes one to the other on
/// the spot — so the model does it once instead.
#[test]
fn an_elided_return_is_the_unit() {
    for sig in [
        quote::quote!(
            pub fn f() {}
        ),
        quote::quote!(
            pub fn f() -> () {}
        ),
    ] {
        let element = parse_one(syn::parse_quote!(#sig));
        assert!(matches!(as_fn(&element).ret.kind, TypeKind::Unit));
    }
}

/// Function shapes `Function` has no slot for, and would therefore drop in
/// silence.
///
/// `async` is the one that bites: the future would be dropped and the export
/// would be a function whose body never runs.
#[test]
fn function_shapes_outside_the_language() {
    let element = parse_one(syn::parse_quote!(
        pub async fn ping() {}
    ));
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnsupportedAsync
    ));
    // Named, so nothing else can claim the address while it sits inert.
    assert_eq!(element.name().expect("named"), "ping");

    let element = parse_one(syn::parse_quote!(
        pub unsafe extern "C" fn log(fmt: u8, ...) {}
    ));
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnsupportedVariadic
    ));
}

/// A generic binder is refused on every item kind. The elements have no binder,
/// so a `T` would lower as an ordinary nominal reference into the flat namespace
/// — indistinguishable from a real item named `T`.
#[test]
fn a_generic_parameter_is_outside_the_language() {
    let cases: Vec<(syn::Item, &str, &str)> = vec![
        (
            syn::parse_quote!(
                pub struct Wrapper<T> {
                    pub value: T,
                }
            ),
            "T",
            "a type parameter",
        ),
        (
            syn::parse_quote!(
                pub fn first<T>(items: Vec<T>) -> T {
                    unimplemented!()
                }
            ),
            "T",
            "a type parameter",
        ),
        (
            syn::parse_quote!(
                pub enum Either<L, R> {
                    Left(L),
                    Right(R),
                }
            ),
            "L",
            "a type parameter",
        ),
        (
            // Unused, and still a binder.
            syn::parse_quote!(
                pub struct Padded<const N: usize> {
                    pub value: u8,
                }
            ),
            "N",
            "a const generic parameter",
        ),
    ];
    for (item, expected_param, expected_kind) in cases {
        let element = parse_one(item);
        let ItemError::UnsupportedGenericParam { param, kind } = as_unsupported(&element) else {
            panic!(
                "expected a generic-parameter diagnosis, got {}",
                describe(&element)
            );
        };
        assert_eq!(param, expected_param);
        assert_eq!(*kind, expected_kind);
    }
}

/// A **lifetime** binder is not a generic parameter for this purpose: lifetimes
/// say nothing a destination language can act on, and the spelling that needs
/// them is already in the syntax — the same call made for a lifetime argument.
#[test]
fn a_lifetime_binder_is_accepted() {
    let element = parse_one(syn::parse_quote!(
        pub struct Borrowed<'a> {
            pub key: &'a str,
        }
    ));
    let s = as_struct(&element);
    assert_eq!(s.fields.len(), 1);
    assert_eq!(tokens(&s.fields[0].ty.origin.spell()), "& 'a str");
}

/// `impl Trait` in argument position is an anonymous type parameter in Rust, but
/// `syn` does not desugar it into the binder list — so the callback form, which
/// every callback-taking source function uses, is untouched by the generic
/// refusal. This is the test that says so.
#[test]
fn a_callback_parameter_is_not_a_generic_binder() {
    let element = parse_one(syn::parse_quote!(
        pub fn for_each(f: impl Fn(u64) + Send + Sync + 'static) {}
    ));
    let func = as_fn(&element);
    assert!(matches!(func.params[0].ty.kind, TypeKind::Callback { .. }));
}

#[test]
fn a_receiver_is_not_a_free_function() {
    let element = parse_one(syn::parse_quote!(
        pub fn get(self) -> u8 {
            unimplemented!()
        }
    ));
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnsupportedReceiver
    ));
}

#[test]
fn a_parameter_must_be_bound_to_one_name() {
    let element = parse_one(syn::parse_quote!(
        pub fn f((a, b): (u8, u8)) {}
    ));
    assert!(matches!(
        as_unsupported(&element),
        ItemError::UnsupportedParamPattern { .. }
    ));
}

/// The diagnosis names the component, not just the item — the whole point of
/// lowering each part separately.
#[test]
fn a_diagnosis_names_the_component() {
    let element = parse_one(syn::parse_quote!(
        pub fn f(ok: u8, bad: (u8, u8)) {}
    ));
    match as_unsupported(&element) {
        ItemError::ParamType { param, source } => {
            assert_eq!(param, "bad");
            assert_eq!(source.reason, UnsupportedTypeReason::UnsupportedTuple);
        }
        other => panic!("expected a parameter diagnosis, got {other}"),
    }

    let element = parse_one(syn::parse_quote!(
        pub fn f() -> (u8, u8) {
            unimplemented!()
        }
    ));
    assert!(matches!(
        as_unsupported(&element),
        ItemError::ReturnType { .. }
    ));

    let element = parse_one(syn::parse_quote!(
        pub enum E {
            V { bad: (u8, u8) },
        }
    ));
    match as_unsupported(&element) {
        ItemError::VariantFieldType { variant, field, .. } => {
            assert_eq!(variant, "V");
            assert_eq!(field, "bad");
        }
        other => panic!("expected a variant diagnosis, got {other}"),
    }
}

/// An item the language cannot express is inert, not fatal: a source crate may
/// mark items no binding uses, and those have never had to be expressible. It
/// keeps its name (so nothing else can claim it) and its syntax.
#[test]
fn an_unsupported_item_is_indexed_not_refused() {
    let elements = parse(vec![
        syn::parse_quote!(
            pub fn unusable(pair: (u8, u8)) {}
        ),
        syn::parse_quote!(
            pub fn usable(x: u8) {}
        ),
    ]);
    assert_eq!(elements[0].name().expect("named"), "unusable");
    assert!(matches!(elements[0], Element::Unsupported(_)));
    assert!(matches!(elements[1], Element::Function(_)));
}

// ── Resolution and access ──────────────────────────────────────────────

/// The model answers by name, which is what every later stage needs. An
/// unsupported item is still reachable — it holds its slot in the namespace —
/// but it is not a type.
#[test]
fn the_model_is_addressed_by_name() {
    let flat = Flat::builder()
        .items(
            vec![
                syn::parse_quote!(
                    pub type Session = zenoh::Session;
                ),
                syn::parse_quote!(
                    pub const LIMIT: usize = 4;
                ),
                syn::parse_quote!(
                    pub fn session_close(s: Session) {}
                ),
                syn::parse_quote!(
                    pub union U {
                        a: u8,
                    }
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("parses");

    assert!(flat.function("session_close").is_some());
    assert!(flat.declared_type("Session").is_some());
    assert!(flat.constant("LIMIT").is_some());
    assert_eq!(flat.functions().count(), 1);
    assert_eq!(flat.types().count(), 1);
    assert_eq!(flat.constants().count(), 1);

    // Reachable, but not a type — it holds its name so nothing else can claim it.
    assert!(flat.element("U").is_some());
    assert!(flat.declared_type("U").is_none());
    assert_eq!(flat.unsupported().count(), 1);

    // A name nobody declared is simply absent.
    assert!(flat.element("nope").is_none());
}

/// A reference leads to the declaration it names. Resolving here is the point of
/// #211: a dangling name used to surface much later, as an unresolved converter
/// from whichever adapter looked first.
#[test]
fn a_reference_resolves_to_its_declaration() {
    let flat = Flat::builder()
        .items(
            vec![
                syn::parse_quote!(
                    pub type Session = zenoh::Session;
                ),
                syn::parse_quote!(
                    pub fn session_close(s: Session) {}
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("parses");

    let f = flat.function("session_close").expect("declared");
    let TypeKind::Named { id, .. } = &f.params[0].ty.kind else {
        panic!("a nominal type");
    };
    let target = flat.resolve(id).expect("resolves");
    assert!(matches!(target, Type::Extern(_)));
    assert_eq!(target.name(), "Session");
}

/// Resolution runs once every declaration is in hand, so a reference may point
/// forward, or into another source entirely — which is how a helper crate names
/// types it cannot mark itself.
#[test]
fn resolution_spans_feeders_and_declaration_order() {
    // Forward reference within one feeder.
    let flat = Flat::builder()
        .items(
            vec![
                syn::parse_quote!(
                    pub fn session_close(s: Session) {}
                ),
                syn::parse_quote!(
                    pub type Session = zenoh::Session;
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("a forward reference resolves");
    assert!(flat.function("session_close").is_some());

    // And across feeders: the declaration arrives in the second stream.
    let flat = Flat::builder()
        .items(vec![(
            syn::parse_quote!(
                pub fn session_close(s: Session) {}
            ),
            loc(),
        )])
        .items(vec![(
            syn::parse_quote!(
                pub type Session = zenoh::Session;
            ),
            loc(),
        )])
        .build()
        .expect("a cross-feeder reference resolves");
    assert!(flat.function("session_close").is_some());
}

/// A name the flat API does not declare makes the *referencing* item
/// unsupported, inert until an adapter declares it — the same deferral every
/// other refusal uses, so an item no binding touches stays harmless.
#[test]
fn an_undeclared_reference_refuses_the_referencing_item() {
    let flat = Flat::builder()
        .items(vec![(
            syn::parse_quote!(
                pub fn session_close(s: Session) {}
            ),
            loc(),
        )])
        .build()
        .expect("a refusal is deferred, not fatal");

    assert!(flat.function("session_close").is_none());
    let u = flat.unsupported().next().expect("one refusal");
    assert!(matches!(
        &*u.error,
        ItemError::UnresolvedType { name } if name == "Session"
    ));
    // It still holds its name, so nothing else can claim it.
    assert_eq!(u.name.as_ref().expect("named"), "session_close");

    // Reachable through every layer a reference can nest in.
    for ty in [
        quote::quote!(Option<Session>),
        quote::quote!(Vec<Session>),
        quote::quote!(&Session),
        quote::quote!(Result<Session, Error>),
        quote::quote!(impl Fn(Session) + Send + Sync + 'static),
        quote::quote!([Session; 4]),
        // NOT `Wrapper<Session>`: a declared type takes no type parameters, so a
        // source writing that would not compile. Generic arguments are lowered and
        // discarded — `generic_arguments_are_spelling_only` covers that they are
        // still checked.
    ] {
        let flat = Flat::builder()
            .items(vec![
                (opaque("Error"), loc()),
                (
                    syn::parse_quote!(
                        pub fn f(s: #ty) {}
                    ),
                    loc(),
                ),
            ])
            .build()
            .expect("deferred");
        assert_eq!(
            flat.unsupported().count(),
            1,
            "`Session` must be found inside {}",
            ty
        );
    }
}

/// An out-parameter is `&mut MaybeUninit<T>` — the two forms the source wrote,
/// each with its own kind. What it *means* (the caller supplies the slot, the
/// callee fills it) is a reading, and the model provides the two that consumers
/// need: [`TypeRef::borrow_target`] sees past the slot to the `T` that actually
/// crosses, and [`TypeRef::is_exclusive_borrow`] is false for it, because a
/// callee may not read the slot first.
///
/// Uninitialized storage anywhere else promises nothing a destination language
/// can use, so it is refused — an acceptance rule about a **position**, which is
/// the one thing a variant set cannot state.
#[test]
fn an_out_parameter_is_a_mutable_borrow_of_a_slot() {
    let out = lower(quote::quote!(&mut MaybeUninit<Sample>)).expect("in the language");
    let TypeKind::Ref { mutable, inner, .. } = &out.kind else {
        panic!("a borrow");
    };
    assert!(mutable);
    let TypeKind::Uninit(slot) = &inner.kind else {
        panic!("the slot the source wrote");
    };
    let TypeKind::Named { id, .. } = &slot.kind else {
        panic!("the value's own type");
    };
    assert_eq!(id.name, "Sample");

    // The readings: the target is the value, and it is not an exclusive borrow.
    let target = out.borrow_target().expect("a borrow");
    assert!(matches!(&target.kind, TypeKind::Named { id, .. } if id.name == "Sample"));
    assert!(!out.is_exclusive_borrow());

    // Against the other two borrows, which differ only where they should.
    for (spelling, exclusive) in [
        (quote::quote!(&Sample), false),
        (quote::quote!(&mut Sample), true),
    ] {
        let ty = lower(spelling).expect("in the language");
        assert_eq!(ty.is_exclusive_borrow(), exclusive);
        assert!(
            matches!(&ty.borrow_target().expect("a borrow").kind, TypeKind::Named { id, .. } if id.name == "Sample")
        );
    }

    // Owned, or shared-borrowed, it means nothing.
    assert_eq!(
        reason(quote::quote!(MaybeUninit<Sample>)),
        UnsupportedTypeReason::OwnedUninit
    );
    assert_eq!(
        reason(quote::quote!(&MaybeUninit<Sample>)),
        UnsupportedTypeReason::SharedUninit
    );

    // And it still needs no declaration, unlike every other generic-bearing name.
    let flat = Flat::builder()
        .items(vec![
            (opaque("Sample"), loc()),
            (
                syn::parse_quote!(
                    pub fn get(out: &mut MaybeUninit<Sample>) -> bool {}
                ),
                loc(),
            ),
        ])
        .build()
        .expect("parses");
    assert!(flat.function("get").is_some());
}

/// Refusing a type removes a *declaration*, so its dependents must be refused
/// too — otherwise a surviving element would hold a reference that resolves to
/// nothing, which is the one invariant the model promises.
///
/// Checked in both declaration orders, because a single pass against a snapshot
/// of the initial declarations keeps the dependent whichever way round it is.
#[test]
fn refusal_is_transitive() {
    let broken: syn::Item = syn::parse_quote!(
        pub struct Broken {
            pub field: Missing,
        }
    );
    let user: syn::Item = syn::parse_quote!(
        pub fn use_broken(value: Broken) {}
    );

    for (label, items) in [
        ("declaration first", vec![broken.clone(), user.clone()]),
        ("dependent first", vec![user, broken]),
    ] {
        let flat = Flat::builder()
            .items(items.into_iter().map(|i| (i, loc())))
            .build()
            .expect("deferred, not fatal");

        assert!(
            flat.declared_type("Broken").is_none(),
            "{label}: `Missing` is undeclared"
        );
        assert!(
            flat.function("use_broken").is_none(),
            "{label}: `Broken` is no longer a declaration either"
        );
        assert_eq!(flat.unsupported().count(), 2, "{label}");
        // Both still hold their names against the namespace.
        assert!(flat.element("Broken").is_some(), "{label}");
        assert!(flat.element("use_broken").is_some(), "{label}");
    }
}

/// And through a chain of any length, in either direction — the fixed point only
/// ever shrinks the declared set, so it terminates and misses no hop.
#[test]
fn refusal_is_transitive_through_a_chain() {
    let chain: Vec<syn::Item> = vec![
        syn::parse_quote!(
            pub struct A {
                pub field: Missing,
            }
        ),
        syn::parse_quote!(
            pub struct B {
                pub field: A,
            }
        ),
        syn::parse_quote!(
            pub struct C {
                pub field: B,
            }
        ),
        syn::parse_quote!(
            pub fn takes_c(value: C) {}
        ),
    ];

    for (label, items) in [
        ("forward", chain.clone()),
        ("reversed", chain.into_iter().rev().collect()),
    ] {
        let flat = Flat::builder()
            .items(items.into_iter().map(|i| (i, loc())))
            .build()
            .expect("deferred");
        assert_eq!(
            flat.types().count(),
            0,
            "{label}: the whole chain collapses"
        );
        assert_eq!(flat.functions().count(), 0, "{label}");
        assert_eq!(flat.unsupported().count(), 4, "{label}");
    }

    // A sound chain is untouched, so the fixed point is not just refusing
    // everything reachable.
    let flat = Flat::builder()
        .items(
            vec![
                opaque("Missing"),
                syn::parse_quote!(
                    pub struct A {
                        pub field: Missing,
                    }
                ),
                syn::parse_quote!(
                    pub fn takes_a(value: A) {}
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("parses");
    assert_eq!(flat.unsupported().count(), 0);
    assert!(flat.function("takes_a").is_some());
}

/// Every reference reachable from a *surviving* element resolves. That is what
/// the transitive pass buys, and what `resolve` relies on.
#[test]
fn every_surviving_reference_resolves() {
    let flat = Flat::builder()
        .items(
            vec![
                opaque("Missing"),
                syn::parse_quote!(
                    pub struct Held {
                        pub field: Missing,
                    }
                ),
                syn::parse_quote!(
                    pub fn takes_held(value: Held) -> Held {}
                ),
                // ... alongside a chain that does collapse.
                syn::parse_quote!(
                    pub struct Broken {
                        pub field: Absent,
                    }
                ),
                syn::parse_quote!(
                    pub fn takes_broken(value: Broken) {}
                ),
            ]
            .into_iter()
            .map(|i: syn::Item| (i, loc())),
        )
        .build()
        .expect("deferred");

    for f in flat.functions() {
        for r in f.params.iter().map(|p| &p.ty).chain([&f.ret]) {
            if let TypeKind::Named { id, .. } = &r.kind {
                assert!(
                    flat.resolve(id).is_some(),
                    "`{}` must resolve from a surviving function",
                    id.name
                );
            }
        }
    }
    assert!(flat.function("takes_held").is_some());
    assert!(flat.function("takes_broken").is_none());
}

/// A generic alias is a generic binder like any other item's, and `Extern` has no
/// binder or arity — so accepting one would let `Handle<u8>` resolve against a
/// declaration that says nothing about its parameter. It is also why
/// `MaybeUninit` needed grammar support rather than an alias.
#[test]
fn a_generic_alias_is_refused() {
    for (item, param, kind_str) in [
        (
            syn::parse_quote!(
                pub type Handle<T> = hidden::Handle<T>;
            ),
            "T",
            "a type parameter",
        ),
        (
            syn::parse_quote!(
                pub type Padded<const N: usize> = hidden::Padded<N>;
            ),
            "N",
            "a const generic parameter",
        ),
    ] {
        let element = parse_one(item);
        let ItemError::UnsupportedGenericParam { param: got, kind } = as_unsupported(&element)
        else {
            panic!(
                "expected a generic-parameter diagnosis, got {}",
                describe(&element)
            );
        };
        assert_eq!(got, param);
        assert_eq!(*kind, kind_str);
    }

    // A lifetime binder stays accepted, as it is on every other item kind:
    // lifetimes are spelling and the spelling already travels.
    let element = parse_one(syn::parse_quote!(
        pub type Borrowed<'a> = hidden::Borrowed<'a>;
    ));
    assert_eq!(as_extern(&element).name, "Borrowed");
}

// ── The flat namespace ─────────────────────────────────────────────────

/// The feeders accumulate, and the whole-stream rules span them.
///
/// This is why inputs are collected before anything is classified rather than
/// parsed one at a time: a duplicate name is only visible with every input in
/// hand, and so is a const that an array length in another input reaches for.
#[test]
fn the_feeders_accumulate_and_whole_stream_rules_span_them() {
    let marker: syn::Item = syn::parse_quote!(
        pub struct Marker {
            pub tag: [u8; TAG_LEN],
        }
    );

    // A length in the first feeder naming a const from the second.
    let flat = Flat::builder()
        .items(vec![(marker.clone(), loc())])
        .items(vec![(tag_len_const(), loc())])
        .build()
        .expect("the const is found across feeders");
    let elements: Vec<Element> = flat.elements().cloned().collect();
    assert_eq!(elements.len(), 2);
    assert_eq!(
        as_struct(&elements[0]).fields[0]
            .ty
            .array_extent()
            .expect("an extent")
            .value,
        4
    );

    // And a name colliding across feeders is still the one hard failure.
    let err = Flat::builder()
        .items(vec![(marker.clone(), loc())])
        .items(vec![(marker, loc())])
        .build()
        .expect_err("a duplicate across feeders is still a duplicate");
    let ParseError::DuplicateName(d) = err;
    assert_eq!(d.name, "Marker");
}

/// Two marked items with one name are ambiguous however the crates are
/// arranged, so this is the one thing a parse refuses outright.
#[test]
fn duplicate_names_are_a_hard_error() {
    let err = try_parse(vec![
        syn::parse_quote!(
            pub struct Sample {
                pub x: u8,
            }
        ),
        syn::parse_quote!(
            pub fn Sample() {}
        ),
    ])
    .expect_err("a duplicate");
    let ParseError::DuplicateName(d) = err;
    assert_eq!(d.name, "Sample");
}

/// Even an item the language could not express holds its name against the
/// namespace: it is still a marked item, and a second one would still be
/// ambiguous.
#[test]
fn an_unsupported_item_still_holds_its_name() {
    assert!(try_parse(vec![
        syn::parse_quote!(
            pub fn Thing(pair: (u8, u8)) {}
        ),
        syn::parse_quote!(
            pub struct Thing {
                pub x: u8,
            }
        ),
    ])
    .is_err());
}

/// The layer stack accepts one shape — `Option<Vec<T>>` — and stops at the first
/// layer that is out of that order or repeats.
///
/// A recursion would happily return `Iterable(Optional(Base))` for
/// `Vec<Option<T>>`, and that is wrong in a way the shape alone does not show:
/// the optional there belongs to the **element**, not to the boundary. The
/// difference is behavioural — `returns_type` compares the core, so an unbounded
/// peel makes a `Vec<Option<T>>` return match a decomposition target `T` and
/// installs a nested optional fold, while the explicit path next to it still
/// refuses `Vec<Option<…>>` as unsupported. One of the two has to be wrong, and
/// it is not the refusal.
///
/// `layer_types` has to stop at the same place, or the registration view
/// un-requires types the shape says are part of the element.
#[test]
fn the_layer_stack_stops_at_an_out_of_order_layer() {
    use crate::shape::Shape;

    let shape_of = |ty: proc_macro2::TokenStream| {
        let reading = lower(ty).expect("lowers");
        let (shape, core) = reading.layer_stack();
        let rendered = match &shape {
            Shape::Base => "Base".to_string(),
            Shape::Optional(_, i) => match &**i {
                Shape::Base => "Optional(Base)".to_string(),
                Shape::Iterable(_) => "Optional(Iterable(Base))".to_string(),
                Shape::Optional(..) => "Optional(Optional(..))".to_string(),
            },
            Shape::Iterable(i) => match &**i {
                Shape::Base => "Iterable(Base)".to_string(),
                other => format!("Iterable({other:?})"),
            },
        };
        (
            rendered,
            quote::ToTokens::to_token_stream(core.origin.as_syn()).to_string(),
            reading.layer_types().len(),
        )
    };

    // In order: both layers are the boundary's.
    assert_eq!(
        shape_of(quote::quote!(Option<Vec<Sample>>)),
        ("Optional(Iterable(Base))".into(), "Sample".into(), 3)
    );
    assert_eq!(
        shape_of(quote::quote!(Option<Sample>)),
        ("Optional(Base)".into(), "Sample".into(), 2)
    );
    assert_eq!(
        shape_of(quote::quote!(Vec<Sample>)),
        ("Iterable(Base)".into(), "Sample".into(), 2)
    );

    // Out of order: the optional is the element's, so the stack stops.
    assert_eq!(
        shape_of(quote::quote!(Vec<Option<Sample>>)),
        ("Iterable(Base)".into(), "Option < Sample >".into(), 2)
    );

    // Repeated: the boundary has one way to say absent.
    assert_eq!(
        shape_of(quote::quote!(Option<Option<Sample>>)),
        ("Optional(Base)".into(), "Option < Sample >".into(), 2)
    );

    // A borrow is not a layer at all — it is ownership, and stays on the core.
    assert_eq!(
        shape_of(quote::quote!(Option<Vec<&Sample>>)),
        ("Optional(Iterable(Base))".into(), "& Sample".into(), 3)
    );
}

/// A **composed** type keys exactly as the spelling it replaces, and classifies
/// as what it was built from.
///
/// The decomposition plans compose types no source wrote — the borrow of a
/// value, a presence flag, a selector — and those types are registered as
/// crossings like any other. If a composed `&T` keyed differently from
/// `parse_quote!(&#t)`, it would register a *different cell* and resolution
/// would silently change. So the identity is pinned, not assumed.
///
/// The pairing is the point: `kind` and `spell()` are built together in
/// one place, so a consumer classifying off one and spelling off the other
/// cannot be handed a disagreement.
#[test]
fn a_composed_type_keys_as_its_spelling() {
    use crate::flat::{ScalarKind, TypeKey, TypeKind, TypeRef};

    let t = lower(quote::quote!(u64)).expect("in the language");

    let borrowed = t.borrowed();
    assert_eq!(borrowed.key(), TypeKey::from_type(&syn::parse_quote!(&u64)));
    assert!(matches!(borrowed.kind, TypeKind::Ref { .. }));
    // The layer wraps the reading it was built from, so peeling gets it back.
    assert_eq!(borrowed.borrow_target().expect("a borrow").key(), t.key());

    let optional = t.optional();
    assert_eq!(
        optional.key(),
        TypeKey::from_type(&syn::parse_quote!(Option<u64>))
    );
    assert_eq!(optional.optional_inner().expect("optional").key(), t.key());

    // A scalar the binding invented: spelled from its own kind, so the two
    // cannot drift.
    assert_eq!(
        TypeRef::scalar(ScalarKind::Bool).key(),
        TypeKey::from_type(&syn::parse_quote!(bool))
    );
    assert_eq!(
        TypeRef::scalar(ScalarKind::I32).key(),
        TypeKey::from_type(&syn::parse_quote!(i32))
    );
    assert_eq!(
        TypeRef::named(&syn::parse_quote!(ZEnum)).key(),
        TypeKey::from_type(&syn::parse_quote!(ZEnum))
    );

    // Composed-from-nothing is PLACELESS: no file wrote it, and claiming a
    // location would make a fabricated one indistinguishable from a real one.
    assert!(
        !TypeRef::scalar(ScalarKind::Bool)
            .origin
            .location
            .has_position(),
        "a scalar no source wrote carries no position"
    );
    // A layered one keeps the inner's location — the borrow exists because of
    // that value.
    assert_eq!(&*borrowed.origin.location, &*t.origin.location);
}

/// A **raw** identifier survives the round trip through `TypeId`.
///
/// `TypeId::name` is a `String`, so an enum legitimately named `r#type` is
/// stored as `"r#type"` — and `Ident::new` *rejects* that spelling, panicking
/// rather than returning an error. A consumer rebuilding an ident from the name
/// therefore has to parse, and gets no warning until a source happens to use a
/// keyword. `TypeId::ident` is where that recovery lives (#278 review).
#[test]
fn a_raw_identifier_survives_typeid() {
    use crate::flat::{TypeKind, TypeRef};

    let raw: syn::Ident = syn::parse_quote!(r#type);
    assert_eq!(raw.to_string(), "r#type", "the hash is part of the name");

    let t = TypeRef::named(&raw);
    let TypeKind::Named { id, .. } = &t.kind else {
        panic!("named")
    };
    // Recovered, and it spells itself back the way it was written.
    let back = id.ident().expect("a raw ident is still an ident");
    assert_eq!(back, raw);
    assert_eq!(tokens(t.origin.as_syn()), "r#type");

    // A path-qualified name is not a single identifier — the same answer the
    // old `bare_path_ident` gave.
    let qualified = crate::flat::TypeId {
        name: "foreign::Option".to_string(),
    };
    assert!(qualified.ident().is_none());
}