ridl-backend-rust 0.2.0

Compiles a RIDL IR package to Rust source, plus the generated interaction face.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
//! Backend tests: per-construct snapshots, the Appendix B rustc-compile proof,
//! Default derivation behaviour (the leaf-recursion rule), and the C header
//! snapshot.

use super::{Ctx, Generated, check_flatbuffers_bound, generate, generate_face, generate_with};
use ridl_ir::v2;

// ---------------------------------------------------------------------------
// Fixture builders.
// ---------------------------------------------------------------------------

fn public_decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
    v2::Decl {
        name: name.to_string(),
        visibility: v2::Visibility::Public as i32,
        is_error: false,
        doc: String::new(),
        labels: Vec::new(),
        deprecated: None,
        ordinal: 0,
        kind: Some(kind),
    }
}

fn package(name: &str, decls: Vec<v2::Decl>) -> v2::Package {
    v2::Package {
        name: name.to_string(),
        decls,
        interfaces: Vec::new(),
        services: Vec::new(),
        retired: Vec::new(),
    }
}

fn init_value(derivable: bool, value: Option<&str>) -> v2::InitValue {
    v2::InitValue {
        derivable,
        value: value.map(str::to_string),
    }
}

fn constraint(min: Option<&str>, max: Option<&str>, step: Option<&str>) -> v2::Constraint {
    v2::Constraint {
        min: min.map(str::to_string),
        max: max.map(str::to_string),
        step: step.map(str::to_string),
        len_min: None,
        len_max: None,
        pattern: None,
        pattern_const: None,
    }
}

fn unit_type(unit: &str, min: &str, max: &str, step: &str, init: &str) -> v2::decl::Kind {
    v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Unit(unit.to_string())),
        }),
        constraint: Some(constraint(Some(min), Some(max), Some(step))),
        declared_init: None,
        init: Some(init_value(true, Some(init))),
        width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
    })
}

fn primitive_type(
    prim: v2::PrimitiveType,
    init: v2::InitValue,
    width: Option<v2::type_def::Width>,
) -> v2::decl::Kind {
    v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Primitive(prim as i32)),
        }),
        constraint: None,
        declared_init: None,
        init: Some(init),
        width,
    })
}

/// A `string`-backed named scalar carrying typl §4.4's default `[0..256]`
/// length bound.
///
/// The checker always materializes that bound (TYPL-103), so IR that reaches
/// a backend always has one; a hand-built fixture without one has no finite
/// FlatBuffers bound and the codec refuses it (design note D-7, §4a).
fn bounded_string_type(init: v2::InitValue) -> v2::decl::Kind {
    v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Primitive(
                v2::PrimitiveType::String as i32,
            )),
        }),
        constraint: Some(v2::Constraint {
            len_max: Some(256),
            ..Default::default()
        }),
        declared_init: None,
        init: Some(init),
        width: None,
    })
}

/// A `bytes`-backed named scalar carrying typl §4.5's default `[0..256]`
/// length bound, the `bytes` counterpart of [`bounded_string_type`].
fn bounded_bytes_type(init: v2::InitValue) -> v2::decl::Kind {
    v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Primitive(
                v2::PrimitiveType::Bytes as i32,
            )),
        }),
        constraint: Some(v2::Constraint {
            len_max: Some(256),
            ..Default::default()
        }),
        declared_init: None,
        init: Some(init),
        width: None,
    })
}

/// The `integer` width the checker derives for a named scalar with no
/// range — typl Appendix D's `long`, which every backend sees on IR the
/// compiler produced. ADR-0019 decision 8 roots such a declaration in a box,
/// so a hand-built fixture with no width has no finite FlatBuffers bound and
/// the codec refuses it.
fn derived_int_width() -> Option<v2::type_def::Width> {
    Some(v2::type_def::Width::IntWidth(v2::IntWidth::I64 as i32))
}

/// The `float` width the checker derives for a named scalar with no unit —
/// `double`. The `integer` counterpart is [`derived_int_width`].
fn derived_float_width() -> Option<v2::type_def::Width> {
    Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F64 as i32))
}

fn named_field(
    name: &str,
    ordinal: u32,
    type_ref: &str,
    optional: bool,
    init: v2::InitValue,
) -> v2::Field {
    v2::Field {
        name: name.to_string(),
        ordinal,
        r#type: Some(v2::FieldType {
            optional,
            kind: Some(v2::field_type::Kind::Named(type_ref.to_string())),
        }),
        declared_init: None,
        init: Some(init),
        doc: String::new(),
        labels: Vec::new(),
        deprecated: None,
    }
}

fn field_member(field: v2::Field) -> v2::StructMember {
    v2::StructMember {
        member: Some(v2::struct_member::Member::Field(field)),
    }
}

fn reserved_member(ordinal: u32, name: &str) -> v2::StructMember {
    v2::StructMember {
        member: Some(v2::struct_member::Member::Reserved(v2::Reserved {
            ordinal,
            name: Some(name.to_string()),
            value: None,
        })),
    }
}

fn enum_value(name: &str, value: i64) -> v2::EnumValue {
    v2::EnumValue {
        name: name.to_string(),
        value,
        doc: String::new(),
    }
}

fn warning_bits() -> Vec<v2::EnumValue> {
    vec![
        enum_value("LOW_FUEL", 0),
        enum_value("CHECK_ENGINE", 1),
        enum_value("DOOR_OPEN", 2),
        enum_value("SEATBELT", 3),
    ]
}

/// A `GearPosition`-like enum declaration used by the raw-discriminant
/// conversion tests.
///
/// The discriminants are deliberately not contiguous from zero, which is what
/// the `enum_with_discriminants` snapshot fixture uses. A conversion built
/// from each variant's position rather than its declared value emits the same
/// source for a contiguous fixture, so a gap is what makes the arm mapping
/// observable.
fn gear_position_decl() -> v2::Decl {
    public_decl(
        "GearPosition",
        v2::decl::Kind::EnumDef(v2::EnumDef {
            values: vec![
                enum_value("PARK", 0),
                enum_value("DRIVE", 1),
                enum_value("REVERSE", 7),
                enum_value("NEUTRAL", 9),
            ],
            reserved: Vec::new(),
        }),
    )
}

/// A `Features`-like enum set declaration used by the raw bit-pattern
/// conversion tests.
fn features_decl() -> v2::Decl {
    public_decl(
        "Features",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: None,
            bits: warning_bits(),
            width: v2::IntWidth::U8 as i32,
        }),
    )
}

/// A `Speed`-like unit type declaration used across the small fixtures.
fn speed_decl() -> v2::Decl {
    v2::Decl {
        doc: "Vehicle speed over ground".to_string(),
        ..public_decl("Speed", unit_type("km/h", "0.0", "250.0", "0.5", "0.0"))
    }
}

/// A `string`-backed type carrying a positive length bound and a literal
/// pattern, used to pin that the pattern check is gated behind
/// `validate-pattern` while the length check is not. `len_min` and `len_max`
/// are both 17 so the minimum branch is emitted (a `len_min` of 0 emits no
/// branch at all).
fn vin_decl() -> v2::Decl {
    public_decl(
        "Vin",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                len_min: Some(17),
                len_max: Some(17),
                pattern: Some("/[A-HJ-NPR-Z0-9]{17}/".to_string()),
                ..constraint(None, None, None)
            }),
            declared_init: None,
            init: Some(init_value(false, None)),
            width: None,
        }),
    )
}

/// A `bytes`-backed type carrying a positive length bound and a literal
/// pattern.
///
/// **No typl source produces this.** The reference gives bytes no `match`
/// (§4.5, §5.4), and `lower_scalar` passes `allow_pattern: false` for that
/// backing, so a `match` written on a bytes type is dropped and the IR
/// carries `{len_min, len_max}` and nothing else. The fixture is built by
/// hand to exercise the backend's totality over an IR it did not lower
/// itself, which is the same thing `a_range_on_a_non_numeric_backing_emits_no_range_check`
/// does for `min`/`max` — `lower_len_scalar` always leaves those absent too.
///
/// What it pins: `newtype_inner` gives such a type a `Vec<u8>`, against which
/// `regex::Regex::is_match` (which takes `&str`) does not type-check, so
/// `constraint_checks` must emit no pattern branch while still emitting its
/// length checks.
fn bytes_pattern_decl() -> v2::Decl {
    public_decl(
        "Sig",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Bytes as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                len_min: Some(1),
                len_max: Some(8),
                pattern: Some("/^[A-Z]+$/".to_string()),
                ..constraint(None, None, None)
            }),
            declared_init: None,
            init: Some(init_value(false, None)),
            width: None,
        }),
    )
}

/// A `string`-backed type whose pattern is a literal the stand-in `regex`
/// can decide, with `len_min` and `len_max` both 3 so a matching and a
/// non-matching value are the same length and the length checks cannot be
/// what separates them. Used by the executed proof of the pattern check.
fn literal_pattern_decl() -> v2::Decl {
    public_decl(
        "Code",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                len_min: Some(3),
                len_max: Some(3),
                pattern: Some("/ABC/".to_string()),
                ..constraint(None, None, None)
            }),
            declared_init: None,
            init: Some(init_value(false, None)),
            width: None,
        }),
    )
}

fn counter_decl() -> v2::Decl {
    public_decl(
        "Counter",
        primitive_type(
            v2::PrimitiveType::Integer,
            init_value(true, Some("0")),
            Some(v2::type_def::Width::IntWidth(v2::IntWidth::U16 as i32)),
        ),
    )
}

// ---------------------------------------------------------------------------
// The `Wire` alias and a declaration that would collide with it (#476).
// ---------------------------------------------------------------------------

/// A declaration named `Wire`, the collision #476 reports.
///
/// The **width** is load-bearing, not a range: a named scalar with no declared
/// width has no finite FlatBuffers bound, and both entry points then refuse it
/// for that reason (K4's D-7 refusal) rather than for the collision — which
/// would make the assertion below pass vacuously. This carries `Counter`'s
/// width for that reason.
fn wire_named_decl() -> v2::Decl {
    public_decl(
        "Wire",
        primitive_type(
            v2::PrimitiveType::Integer,
            init_value(true, Some("0")),
            Some(v2::type_def::Width::IntWidth(v2::IntWidth::U16 as i32)),
        ),
    )
}

/// A package declaring `Wire` is refused by the face entry point rather than
/// emitting two items of that name.
///
/// `generate_face` emits `pub type Wire` at package scope, and a typl
/// declaration named `Wire` emits `pub struct Wire` at the same scope; rustc
/// reports E0428 on the pair. The refusal names the declaration so the cause
/// is the package's, not a line of generated source the author never wrote.
/// E11.14 decision 5: the collision is in the package rather than in one
/// interface, so it is a build error and not decision 2's per-interface skip.
#[test]
fn a_declaration_named_wire_is_refused_by_the_face() {
    let error = generate_face(&package("veh.common", vec![wire_named_decl()]))
        .expect_err("a declaration named `Wire` collides with the encoding alias");
    // Asserting only that the message names `Wire` would be satisfied by an
    // unrelated refusal that happens to carry the declaration's path — an
    // unconstrained `integer` has no finite FlatBuffers bound and is refused
    // by both entry points, which is why this fixture carries a range.
    assert!(
        error.message.contains("collide") || error.message.contains("alias"),
        "the refusal must state the collision, got: {}",
        error.message
    );
    assert!(
        error.message.contains("Wire"),
        "the refusal must name the declaration, got: {}",
        error.message
    );
}

/// The plain entry point is unaffected: it emits no alias, so `Wire` is an
/// ordinary declaration there. This is what keeps decision 5 scoped to the
/// face rather than narrowing what `generate` accepts.
#[test]
fn a_declaration_named_wire_generates_without_a_face() {
    let source = generate(&package("veh.common", vec![wire_named_decl()]))
        .expect("the plain entry point emits no alias")
        .rust_source;
    assert!(source.contains("pub struct Wire("), "got:\n{source}");
    assert!(!source.contains("pub type Wire"), "got:\n{source}");
}

// ---------------------------------------------------------------------------
// Per-construct snapshots.
// ---------------------------------------------------------------------------

fn rust_for(decls: Vec<v2::Decl>) -> String {
    generate(&package("veh.common", decls))
        .expect("generation succeeds")
        .rust_source
}

#[test]
fn scalar_unit_type_with_doc() {
    insta::assert_snapshot!(rust_for(vec![speed_decl()]));
}

#[test]
fn named_scalar_backings() {
    let decls = vec![
        speed_decl(),
        counter_decl(),
        public_decl(
            "Enabled",
            primitive_type(
                v2::PrimitiveType::Boolean,
                init_value(true, Some("false")),
                None,
            ),
        ),
        public_decl("Label", bounded_string_type(init_value(true, Some("")))),
        public_decl("Blob", bounded_bytes_type(init_value(true, Some("")))),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn constrained_scalar_is_a_value_object() {
    let source = rust_for(vec![speed_decl()]);
    // The field is private: no `pub` inside the tuple struct.
    assert!(
        source.contains("pub struct Speed(f64)"),
        "inner field must be private, got:\n{source}"
    );
    // The plan's Task 3 spells `Result`, `TryFrom` and `From` unqualified.
    // The generated code names them by absolute path instead, because a
    // package may declare a type of the same name in the same module
    // (`prelude_names_declared_by_the_package_compile`); these assertions
    // follow the generated code, not the plan's text. The signature is
    // checked in two parts because prettyplease wraps it at its own width.
    assert!(source.contains("pub fn new("));
    assert!(source.contains(") -> ::core::result::Result<Self, ::ridl_rt::payload::Violation> {"));
    assert!(source.contains("pub const fn new_unchecked(value: f64) -> Self"));
    assert!(source.contains("pub const fn get(self) -> f64"));
    assert!(source.contains("impl ::core::convert::TryFrom<f64> for Speed"));
    assert!(source.contains("impl ::core::convert::From<Speed> for f64"));
    // The infallible inbound conversion must never appear on a constrained type.
    assert!(
        !source.contains("impl ::core::convert::From<f64> for Speed")
            && !source.contains("impl From<f64> for Speed"),
        "From<Inner> reintroduces unchecked construction"
    );
}

#[test]
fn vacuous_scalar_constructs_infallibly() {
    let decls = vec![public_decl(
        "Enabled",
        primitive_type(
            v2::PrimitiveType::Boolean,
            init_value(true, Some("false")),
            None,
        ),
    )];
    let source = rust_for(decls);
    assert!(source.contains("pub const fn new(value: bool) -> Self"));
    assert!(source.contains("impl ::core::convert::From<bool> for Enabled"));
    assert!(source.contains("impl ::core::convert::From<Enabled> for bool"));
    // No escape hatch is emitted: `new` already is one.
    assert!(
        !source.contains("Enabled::new_unchecked")
            && !source.contains("fn new_unchecked(value: bool)"),
        "new_unchecked would duplicate new on a vacuous type, got:\n{source}"
    );
    // And no manual TryFrom, which would collide with core's blanket impl.
    assert!(
        !source.contains("impl ::core::convert::TryFrom<bool> for Enabled")
            && !source.contains("impl TryFrom<bool> for Enabled"),
        "a manual TryFrom collides with core's blanket impl, got:\n{source}"
    );
}

/// `constraint_is_vacuous` excludes `step` (`crates/ridl-ir/src/lib.rs`), so a
/// constraint carrying only a `step` is vacuous and takes the infallible
/// `emit_vacuous_type_def` path — the same path `Enabled` above takes with no
/// constraint at all. `unchecked_doc` still names the gap on a type reached
/// this way, because it reads `step` unconditionally, off the same
/// `td.constraint`, regardless of which path emitted the type. Deleting the
/// `step` exclusion from `constraint_is_vacuous` would route this type
/// through `emit_type_def` instead and stop `unchecked_doc`'s note from
/// matching a constructor that had gone fallible; this test catches that.
#[test]
fn step_only_scalar_is_vacuous_and_still_names_the_gap() {
    let source = rust_for(vec![public_decl(
        "Rounded",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Float as i32,
                )),
            }),
            constraint: Some(constraint(None, None, Some("0.5"))),
            declared_init: None,
            init: Some(init_value(true, Some("0.0"))),
            width: derived_float_width(),
        }),
    )]);
    // The vacuous path: infallible `new`, no `new_unchecked`, no manual
    // `TryFrom`.
    assert!(source.contains("pub const fn new(value: f64) -> Self"));
    assert!(source.contains("impl ::core::convert::From<f64> for Rounded"));
    assert!(
        !source.contains("Rounded::new_unchecked")
            && !source.contains("fn new_unchecked(value: f64)"),
        "new_unchecked would duplicate new on a vacuous type, got:\n{source}"
    );
    assert!(
        !source.contains("impl ::core::convert::TryFrom<f64> for Rounded")
            && !source.contains("impl TryFrom<f64> for Rounded"),
        "a manual TryFrom collides with core's blanket impl, got:\n{source}"
    );
    // And the quantization gap is still named on the type, although `new`
    // cannot fail.
    assert!(source.contains("/// Quantization (`step`) is not checked by `new`."));
    // No `fn check` on the vacuous path either: `named_scalar_check`'s
    // `ctor != "new_unchecked"` short-circuit depends on this, since a
    // vacuous type's `ctor` is `"new"`, not `"new_unchecked"`.
    assert!(
        !source.contains("fn check("),
        "a vacuous type has no invariant for check to hold, got:\n{source}"
    );
}

#[test]
fn constant_of_a_constrained_type_uses_new_unchecked() {
    let decls = vec![
        speed_decl(),
        public_decl(
            "MAX_SPEED",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some("Speed".to_string()),
                value: "250.0".to_string(),
                regex: None,
            }),
        ),
    ];
    let source = rust_for(decls);
    assert!(source.contains("Speed::new_unchecked(250.0)"));
}

/// A string- or bytes-backed named scalar with a length bound and no range.
/// A type whose minimum length is positive has no derivable init (typl §5.8).
fn bounded_text_type(prim: v2::PrimitiveType, len_min: u64, len_max: u64) -> v2::decl::Kind {
    v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Primitive(prim as i32)),
        }),
        constraint: Some(v2::Constraint {
            len_min: Some(len_min),
            len_max: Some(len_max),
            ..constraint(None, None, None)
        }),
        declared_init: None,
        init: Some(if len_min == 0 {
            init_value(true, Some(""))
        } else {
            init_value(false, None)
        }),
        width: None,
    })
}

/// A float named scalar with a range and no `step`.
fn ratio_decl() -> v2::Decl {
    public_decl(
        "Ratio",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Float as i32,
                )),
            }),
            constraint: Some(constraint(Some("0.0"), Some("1.0"), None)),
            declared_init: None,
            init: Some(init_value(true, Some("0.0"))),
            width: derived_float_width(),
        }),
    )
}

/// The constraint branches `named_scalar_backings` does not reach: a string
/// length bound, a bytes length bound, and a range without a `step`.
#[test]
fn constrained_scalar_backings() {
    let decls = vec![
        public_decl("Name", bounded_text_type(v2::PrimitiveType::String, 1, 64)),
        public_decl("Digest", bounded_text_type(v2::PrimitiveType::Bytes, 0, 32)),
        ratio_decl(),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn a_string_length_bound_counts_characters() {
    let source = rust_for(vec![public_decl(
        "Name",
        bounded_text_type(v2::PrimitiveType::String, 1, 64),
    )]);
    for check in [
        "if (value.chars().count() as u64) < 1 {",
        "if (value.chars().count() as u64) > 64 {",
        "rule: ::ridl_rt::payload::Rule::Length,",
    ] {
        assert!(source.contains(check), "expected `{check}` in:\n{source}");
    }
}

#[test]
fn a_bytes_length_bound_counts_bytes() {
    let source = rust_for(vec![public_decl(
        "Digest",
        bounded_text_type(v2::PrimitiveType::Bytes, 4, 32),
    )]);
    for check in [
        "if (value.len() as u64) < 4 {",
        "if (value.len() as u64) > 32 {",
    ] {
        assert!(source.contains(check), "expected `{check}` in:\n{source}");
    }
}

/// `[0..256]` is the default length bound of string and bytes (typl §4.4,
/// §4.5), so a minimum of 0 is the common case. `(… as u64) < 0` is never
/// true and draws rustc's `unused_comparisons` warning in the consumer's
/// build, so the branch is not emitted.
#[test]
fn a_zero_length_minimum_emits_no_check() {
    for (name, prim) in [
        ("Text", v2::PrimitiveType::String),
        ("Blob", v2::PrimitiveType::Bytes),
    ] {
        let source = rust_for(vec![public_decl(name, bounded_text_type(prim, 0, 256))]);
        assert!(
            !source.contains("< 0"),
            "a zero minimum must emit no comparison, got:\n{source}"
        );
        assert!(
            source.contains("> 256"),
            "the maximum is still checked, got:\n{source}"
        );
    }
}

/// The newtype backing an integer named scalar is always `i64`
/// (`newtype_inner`). A maximum equal to `i64::MAX` (9223372036854775807)
/// makes `value > 9223372036854775807` never true: rustc draws its
/// `unused_comparisons` warning on it in the consumer's build, so the branch
/// is not emitted when the declared maximum equals the inner type's maximum.
#[test]
fn a_maximum_at_the_inner_types_maximum_emits_no_check() {
    let source = rust_for(vec![public_decl(
        "Timestamp",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Integer as i32,
                )),
            }),
            constraint: Some(constraint(Some("0"), Some("9223372036854775807"), None)),
            declared_init: None,
            init: Some(init_value(true, Some("0"))),
            width: derived_int_width(),
        }),
    )]);
    assert!(
        !source.contains("> 9223372036854775807"),
        "a maximum at i64::MAX must emit no comparison, got:\n{source}"
    );
    assert!(
        source.contains("if value < 0 {"),
        "the minimum is still checked, got:\n{source}"
    );
}

/// The suppression above is an exact equality, not a threshold: a maximum one
/// below `i64::MAX` is a comparison rustc cannot fold, so the branch is still
/// emitted. Without this test a guard that suppressed a range of large maxima
/// would pass the suite.
#[test]
fn a_maximum_below_the_inner_types_maximum_still_emits_a_check() {
    let source = rust_for(vec![public_decl(
        "Timestamp",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Integer as i32,
                )),
            }),
            constraint: Some(constraint(Some("0"), Some("9223372036854775806"), None)),
            declared_init: None,
            init: Some(init_value(true, Some("0"))),
            width: derived_int_width(),
        }),
    )]);
    assert!(
        source.contains("> 9223372036854775806"),
        "a maximum below i64::MAX must still be checked, got:\n{source}"
    );
}

/// The suppression applies to an integer backing only. A float backing is
/// never asked whether its maximum looks like `i64::MAX`, because the float
/// newtype is not backed by `i64` and the comparison is not a tautology there.
/// This pins that short circuit: without it, a float maximum that happens to
/// spell `i64::MAX` would lose its check.
#[test]
fn a_float_maximum_spelling_the_integer_maximum_still_emits_a_check() {
    let source = rust_for(vec![public_decl(
        "Ratio",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Float as i32,
                )),
            }),
            constraint: Some(constraint(Some("0.0"), Some("9223372036854775807"), None)),
            declared_init: None,
            init: Some(init_value(true, Some("0.0"))),
            width: derived_float_width(),
        }),
    )]);
    assert!(
        source.contains("> 9223372036854775807"),
        "a float maximum must be checked whatever it spells, got:\n{source}"
    );
}

/// A `min` or `max` on a non-numeric backing is not something `ridl-sem`
/// produces, but the IR is an artifact other tools write (ADR-0014), so the
/// backend ignores the two rather than rendering a numeric comparison against
/// a `String`.
#[test]
fn a_range_on_a_non_numeric_backing_emits_no_range_check() {
    let source = rust_for(vec![public_decl(
        "Handle",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                len_min: Some(1),
                len_max: Some(8),
                ..constraint(Some("0"), Some("10"), None)
            }),
            declared_init: None,
            init: Some(init_value(false, None)),
            width: None,
        }),
    )]);
    assert!(
        !source.contains("Rule::Range")
            && !source.contains("if value <")
            && !source.contains("if value >"),
        "a range on a string backing must emit no range check, got:\n{source}"
    );
    assert!(
        source.contains("Rule::Length"),
        "the length bound is still checked, got:\n{source}"
    );
}

#[test]
fn a_range_without_a_step_names_nothing_unchecked() {
    let source = rust_for(vec![ratio_decl()]);
    assert!(
        !source.contains("is not checked by `new`"),
        "a constraint with no step and no pattern has nothing unchecked to name, got:\n{source}"
    );
    assert!(
        source.contains("if value > 1.0 {"),
        "the range is still checked, got:\n{source}"
    );
}

/// An unresolved `pattern_const` names the pattern as unchecked, because no
/// check is emitted for it (design, "Not validated, and documented as such"
/// still applies to that case). A length bound alone leaves nothing unchecked
/// to name.
#[test]
fn an_unresolved_pattern_const_is_named_on_the_type() {
    let with_pattern = |pattern_const: Option<&str>| {
        rust_for(vec![public_decl(
            "Handle",
            v2::decl::Kind::TypeDef(v2::TypeDef {
                backing: Some(v2::Backing {
                    kind: Some(v2::backing::Kind::Primitive(
                        v2::PrimitiveType::String as i32,
                    )),
                }),
                constraint: Some(v2::Constraint {
                    len_min: Some(3),
                    len_max: Some(8),
                    pattern: None,
                    pattern_const: pattern_const.map(str::to_string),
                    ..constraint(None, None, None)
                }),
                declared_init: None,
                init: Some(init_value(false, None)),
                width: None,
            }),
        )])
    };
    let source = with_pattern(Some("HANDLE_PATTERN"));
    assert!(
        source.contains("/// The `match` pattern is not checked by `new`."),
        "an unresolved pattern constant must be named as unchecked, got:\n{source}"
    );
    let source = with_pattern(None);
    assert!(
        !source.contains("is not checked by `new`"),
        "a length bound alone leaves nothing unchecked to name, got:\n{source}"
    );
}

/// A literal pattern is checked by `new` under `validate-pattern`, so the
/// type names that condition instead of claiming the pattern goes unchecked
/// outright.
#[test]
fn a_literal_pattern_is_named_as_feature_gated() {
    let source = rust_for(vec![public_decl(
        "Handle",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                len_min: Some(3),
                len_max: Some(8),
                pattern: Some("/[a-z]+/".to_string()),
                pattern_const: None,
                ..constraint(None, None, None)
            }),
            declared_init: None,
            init: Some(init_value(false, None)),
            width: None,
        }),
    )]);
    assert!(
        !source.contains("The `match` pattern is not checked by `new`."),
        "a literal pattern is checked by `new` under the feature, got:\n{source}"
    );
    // The assertion names the doc line itself. A bare `contains`
    // ("validate-pattern") is satisfied by the `#[cfg(feature =
    // "validate-pattern")]` attribute in the constructor body, so deleting
    // the doc line entirely would leave it green.
    assert!(
        source.contains(
            "/// The `match` pattern is checked by `new` only when the crate is built with the `validate-pattern` feature."
        ),
        "the type must name the condition its pattern guarantee depends on, got:\n{source}"
    );
}

/// A `step` and a literal pattern together are both named: the step is never
/// checked, and the pattern is checked only under `validate-pattern`. The
/// `unchecked_doc` check for `step` reads no backing, so it is unconditional;
/// the backing here is `String` so the pattern's own guard (a check is
/// emitted only for a `String` backing) also applies.
#[test]
fn a_step_and_a_literal_pattern_are_both_named() {
    let source = rust_for(vec![public_decl(
        "Stepped",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
            constraint: Some(v2::Constraint {
                pattern: Some("/x/".to_string()),
                // typl §4.4's default length bound, which the checker always
                // materializes and the box root needs to be sizable.
                len_max: Some(256),
                ..constraint(None, None, Some("0.5"))
            }),
            declared_init: None,
            init: Some(init_value(true, Some("0.0"))),
            width: None,
        }),
    )]);
    assert!(source.contains("/// Quantization (`step`) is not checked by `new`."));
    assert!(!source.contains("The `match` pattern is not checked by `new`."));
    // The doc line itself, not the `cfg` attribute that also carries the
    // feature name.
    assert!(source.contains(
        "/// The `match` pattern is checked by `new` only when the crate is built with the `validate-pattern` feature."
    ));
}

/// The pattern check is emitted only under `validate-pattern`; the range and
/// length checks above it are not gated, since they need no dependency.
#[test]
fn pattern_check_is_feature_gated() {
    let source = rust_for(vec![vin_decl()]);
    assert!(source.contains("#[cfg(feature = \"validate-pattern\")]"));
    assert!(source.contains("::ridl_rt::payload::Rule::Pattern"));
    // Both crate paths are absolute, so an interface named `Std` or `Regex`
    // cannot shadow them from the module the constructor lives in.
    assert!(source.contains("::std::sync::LazyLock"));
    // The regex source is the pattern with its `/` delimiters stripped. The
    // IR stores them (`ridl-sem` keeps the literal as written), and emitting
    // them would compile into a regex that never matches, so every `new`
    // would reject every value. Asserting only on `Regex::new` leaves that
    // undetected, so the argument is pinned too.
    assert!(
        source.contains(r#"::regex::Regex::new("[A-HJ-NPR-Z0-9]{17}")"#),
        "the emitted regex source must have its delimiters stripped, got:\n{source}"
    );
    // The length check is not gated - it needs no dependency. This is the
    // text before the first gate, so the name says ungated, not gated.
    let ungated = source
        .split("#[cfg(feature = \"validate-pattern\")]")
        .next()
        .unwrap();
    assert!(ungated.contains("::ridl_rt::payload::Rule::Length"));
}

/// Outside this test and [`the_generated_pattern_check_runs`], no proof in
/// this repository compiles the `#[cfg(feature = "validate-pattern")]` block:
/// every other `rustc` compile proof, here and in
/// `crates/ridlc/tests/rust_crate_emit.rs`, drives bare `rustc` with no
/// `--cfg` for that feature, so the block is compiled out. `regex` is not a
/// declared dependency of any workspace crate, so neither proof can link the
/// real one; both link [`regex_stub_rlib`], a hand-written stand-in built the
/// same way [`ridl_rt_rlib`] builds `ridl-rt` (see its doc comment for why one
/// `rustc` call is the whole build).
///
/// The two are not redundant. This one uses `vin_decl` and is the only test
/// asserting that the gate attribute is emitted at all, so it alone catches
/// the gate being dropped. [`the_generated_pattern_check_runs`] uses a fixture
/// whose pattern its stand-in can decide, and runs the result, so it catches
/// what compiling cannot see.
#[test]
fn pattern_check_compiles_under_validate_pattern_against_a_regex_stand_in() {
    let source = rust_for(vec![vin_decl()]);
    assert!(
        source.contains("#[cfg(feature = \"validate-pattern\")]"),
        "the fixture must actually exercise the gated block, got:\n{source}"
    );

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("pattern_gated.rs");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let ridl_rt = ridl_rt_rlib(dir.path());
    let regex = regex_stub_rlib(dir.path());

    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
        ])
        .arg("-o")
        .arg(dir.path().join("pattern_gated.rmeta"))
        .arg("--cfg")
        .arg(r#"feature="validate-pattern""#)
        .arg("--extern")
        .arg(format!("ridl_rt={}", ridl_rt.display()))
        .arg("--extern")
        .arg(format!("regex={}", regex.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "the validate-pattern block must compile against the regex stand-in, source:\n{source}"
    );
}

/// The pattern check is compiled **and run**, with the feature enabled.
///
/// `pattern_check_compiles_under_validate_pattern_against_a_regex_stand_in`
/// stops at `--emit metadata`, so it type-checks the gated block and never
/// evaluates it. Two things the emitter can get wrong survive that: the
/// polarity of the test (`if !PATTERN.is_match(…)` inverted to
/// `if PATTERN.is_match(…)` still type-checks), and the stripping of the
/// pattern's `/` delimiters (emitting `"/ABC/"` is a valid regex source that
/// simply never matches, so every `new` would reject every value). Both leave
/// every string assertion in this file green, so only an executed assertion
/// catches them.
///
/// The stand-in's `Regex::new` refuses a delimiter-carrying pattern and its
/// `is_match` compares for equality, so `Code::new("ABC")` must be accepted
/// and `Code::new("XYZ")` must be refused with `Rule::Pattern`. Both values
/// are three characters, which is exactly the declared length bound, so the
/// length checks cannot be what decides either case.
#[test]
fn the_generated_pattern_check_runs() {
    let source = format!(
        "{}\n{}",
        rust_for(vec![literal_pattern_decl()]),
        r#"
fn main() {
    // The matching value. If the emitted test were inverted, this would be
    // refused; if the delimiters were left on the pattern, the stand-in's
    // `new` would return `Err` and the `expect` in the generated code would
    // panic before this line.
    match Code::new(String::from("ABC")) {
        Ok(c) => assert_eq!(c.get(), "ABC"),
        Err(v) => panic!("ABC matches the pattern, got {:?}", v.rule),
    }
    // The non-matching value, the same length as the matching one, so the
    // length bounds cannot be what refuses it.
    match Code::new(String::from("XYZ")) {
        Err(v) => assert_eq!(v.rule, ::ridl_rt::payload::Rule::Pattern),
        Ok(_) => panic!("XYZ does not match the pattern"),
    }
    // A value outside the length bound is still refused on length, which
    // proves the ungated checks survive with the feature enabled.
    match Code::new(String::from("ABCD")) {
        Err(v) => assert_eq!(v.rule, ::ridl_rt::payload::Rule::Length),
        Ok(_) => panic!("ABCD is outside the declared length bound"),
    }
}
"#
    );

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("pattern_run.rs");
    let bin_path = dir.path().join("pattern_run");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let ridl_rt = ridl_rt_rlib(dir.path());
    let regex = regex_stub_rlib(dir.path());

    let status = std::process::Command::new("rustc")
        .args(["--edition", "2024", "--crate-type", "bin"])
        .arg("-o")
        .arg(&bin_path)
        .arg("--cfg")
        .arg(r#"feature="validate-pattern""#)
        .arg("--extern")
        .arg(format!("ridl_rt={}", ridl_rt.display()))
        .arg("--extern")
        .arg(format!("regex={}", regex.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "the gated pattern check must compile as a program, source:\n{source}"
    );

    let run = std::process::Command::new(&bin_path)
        .output()
        .expect("the compiled program runs");
    assert!(
        run.status.success(),
        "the generated pattern check must behave as declared, stderr:\n{}",
        String::from_utf8_lossy(&run.stderr)
    );
}

/// A literal pattern on a `bytes` backing emits no pattern check at all: a
/// `Vec<u8>` value does not type-check against `regex::Regex::is_match`
/// (`&str`). The length checks are unaffected.
#[test]
fn bytes_backed_pattern_emits_no_pattern_check() {
    let source = rust_for(vec![bytes_pattern_decl()]);
    assert!(
        !source.contains("::ridl_rt::payload::Rule::Pattern"),
        "a bytes backing must emit no pattern check, got:\n{source}"
    );
    assert!(
        !source.contains("#[cfg(feature = \"validate-pattern\")]"),
        "a bytes backing must emit no feature-gated block, got:\n{source}"
    );
    assert!(
        !source.contains("::regex::"),
        "a bytes backing must name no regex engine, got:\n{source}"
    );
    assert!(
        source.contains("::ridl_rt::payload::Rule::Length"),
        "the length bound is still checked, got:\n{source}"
    );
}

/// The doc for a bytes-backed pattern must not claim the feature-gated
/// guarantee it does not implement: since `constraint_checks` emits no
/// pattern branch for this backing, the type must carry the plain "not
/// checked" line instead.
///
/// This is about an IR the backend did not lower, not about a typl source.
/// A bytes type written with a `match` reaches the backend with no pattern
/// at all, so `unchecked_doc` emits no line for it whatsoever; see
/// [`bytes_pattern_decl`]. The behaviour pinned here is that a pattern
/// arriving on a backing the check cannot cover is described accurately
/// rather than advertised as gated.
#[test]
fn bytes_backed_pattern_is_named_as_unchecked_not_feature_gated() {
    let source = rust_for(vec![bytes_pattern_decl()]);
    assert!(
        source.contains(" The `match` pattern is not checked by `new`."),
        "a bytes-backed pattern must be named plainly unchecked, got:\n{source}"
    );
    assert!(
        !source.contains("validate-pattern"),
        "a bytes-backed pattern must not name the feature it is not gated on, got:\n{source}"
    );
}

/// A deprecated declaration's own impl blocks use the deprecated type, which
/// would draw the `deprecated` lint in the consumer's build about code the
/// consumer did not write.
#[test]
fn a_deprecated_scalar_allows_deprecated_on_its_impls() {
    let source = rust_for(vec![v2::Decl {
        deprecated: Some("use Velocity".to_string()),
        ..speed_decl()
    }]);
    // The inherent impl and the two trait impls. This is a lower bound, not an
    // exact total: `defaults.rs` emits a `Default` impl that still draws the
    // lint, and closing that gap must not fail this test.
    assert!(
        source.matches("#[allow(deprecated)]").count() >= 3,
        "each generated impl of a deprecated type allows the lint, got:\n{source}"
    );
    // The comparison is against the same declaration undeprecated, not against
    // zero: the codec allows the lint on every item it writes, deprecated or
    // not, and ADR-0019 decision 8 gave a named scalar codec items of its own.
    let plain = rust_for(vec![speed_decl()]);
    assert!(
        source.matches("#[allow(deprecated)]").count()
            >= plain.matches("#[allow(deprecated)]").count() + 3,
        "a type that is not deprecated allows the lint only where the codec does, got:\n{plain}"
    );
}

/// A `boolean` type is vacuous, so it has no `new_unchecked`; its `new` is
/// `const` and infallible, and a constant constructs through that instead
/// (`scalar_ctor`).
#[test]
fn a_boolean_constant_constructs_through_new() {
    let decls = vec![
        public_decl(
            "Flag",
            primitive_type(
                v2::PrimitiveType::Boolean,
                init_value(true, Some("false")),
                None,
            ),
        ),
        public_decl(
            "ENABLED",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some("Flag".to_string()),
                value: "true".to_string(),
                regex: None,
            }),
        ),
    ];
    let source = rust_for(decls);
    assert!(
        source.contains("pub const ENABLED: Flag = Flag::new(true);"),
        "a boolean constant constructs through new, got:\n{source}"
    );
}

/// A typl type name is CamelCase (typl §15.1) and `ridl-sem` reserves no
/// identifier, so a package may declare `type Result`, `type Ok`, `type Err`,
/// `type TryFrom` or `type From`. Each is a struct in the same module as the
/// generated constructors, where it shadows the prelude name; the constructors
/// must therefore name the five by absolute path. A `rustc` run is the proof:
/// with `pub struct Result(i64);` in scope, an unqualified `Result<Self, _>`
/// fails with E0107.
#[test]
fn prelude_names_declared_by_the_package_compile() {
    let mut decls: Vec<v2::Decl> = ["Result", "Ok", "Err", "TryFrom", "From"]
        .into_iter()
        .map(|name| {
            public_decl(
                name,
                primitive_type(
                    v2::PrimitiveType::Integer,
                    init_value(true, Some("0")),
                    Some(v2::type_def::Width::IntWidth(v2::IntWidth::I32 as i32)),
                ),
            )
        })
        .collect();
    decls.push(speed_decl());
    let rust_source = rust_for(decls);

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("prelude_names.rs");
    std::fs::write(&source_path, &rust_source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
        ])
        .arg("-o")
        .arg(dir.path().join("prelude_names.rmeta"))
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "a package declaring the prelude's names must compile, source:\n{rust_source}"
    );
}

#[test]
fn constants_all_forms() {
    let decls = vec![
        speed_decl(),
        public_decl(
            "MAX_SPEED",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some("Speed".to_string()),
                value: "250.0".to_string(),
                regex: None,
            }),
        ),
        public_decl(
            "MAX_GEAR",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some("integer".to_string()),
                value: "6".to_string(),
                regex: None,
            }),
        ),
        public_decl("Greeting", bounded_string_type(init_value(true, Some("")))),
        public_decl(
            "BANNER",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some("Greeting".to_string()),
                value: "hello".to_string(),
                regex: None,
            }),
        ),
        public_decl(
            "VIN_PATTERN",
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: None,
                value: String::new(),
                regex: Some("^[A-HJ-NPR-Z0-9]{17}$".to_string()),
            }),
        ),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn struct_with_optional_and_reserved() {
    // A struct that mixes a normal field, a reserved tombstone (occupies an
    // ordinal, emits no field), and an optional field.
    let struct_def = v2::StructDef {
        members: vec![
            field_member(named_field(
                "name",
                1,
                "Label",
                false,
                init_value(false, None),
            )),
            reserved_member(2, "legacyChecksum"),
            field_member(named_field(
                "speed",
                3,
                "Speed",
                false,
                init_value(true, None),
            )),
            field_member(named_field(
                "override",
                4,
                "Speed",
                true,
                init_value(true, None),
            )),
        ],
        fixed_layout: false,
    };
    let decls = vec![
        speed_decl(),
        public_decl(
            "Label",
            // A match-constrained string is not derivable.
            bounded_string_type(init_value(false, None)),
        ),
        public_decl("DriverProfile", v2::decl::Kind::StructDef(struct_def)),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

/// One struct with one named field, for the name-projection tests.
fn struct_with_field(name: &str, field_name: &str, type_ref: &str) -> v2::Decl {
    public_decl(
        name,
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(named_field(
                field_name,
                1,
                type_ref,
                false,
                init_value(true, None),
            ))],
            fixed_layout: false,
        }),
    )
}

/// typl §15.1 makes field names camelCase, so an untransformed name draws
/// `non_snake_case` at every consumer of the generated module. The field name
/// goes through the pinned transform (ADR-0016 decisions 1 and 2).
///
/// Two sites project the name, and the assertions discriminate them: the
/// struct declaration in `emit_field`, and the `Default` initializer in
/// `struct_default`. Projecting one and not the other is worse than
/// projecting neither — the initializer would name a field the struct does
/// not have, which is E0560 — so the negative assertion is that the written
/// name appears nowhere at all, rather than that one particular line is
/// absent.
#[test]
fn a_struct_field_name_is_projected_to_snake_case() {
    let source = rust_for(vec![
        speed_decl(),
        struct_with_field("Reading", "sensorId", "Speed"),
    ]);
    assert!(source.contains("pub sensor_id:"), "got:\n{source}");
    assert!(
        source.contains("sensor_id: Speed::default()"),
        "the `Default` initializer must name the projected field, got:\n{source}"
    );
    assert!(
        !source.contains("sensorId"),
        "the written name must reach no generated site, got:\n{source}"
    );
}

#[test]
fn enum_with_discriminants() {
    let decls = vec![public_decl(
        "GearPosition",
        v2::decl::Kind::EnumDef(v2::EnumDef {
            values: vec![
                enum_value("PARK", 0),
                enum_value("DRIVE", 1),
                enum_value("REVERSE", 2),
                enum_value("NEUTRAL", 3),
            ],
            reserved: Vec::new(),
        }),
    )];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn enumset_standalone_form() {
    let decls = vec![public_decl(
        "WarningFlags",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: None,
            bits: warning_bits(),
            width: v2::IntWidth::U8 as i32,
        }),
    )];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn enum_converts_from_a_raw_discriminant() {
    let source = rust_for(vec![gear_position_decl()]);
    assert!(source.contains("impl ::core::convert::TryFrom<i64> for GearPosition"));
    assert!(source.contains("impl ::core::convert::From<GearPosition> for i64"));
    assert!(source.contains("::ridl_rt::payload::Rule::Variant"));
    // Each arm carries the declared discriminant, not the variant's position.
    // Asserting one arm of the gap is what distinguishes the two: over a
    // fixture numbered contiguously from zero, arms built from the position
    // emit identical source.
    assert!(
        source.contains("7 => ::core::result::Result::Ok(Self::REVERSE)"),
        "the arm maps the declared discriminant, got:\n{source}"
    );
}

#[test]
fn enum_set_rejects_bits_outside_the_declared_mask() {
    let source = rust_for(vec![features_decl()]);
    assert!(source.contains("impl ::core::convert::TryFrom<i64> for Features"));
    // The declared bits are positions 0 to 3, so the mask is 0b1111. The
    // value is asserted rather than the constant's presence: a fold that
    // ORed the bit positions instead of shifting by them would still emit a
    // `DECLARED_MASK`, and would still pass a presence check.
    assert!(
        source.contains("const DECLARED_MASK: i64 = 15"),
        "the mask is the union of the declared bits, got:\n{source}"
    );
}

#[test]
fn a_bit_position_outside_the_int64_domain_does_not_panic_codegen() {
    // `ridl-sem` reports TYPL-111 for a position outside 0..=63 and still
    // carries the bit into the IR, so codegen is handed one. Folding it into
    // the mask would shift by 64 and panic in a debug build; codegen is
    // total, so the bit contributes nothing and the checker's diagnostic is
    // what reports it.
    let source = rust_for(vec![public_decl(
        "Odd",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: None,
            bits: vec![
                enum_value("IN_DOMAIN", 1),
                enum_value("TOO_HIGH", 64),
                enum_value("NEGATIVE", -1),
            ],
            width: v2::IntWidth::U8 as i32,
        }),
    )]);
    assert!(
        source.contains("const DECLARED_MASK: i64 = 2"),
        "only the in-domain bit reaches the mask, got:\n{source}"
    );
}

#[test]
fn the_highest_declared_bit_is_in_domain() {
    // Bit 63 is the highest position the int64 domain admits (typl §9.3), so
    // it belongs in the mask. The domain guard is an inclusive range for this
    // reason: an exclusive one would drop a declared bit, and `TryFrom` would
    // then refuse a value that is in contract.
    let source = rust_for(vec![public_decl(
        "Wide",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: None,
            bits: vec![enum_value("TOP", 63)],
            width: v2::IntWidth::U64 as i32,
        }),
    )]);
    assert!(
        source.contains("const DECLARED_MASK: i64 = -9223372036854775808"),
        "bit 63 is in the mask, got:\n{source}"
    );
}

/// The `#[allow(deprecated)]` branch of `emit_enum` and `emit_enum_set`.
///
/// [`a_deprecated_scalar_allows_deprecated_on_its_impls`] covers
/// `emit_type_def` only. A deprecated enum or enum set reaches neither of the
/// two emitters this exercises, so without this test both branches could be
/// replaced by an empty token stream with nothing failing.
#[test]
fn a_deprecated_enum_and_enum_set_allow_deprecated_on_their_impls() {
    let source = rust_for(vec![
        v2::Decl {
            deprecated: Some("use Gear".to_string()),
            ..gear_position_decl()
        },
        v2::Decl {
            deprecated: Some("use Flags".to_string()),
            ..features_decl()
        },
    ]);
    // The enum's two trait impls, and the enum set's inherent block and two
    // trait impls. A lower bound, not an exact total: `defaults.rs` emits a
    // `Default` impl that still draws the lint, and closing that gap must not
    // fail this test.
    assert!(
        source.matches("#[allow(deprecated)]").count() >= 5,
        "each generated impl of a deprecated enum or enum set allows the lint, got:\n{source}"
    );
    // As above: the codec's own items carry the attribute whatever the
    // declaration says, and decision 8 gave an enum and an enum set some.
    let plain = rust_for(vec![gear_position_decl(), features_decl()]);
    assert!(
        source.matches("#[allow(deprecated)]").count()
            >= plain.matches("#[allow(deprecated)]").count() + 5,
        "declarations that are not deprecated allow the lint only where the codec does, \
         got:\n{plain}"
    );
}

#[test]
fn an_internal_enum_set_keeps_its_visibility_on_every_generated_item() {
    // The mask and the accessor carry the declaration's visibility, as the
    // bit constants do.
    //
    // No lint catches a literal `pub` here. An associated item's effective
    // visibility is capped by the impl's self type, so `pub const` inside an
    // inherent impl of a `pub(crate)` type is accepted in silence — checked
    // with rustc under `-D private-interfaces -D private-bounds`, which exits
    // 0. `private_interfaces` fires on a public field or signature that
    // exposes a private type, which is the driftsys/ridl#161 shape and not
    // this one. This assertion is the only thing that observes the
    // visibility, so do not weaken it on the assumption that the corpus
    // proof's lint flags would catch a regression.
    let source = rust_for(vec![v2::Decl {
        visibility: v2::Visibility::Internal as i32,
        ..features_decl()
    }]);
    assert!(
        source.contains("pub(crate) const DECLARED_MASK"),
        "the mask carries the declaration's visibility, got:\n{source}"
    );
    assert!(
        source.contains("pub(crate) const fn get"),
        "the accessor carries the declaration's visibility, got:\n{source}"
    );
    assert!(
        !source.contains("pub const "),
        "no generated item of an internal enum set is public, got:\n{source}"
    );
}

#[test]
fn enumset_derived_form() {
    // The derived form carries a backing enum name; the checker copies the
    // backing enum's values into `bits`, so the emitted Rust is identical to
    // the standalone form.
    let decls = vec![
        public_decl(
            "Warning",
            v2::decl::Kind::EnumDef(v2::EnumDef {
                values: warning_bits(),
                reserved: Vec::new(),
            }),
        ),
        public_decl(
            "WarningFlags",
            v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
                backing_enum: Some("Warning".to_string()),
                bits: warning_bits(),
                width: v2::IntWidth::U8 as i32,
            }),
        ),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn result_union() {
    let reading = v2::StructDef {
        members: vec![field_member(named_field(
            "value",
            1,
            "Speed",
            false,
            init_value(true, None),
        ))],
        fixed_layout: true,
    };
    let fault = v2::StructDef {
        members: vec![field_member(named_field(
            "code",
            1,
            "Counter",
            false,
            init_value(true, None),
        ))],
        fixed_layout: true,
    };
    let union = v2::UnionDef {
        arms: vec![
            v2::UnionArm {
                name: "ok".to_string(),
                ordinal: 1,
                type_ref: "SensorReading".to_string(),
                doc: "Successful reading".to_string(),
            },
            v2::UnionArm {
                name: "err".to_string(),
                ordinal: 2,
                type_ref: "SensorFault".to_string(),
                doc: String::new(),
            },
        ],
        is_result: true,
        reserved: Vec::new(),
    };
    let decls = vec![
        speed_decl(),
        counter_decl(),
        public_decl("SensorReading", v2::decl::Kind::StructDef(reading)),
        v2::Decl {
            is_error: true,
            ..public_decl("SensorFault", v2::decl::Kind::StructDef(fault))
        },
        public_decl("SensorResult", v2::decl::Kind::UnionDef(union)),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

fn tuple_field(name: &str, type_ref: &str) -> v2::TupleField {
    v2::TupleField {
        name: name.to_string(),
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Named(type_ref.to_string())),
        }),
    }
}

#[test]
fn tuple_field_generates_named_struct() {
    let range = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
                fields: vec![tuple_field("min", "Speed"), tuple_field("max", "Speed")],
            })),
        }),
        ..named_field("range", 1, "", false, init_value(true, None))
    };
    let struct_def = v2::StructDef {
        members: vec![field_member(range)],
        fixed_layout: false,
    };
    let decls = vec![
        speed_decl(),
        public_decl("SensorBounds", v2::decl::Kind::StructDef(struct_def)),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

/// A tuple field name is camelCase in typl exactly as a struct field name is
/// (typl §15.1), and the struct a tuple generates carries it as a Rust field
/// name, so it goes through the same pinned transform (ADR-0016 decisions 1
/// and 2).
///
/// Two sites project it, and the assertions discriminate them: the generated
/// struct in `emit_tuple_struct`, and the `Default` initializer in
/// `tuple_default_expr`. Projecting one and not the other is E0560, so the
/// negative assertion is that the written name reaches no generated site.
///
/// Two tuple field names distinct in typl can still project to one Rust field
/// name. That is unchecked, and rustc rejects the result with E0124 —
/// driftsys/ridl#449.
#[test]
fn a_tuple_field_name_is_projected_to_snake_case() {
    let bounds = shaped_field("range", 1, tuple_of(&[("minSpeed", "Speed")]));
    let decls = vec![
        speed_decl(),
        public_decl(
            "SensorBounds",
            v2::decl::Kind::StructDef(v2::StructDef {
                members: vec![field_member(bounds)],
                fixed_layout: false,
            }),
        ),
    ];
    let source = rust_for(decls);
    assert!(source.contains("pub min_speed:"), "got:\n{source}");
    assert!(
        source.contains("min_speed: Speed::default()"),
        "the `Default` initializer must name the projected field, got:\n{source}"
    );
    assert!(
        !source.contains("minSpeed"),
        "the written name must reach no generated site, got:\n{source}"
    );
}

/// A struct field whose type is `kind`, at `ordinal`.
fn shaped_field(name: &str, ordinal: u32, kind: v2::field_type::Kind) -> v2::Field {
    v2::Field {
        ordinal,
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(kind),
        }),
        ..named_field(name, ordinal, "", false, init_value(true, None))
    }
}

/// A tuple type whose fields are the given `(name, type_ref)` pairs.
fn tuple_of(fields: &[(&str, &str)]) -> v2::field_type::Kind {
    v2::field_type::Kind::Tuple(v2::TupleType {
        fields: fields
            .iter()
            .map(|(name, type_ref)| tuple_field(name, type_ref))
            .collect(),
    })
}

/// A tuple under an `internal` declaration generates a **`pub(crate)`** struct,
/// in every typl position that can reach one, and the struct compiles under
/// `-D private-interfaces` (issue #167).
///
/// A tuple is anonymous in source, so the struct it generates has no visibility
/// of its own to declare; before this fix it was fixed at `pub`, which put a
/// `pub(crate)` payload type into a `pub` struct's field. `ridlc check` accepts
/// that source — an `internal` declaration may name `internal` declarations
/// freely (typl §3.3) — so the generated module was the only thing wrong with
/// it, and only rustc could say so.
///
/// **All five typl positions are exercised, not one.** Issue #161 was reported
/// as two positions and turned out to be twenty; a fix verified on the direct
/// field alone would leave the array element, the optional, the map value and
/// the nested tuple emitting `pub`, and every one of them reaches
/// `field_type_tokens` by its own branch. The nested tuple is the one that
/// cannot be found during the declaration walk at all: it is discovered only
/// while emitting the outer tuple's fields, from the flat worklist, which is
/// exactly where the inducing declaration is out of reach.
///
/// The `rustc` run is the proof rather than the string assertions: a snapshot
/// records what was emitted, not that it is valid Rust, and this defect
/// produced output that a plain `rustc` invocation accepts with a warning.
#[test]
fn a_tuple_under_an_internal_declaration_is_package_private() {
    let hidden = v2::Decl {
        visibility: v2::Visibility::Internal as i32,
        ..public_decl(
            "Hidden",
            primitive_type(
                v2::PrimitiveType::Integer,
                init_value(true, Some("0")),
                Some(v2::type_def::Width::IntWidth(v2::IntWidth::U16 as i32)),
            ),
        )
    };
    let holder = v2::StructDef {
        members: vec![
            // 1. a direct tuple field
            field_member(shaped_field("direct", 1, tuple_of(&[("a", "Hidden")]))),
            // 2. a tuple as an array element
            field_member(shaped_field(
                "arr",
                2,
                v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                    element: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(tuple_of(&[("b", "Hidden")])),
                    })),
                    min: 3,
                    max: 3,
                })),
            )),
            // 3. an optional tuple field
            field_member(v2::Field {
                r#type: Some(v2::FieldType {
                    optional: true,
                    kind: Some(tuple_of(&[("c", "Hidden")])),
                }),
                ..shaped_field("opt", 3, tuple_of(&[("c", "Hidden")]))
            }),
            // 4. a tuple as a map value
            field_member(shaped_field(
                "mp",
                4,
                v2::field_type::Kind::Map(Box::new(v2::MapType {
                    key: Some(Box::new(v2::FieldType {
                        optional: false,
                        // A bare `string` map key is lowered with typl
                        // §4.4's `[0..256]` default (driftsys/ridl#459), so
                        // it reaches a backend as an inline scalar.
                        kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
                            backing: Some(v2::Backing {
                                kind: Some(v2::backing::Kind::Primitive(
                                    v2::PrimitiveType::String as i32,
                                )),
                            }),
                            constraint: Some(v2::Constraint {
                                len_max: Some(256),
                                ..Default::default()
                            }),
                            declared_init: None,
                            init: None,
                            width: None,
                        }))),
                    })),
                    value: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(tuple_of(&[("d", "Hidden")])),
                    })),
                    min: 0,
                    max: 4,
                })),
            )),
            // 5. a tuple nested inside a tuple — reached only by draining the
            //    worklist, after the declaration walk has finished.
            field_member(shaped_field(
                "nested",
                5,
                v2::field_type::Kind::Tuple(v2::TupleType {
                    fields: vec![v2::TupleField {
                        name: "e".to_string(),
                        r#type: Some(v2::FieldType {
                            optional: false,
                            kind: Some(tuple_of(&[("f", "Hidden")])),
                        }),
                    }],
                }),
            )),
        ],
        fixed_layout: false,
    };
    // The regression direction, in the same module: a public struct's tuple
    // stays `pub`. Its payload is the public `Counter`, because a public
    // declaration naming an `internal` one is TYPL-005 and never reaches a
    // backend.
    let shown = v2::StructDef {
        members: vec![field_member(shaped_field(
            "direct",
            1,
            tuple_of(&[("g", "Counter")]),
        ))],
        fixed_layout: false,
    };

    let rust_source = rust_for(vec![
        counter_decl(),
        hidden,
        v2::Decl {
            visibility: v2::Visibility::Internal as i32,
            ..public_decl("Holder", v2::decl::Kind::StructDef(holder))
        },
        public_decl("Shown", v2::decl::Kind::StructDef(shown)),
    ]);

    for item in [
        "pub(crate) struct HolderDirect",
        "pub(crate) struct HolderArrElement",
        "pub(crate) struct HolderOpt",
        "pub(crate) struct HolderMpValue",
        "pub(crate) struct HolderNested",
        "pub(crate) struct HolderNestedE",
    ] {
        assert!(
            rust_source.contains(item),
            "a tuple under an `internal` declaration must emit `{item}`, got:\n{rust_source}"
        );
    }
    // `pub(crate) struct X` does not contain `pub struct X`, so these are
    // genuine negatives rather than restatements of the loop above.
    for leaked in [
        "pub struct HolderDirect",
        "pub struct HolderArrElement",
        "pub struct HolderOpt",
        "pub struct HolderMpValue",
        "pub struct HolderNested",
        "pub struct HolderNestedE",
    ] {
        assert!(
            !rust_source.contains(leaked),
            "a tuple under an `internal` declaration must not emit `{leaked}`, \
             got:\n{rust_source}"
        );
    }
    assert!(
        rust_source.contains("pub struct ShownDirect"),
        "a public declaration's tuple must still be `pub`, got:\n{rust_source}"
    );

    // The proof. `private-interfaces` and `private-bounds` are denied by name
    // rather than with a blanket `-D warnings`, matching `rustc_accepts` in
    // `crates/ridlc/tests/corpus.rs`: the generated code carries by-design
    // naming and dead-code lints that say nothing about visibility.
    //
    // `non_snake_case` is denied beside them so that a field name reaching
    // generated Rust verbatim fails this run rather than warning in it. It is
    // inert on this fixture, whose every field name is a single word: the
    // proof that guards issue #243 is `appendix_a_compiles_with_rustc`, whose
    // IR carries `sensorId` and `isOpen`. The deny here is what makes this
    // proof stay a proof if a multi-word field name is ever added to the
    // fixture. An enum variant keeps its typl `SCREAMING_SNAKE` spelling and
    // draws `non_camel_case_types`, a different lint, which stays undenied.
    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("internal_tuple.rs");
    std::fs::write(&source_path, &rust_source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
            "-D",
            "private-interfaces",
            "-D",
            "private-bounds",
            "-D",
            "non_snake_case",
        ])
        .arg("-o")
        .arg(dir.path().join("internal_tuple.rmeta"))
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "a tuple under an `internal` declaration must compile under \
         `-D private-interfaces`, source:\n{rust_source}"
    );
}

fn array_field(name: &str, element: &str, min: u64, max: u64) -> v2::Field {
    v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named(element.to_string())),
                })),
                min,
                max,
            }))),
        }),
        ..named_field(name, 1, "", false, init_value(true, None))
    }
}

#[test]
fn fixed_and_bounded_arrays() {
    let struct_def = v2::StructDef {
        members: vec![
            field_member(array_field("readings", "Speed", 8, 8)),
            field_member(v2::Field {
                ordinal: 2,
                ..array_field("history", "Speed", 2, 8)
            }),
        ],
        fixed_layout: false,
    };
    let decls = vec![
        speed_decl(),
        public_decl("Samples", v2::decl::Kind::StructDef(struct_def)),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn bounded_map() {
    let map_field = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("Counter".to_string())),
                })),
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("Speed".to_string())),
                })),
                min: 0,
                max: 32,
            }))),
        }),
        ..named_field("meta", 1, "", false, init_value(true, None))
    };
    let struct_def = v2::StructDef {
        members: vec![field_member(map_field)],
        fixed_layout: false,
    };
    let decls = vec![
        speed_decl(),
        counter_decl(),
        public_decl("Table", v2::decl::Kind::StructDef(struct_def)),
    ];
    insta::assert_snapshot!(rust_for(decls));
}

#[test]
fn deprecated_and_internal_visibility() {
    let decls = vec![
        v2::Decl {
            deprecated: Some("use Velocity".to_string()),
            ..speed_decl()
        },
        v2::Decl {
            deprecated: Some(String::new()),
            ..public_decl(
                "OldFlag",
                primitive_type(
                    v2::PrimitiveType::Boolean,
                    init_value(true, Some("false")),
                    None,
                ),
            )
        },
        v2::Decl {
            visibility: v2::Visibility::Internal as i32,
            ..public_decl(
                "RawTicks",
                primitive_type(
                    v2::PrimitiveType::Integer,
                    init_value(true, Some("0")),
                    Some(v2::type_def::Width::IntWidth(v2::IntWidth::U32 as i32)),
                ),
            )
        },
    ];
    insta::assert_snapshot!(rust_for(decls));
}

// ---------------------------------------------------------------------------
// Default derivation — the leaf-recursion rule.
// ---------------------------------------------------------------------------

#[test]
fn derivable_scalar_gets_default_with_derived_value() {
    // A numeric type whose range excludes 0 defaults to `min`, not 0.
    let ranged = v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Unit("Cel".to_string())),
        }),
        constraint: Some(constraint(Some("10.0"), Some("40.0"), Some("0.5"))),
        declared_init: None,
        init: Some(init_value(true, Some("10.0"))),
        width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
    });
    let source = rust_for(vec![public_decl("Warm", ranged)]);
    assert!(
        source.contains("impl Default for Warm"),
        "a derivable scalar must get a Default impl, got:\n{source}"
    );
    assert!(
        source.contains("Warm::new_unchecked(10.0)"),
        "the derived init must be the range minimum 10.0, got:\n{source}"
    );
}

#[test]
fn leaf_recursion_denies_default_through_a_composite_field() {
    // The trap: `Outer { inner: Inner }` where `Inner` holds a non-derivable
    // leaf. T15 marks `Outer.inner.init.derivable == true` (a one-level flag),
    // yet neither `Inner` nor `Outer` is Default-constructible, so neither may
    // receive an `impl Default`.
    let inner = v2::StructDef {
        members: vec![field_member(named_field(
            "pattern",
            1,
            "Vin",
            false,
            // A match-constrained string leaf: not derivable.
            init_value(false, None),
        ))],
        fixed_layout: false,
    };
    let outer = v2::StructDef {
        members: vec![field_member(named_field(
            "inner",
            1,
            "Inner",
            false,
            // The one-level composite flag reads derivable despite the leaf.
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let decls = vec![
        public_decl("Vin", bounded_string_type(init_value(false, None))),
        public_decl("Inner", v2::decl::Kind::StructDef(inner)),
        public_decl("Outer", v2::decl::Kind::StructDef(outer)),
    ];
    let source = rust_for(decls);
    assert!(
        !source.contains("impl Default for Inner"),
        "Inner has a non-derivable leaf; it must not get a Default, got:\n{source}"
    );
    assert!(
        !source.contains("impl Default for Outer"),
        "Outer transitively contains a non-derivable leaf; it must not get a Default despite the one-level flag, got:\n{source}"
    );
}

#[test]
fn enumset_default_is_the_empty_set() {
    let source = rust_for(vec![public_decl(
        "WarningFlags",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: None,
            bits: warning_bits(),
            width: v2::IntWidth::U8 as i32,
        }),
    )]);
    assert!(
        source.contains("WarningFlags(0)"),
        "the enumset default must be the empty-set sentinel 0, got:\n{source}"
    );
}

#[test]
fn enum_default_prefers_the_zero_discriminant() {
    // Values start at 5; none is 0, so the default is the lowest declared.
    let source = rust_for(vec![public_decl(
        "Mode",
        v2::decl::Kind::EnumDef(v2::EnumDef {
            values: vec![enum_value("SLOW", 5), enum_value("FAST", 9)],
            reserved: Vec::new(),
        }),
    )]);
    assert!(
        source.contains("Mode::SLOW"),
        "with no zero value the default is the lowest discriminant, got:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// Appendix B — the full typl example.
// ---------------------------------------------------------------------------

/// The typl reference Appendix B package `veh.common`, built as IR v2 with
/// populated init values (T15). Cross-package references to `ridl.std` are
/// fully qualified, as the resolver leaves them (typl §3.2).
#[allow(clippy::vec_init_then_push)]
fn appendix_b() -> v2::Package {
    let mut decls = Vec::new();

    // ---- Units and scalars ----
    decls.push(v2::Decl {
        doc: "Vehicle speed over ground".to_string(),
        ..public_decl("Speed", unit_type("km/h", "0.0", "250.0", "0.5", "0.0"))
    });
    decls.push(v2::Decl {
        doc: "Coolant / ambient temperature".to_string(),
        ..public_decl(
            "Temperature",
            unit_type("Cel", "-40.0", "125.0", "0.1", "0.0"),
        )
    });
    decls.push(v2::Decl {
        doc: "Engine crankshaft speed".to_string(),
        ..public_decl("RPM", unit_type("/min", "0.0", "8000.0", "10.0", "0.0"))
    });
    decls.push(v2::Decl {
        doc: "Normalised ratio".to_string(),
        ..public_decl("Ratio", unit_type("%", "0.0", "100.0", "0.1", "0.0"))
    });
    decls.push(counter_decl());
    decls.push(public_decl(
        "Gain",
        v2::decl::Kind::TypeDef(v2::TypeDef {
            backing: Some(v2::Backing {
                kind: Some(v2::backing::Kind::Primitive(
                    v2::PrimitiveType::Float as i32,
                )),
            }),
            constraint: Some(constraint(Some("0.0"), Some("1.0"), Some("0.01"))),
            declared_init: None,
            init: Some(init_value(true, Some("0.0"))),
            width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
        }),
    ));

    // ---- Constants ----
    for (name, type_ref, value) in [
        ("MAX_SPEED", "Speed", "250.0"),
        ("SPEED_LIMIT_EU", "Speed", "130.0"),
        ("IDLE_RPM", "RPM", "800.0"),
    ] {
        decls.push(public_decl(
            name,
            v2::decl::Kind::ConstDef(v2::ConstDef {
                type_ref: Some(type_ref.to_string()),
                value: value.to_string(),
                regex: None,
            }),
        ));
    }
    decls.push(public_decl(
        "MAX_GEAR",
        v2::decl::Kind::ConstDef(v2::ConstDef {
            type_ref: Some("integer".to_string()),
            value: "6".to_string(),
            regex: None,
        }),
    ));

    // ---- Enums ----
    decls.push(public_decl(
        "GearPosition",
        v2::decl::Kind::EnumDef(v2::EnumDef {
            values: vec![
                enum_value("PARK", 0),
                enum_value("DRIVE", 1),
                enum_value("REVERSE", 2),
                enum_value("NEUTRAL", 3),
            ],
            reserved: Vec::new(),
        }),
    ));
    decls.push(public_decl(
        "Warning",
        v2::decl::Kind::EnumDef(v2::EnumDef {
            values: warning_bits(),
            reserved: Vec::new(),
        }),
    ));
    decls.push(public_decl(
        "WarningFlags",
        v2::decl::Kind::EnumSetDef(v2::EnumSetDef {
            backing_enum: Some("Warning".to_string()),
            bits: warning_bits(),
            width: v2::IntWidth::U8 as i32,
        }),
    ));

    // ---- Composites ----
    decls.push(public_decl(
        "SpeedLimitPayload",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                field_member(named_field(
                    "limit",
                    1,
                    "Speed",
                    false,
                    init_value(true, None),
                )),
                field_member(named_field(
                    "actual",
                    2,
                    "Speed",
                    false,
                    init_value(true, None),
                )),
            ],
            fixed_layout: true,
        }),
    ));

    // gears : integer [0..MAX_GEAR] = 6 (inline scalar with declared init)
    let gears = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
                backing: Some(v2::Backing {
                    kind: Some(v2::backing::Kind::Primitive(
                        v2::PrimitiveType::Integer as i32,
                    )),
                }),
                constraint: Some(constraint(Some("0"), Some("6"), None)),
                declared_init: None,
                init: None,
                width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
            }))),
        }),
        declared_init: Some("6".to_string()),
        ..named_field("gears", 4, "", false, init_value(true, Some("6")))
    };
    decls.push(public_decl(
        "DriverProfile",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                // name : Name — ridl.std, string+match, not derivable.
                field_member(named_field(
                    "name",
                    1,
                    "ridl.std.Name",
                    false,
                    init_value(false, None),
                )),
                field_member(named_field(
                    "speed",
                    2,
                    "Speed",
                    false,
                    init_value(true, None),
                )),
                field_member(named_field(
                    "override",
                    3,
                    "Speed",
                    true,
                    init_value(true, None),
                )),
                field_member(gears),
            ],
            fixed_layout: false,
        }),
    ));

    // SensorBounds
    let range = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
                fields: vec![tuple_field("min", "Speed"), tuple_field("max", "Speed")],
            })),
        }),
        ..named_field("range", 1, "", false, init_value(true, None))
    };
    let readings = v2::Field {
        ordinal: 2,
        ..array_field("readings", "Speed", 8, 8)
    };
    // labels : [Label; 1..16] — Label is ridl.std, not derivable; min 1 makes
    // the field non-derivable.
    let labels = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("ridl.std.Label".to_string())),
                })),
                min: 1,
                max: 16,
            }))),
        }),
        ..named_field("labels", 3, "", false, init_value(false, None))
    };
    let meta = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("ridl.std.Label".to_string())),
                })),
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("ridl.std.Name".to_string())),
                })),
                min: 0,
                max: 32,
            }))),
        }),
        ..named_field("meta", 4, "", false, init_value(true, None))
    };
    decls.push(public_decl(
        "SensorBounds",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                field_member(range),
                field_member(readings),
                field_member(labels),
                field_member(meta),
            ],
            fixed_layout: false,
        }),
    ));

    decls.push(public_decl(
        "SensorResult",
        v2::decl::Kind::UnionDef(v2::UnionDef {
            arms: vec![
                v2::UnionArm {
                    name: "ok".to_string(),
                    ordinal: 1,
                    type_ref: "SensorReading".to_string(),
                    doc: String::new(),
                },
                v2::UnionArm {
                    name: "err".to_string(),
                    ordinal: 2,
                    type_ref: "SensorFault".to_string(),
                    doc: String::new(),
                },
            ],
            is_result: true,
            reserved: Vec::new(),
        }),
    ));

    decls.push(public_decl(
        "SensorReading",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                field_member(named_field(
                    "value",
                    1,
                    "Speed",
                    false,
                    init_value(true, None),
                )),
                // timestamp : Timestamp — ridl.std integer, derivable.
                field_member(named_field(
                    "timestamp",
                    2,
                    "ridl.std.Timestamp",
                    false,
                    init_value(true, None),
                )),
            ],
            fixed_layout: true,
        }),
    ));

    decls.push(v2::Decl {
        is_error: true,
        ..public_decl(
            "SensorFault",
            v2::decl::Kind::StructDef(v2::StructDef {
                members: vec![
                    field_member(named_field(
                        "code",
                        1,
                        "Counter",
                        false,
                        init_value(true, None),
                    )),
                    field_member(named_field(
                        "message",
                        2,
                        "ridl.std.Message",
                        false,
                        init_value(false, None),
                    )),
                ],
                fixed_layout: false,
            }),
        )
    });

    // internal struct RawWheelFrame { ticks : Counter, frame : bytes [8] }
    let frame = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
                backing: Some(v2::Backing {
                    kind: Some(v2::backing::Kind::Primitive(
                        v2::PrimitiveType::Bytes as i32,
                    )),
                }),
                constraint: Some(v2::Constraint {
                    len_min: Some(8),
                    len_max: Some(8),
                    ..constraint(None, None, None)
                }),
                declared_init: None,
                init: None,
                width: None,
            }))),
        }),
        ..named_field("frame", 2, "", false, init_value(false, None))
    };
    decls.push(v2::Decl {
        visibility: v2::Visibility::Internal as i32,
        ..public_decl(
            "RawWheelFrame",
            v2::decl::Kind::StructDef(v2::StructDef {
                members: vec![
                    field_member(named_field(
                        "ticks",
                        1,
                        "Counter",
                        false,
                        init_value(true, None),
                    )),
                    field_member(frame),
                ],
                fixed_layout: false,
            }),
        )
    });

    package("veh.common", decls)
}

#[test]
fn appendix_b_rust_snapshot() {
    let Generated { rust_source, .. } = generate(&appendix_b()).expect("Appendix B generates");
    insta::assert_snapshot!(rust_source);
}

/// Builds `ridl-rt` as an rlib with plain `rustc`, so a compile proof can
/// pass `--extern ridl_rt=<path>` for the generated source that names the
/// runtime.
///
/// Every generated named scalar names `::ridl_rt::payload::Violation` from its
/// `new`, so every compile proof over generated code passes `--extern`;
/// [`the_compile_proof_harness_links_ridl_rt`] checks the helper on its own,
/// with a source that has no other way to fail.
///
/// One `rustc` call over its `lib.rs` is the whole build: `ridl-rt` is
/// `no_std` and has no dependency in any feature combination (ADR-0021
/// decision 8). It is built with the same `rustc` the proof itself spawns; an
/// rlib built by another toolchain is rejected with E0514, which is what
/// happens if this is hoisted to a shared location outside the repository.
///
/// **The three encoding features are enabled here**, which is the proof
/// mechanism E11.7 stage K3 settled. A generated `Payload<E>` implementation
/// names items that a feature gates — `ridl_rt::flatbuffers` is the first —
/// and this rlib is what every compile proof links, so a proof over generated
/// codec code does not compile against a bare build. One `--cfg` argument per
/// encoding is the whole mechanism; the alternative considered was a cargo
/// build of an emitted crate with path dependencies, which costs a manifest,
/// a target directory and a cargo run per proof and still does not build what
/// a consumer outside this repository builds. Enabling all three rather than
/// only `flatbuffers` is so that E11.8 and E11.12 inherit a working proof
/// without editing this helper again.
///
/// Edition 2021 is the edition `crates/ridl-rt/Cargo.toml` declares. The
/// generated code keeps compiling as edition 2024; the two are independent.
fn ridl_rt_rlib(dir: &std::path::Path) -> std::path::PathBuf {
    let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("ridl-rt")
        .join("src")
        .join("lib.rs");
    let rlib = dir.join("libridl_rt.rlib");
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2021",
            "--crate-type",
            "rlib",
            "--crate-name",
            "ridl_rt",
        ])
        .arg("--cfg")
        .arg(r#"feature="flatbuffers""#)
        .arg("--cfg")
        .arg(r#"feature="proto3""#)
        .arg("--cfg")
        .arg(r#"feature="repr-c""#)
        .arg(&source)
        .arg("-o")
        .arg(&rlib)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "ridl-rt must build as an rlib for the compile proofs to see it"
    );
    // An rlib is an `ar` archive. Asserting the magic distinguishes a real
    // rlib from a metadata-only file under the same name, which a proof using
    // `--emit metadata` would accept while nothing that links could.
    let head = std::fs::read(&rlib).expect("the rlib is readable");
    assert!(
        head.starts_with(b"!<arch>\n"),
        "the helper must produce an rlib archive, not metadata under an rlib name"
    );
    rlib
}

/// A hand-written stand-in for the `regex` crate, built as an rlib with plain
/// `rustc` the same way [`ridl_rt_rlib`] builds `ridl-rt`. `regex` is not a
/// declared dependency of any workspace crate (`validate-pattern` names it as
/// an optional dependency only in the crate emitted for a consumer, never
/// here), so the real crate cannot be linked; this stand-in exposes just
/// enough surface for the emitted `#[cfg(feature = "validate-pattern")]`
/// block to type-check: a `Regex` with a fallible `new` and an `is_match`.
///
/// `is_match` takes `&str` and nothing more general (not `&[u8]`, not an
/// `AsRef<str>` bound), so the proof pins the emitted call's argument type
/// rather than accepting whatever the generator produces. Passing the value
/// by move instead of by reference, for instance, fails here.
///
/// It does **not** guard the backing guard in `constraint_checks`. Doing that
/// would need a compile proof over a bytes fixture with the feature on, and
/// no proof here feeds one: both proofs use a `String`-backed fixture, since
/// a bytes fixture emits no gated block to compile. Removing the backing
/// guard is caught by `bytes_backed_pattern_emits_no_pattern_check`, which
/// reads the generated text, not by anything that compiles it.
const REGEX_STAND_IN_SOURCE: &str = r#"
pub struct Regex {
    pattern: String,
}

#[derive(Debug)]
pub struct Error;

impl Regex {
    /// Refuses a pattern that still carries its `/` delimiters. The real
    /// engine accepts `"/ABC/"` — it is a valid regex whose first and last
    /// characters are literal slashes, so it simply never matches a value
    /// that has none — which is why an executed proof needs this refusal to
    /// notice that the emitter stopped stripping them.
    ///
    /// Both ends must be slashes, not either end. `strip_regex_delimiters`
    /// removes one leading and one trailing `/`, so a typl pattern written
    /// `/a\//` strips to `a\/`, which ends in a slash and is correct. A
    /// refusal keyed on either end alone would reject that.
    pub fn new(pattern: &str) -> Result<Regex, Error> {
        if pattern.len() >= 2 && pattern.starts_with('/') && pattern.ends_with('/') {
            return Err(Error);
        }
        Ok(Regex { pattern: pattern.to_string() })
    }

    /// Matches when the text equals the pattern. This is not a regex engine
    /// and does not pretend to be one: it is the smallest predicate that
    /// distinguishes a match from a non-match, which is all an executed
    /// proof of the constructor's polarity needs.
    pub fn is_match(&self, text: &str) -> bool {
        text == self.pattern
    }
}
"#;

fn regex_stub_rlib(dir: &std::path::Path) -> std::path::PathBuf {
    let source_path = dir.join("regex_stand_in.rs");
    std::fs::write(&source_path, REGEX_STAND_IN_SOURCE)
        .expect("the regex stand-in source is written");
    let rlib = dir.join("libregex.rlib");
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "rlib",
            "--crate-name",
            "regex",
        ])
        .arg(&source_path)
        .arg("-o")
        .arg(&rlib)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "the regex stand-in must build as an rlib for the compile proof to link"
    );
    let head = std::fs::read(&rlib).expect("the rlib is readable");
    assert!(
        head.starts_with(b"!<arch>\n"),
        "the helper must produce an rlib archive, not metadata under an rlib name"
    );
    rlib
}

#[test]
fn the_compile_proof_harness_links_ridl_rt() {
    // The harness the compile proofs use. Source naming the runtime by its
    // absolute path must compile against the rlib this helper builds, and
    // must fail without it. Without the second half, a helper that produced
    // an unusable rlib would only be noticed through a proof failing for a
    // reason that says nothing about the generated code.
    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("names_the_runtime.rs");
    std::fs::write(
        &source_path,
        // The shape the generated constructors use: the absolute path, no
        // `use` line, so no name enters the module's namespace.
        r#"
pub struct Speed(pub u16);

impl Speed {
    pub fn new(value: u16) -> Result<Self, ::ridl_rt::payload::Violation> {
        if value > 300 {
            return Err(::ridl_rt::payload::Violation {
                type_name: "Speed",
                rule: ::ridl_rt::payload::Rule::Range,
            });
        }
        Ok(Self(value))
    }
}
"#,
    )
    .expect("the source is written");
    let rlib = ridl_rt_rlib(dir.path());

    let with_extern = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
        ])
        .arg("-o")
        .arg(dir.path().join("with_extern.rmeta"))
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        with_extern.success(),
        "source naming ::ridl_rt::payload::Violation must compile against the helper's rlib"
    );
    // Where it was asked to put it. Without this, a run with no `-o` would
    // also exit zero, writing its output into the package directory instead.
    assert!(
        dir.path().join("with_extern.rmeta").exists(),
        "the proof's output must land in its own temp directory"
    );

    // Captured, so the expected failure does not print an error into an
    // otherwise passing test run.
    let without_extern = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
        ])
        .arg("-o")
        .arg(dir.path().join("without_extern.rmeta"))
        .arg(&source_path)
        .output()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        !without_extern.status.success(),
        "without --extern the same source must fail, or the proof proves nothing"
    );
    // And it must fail because `ridl_rt` is not linked, rather than because
    // the source above has a mistake in it, which would pass this test while
    // proving nothing about the rlib. The check is on the error code, not on
    // the crate name: `rustc` echoes the offending source line into its
    // diagnostic, so `ridl_rt` appears in stderr for any error whose span
    // falls on that line.
    let stderr = String::from_utf8_lossy(&without_extern.stderr);
    assert!(
        stderr.contains("E0433"),
        "the failure must be the unresolved crate, got:\n{stderr}"
    );
}

#[test]
fn the_harness_rlib_belongs_to_its_caller() {
    // Two callers must get two files, each under the directory it passed.
    // `cargo test` runs the compile proofs in parallel threads, so a helper
    // writing to one shared path would have two `rustc` processes writing one
    // file while a third read it.
    let first = tempfile::tempdir().expect("a temp dir is created");
    let second = tempfile::tempdir().expect("a temp dir is created");
    let first_rlib = ridl_rt_rlib(first.path());
    let second_rlib = ridl_rt_rlib(second.path());

    assert_ne!(first_rlib, second_rlib);
    assert!(first_rlib.starts_with(first.path()));
    assert!(second_rlib.starts_with(second.path()));
    assert!(first_rlib.exists() && second_rlib.exists());
}

/// The generated Rust for the full Appendix B package compiles with `rustc`.
/// A minimal prelude stands in for the `ridl.std` types the package imports,
/// declared in the module path the cross-package references map to. The temp
/// directory is removed on drop, closing the #102 temp-file leak.
#[test]
fn appendix_b_compiles_with_rustc() {
    let Generated { rust_source, .. } = generate(&appendix_b()).expect("Appendix B generates");

    // The stand-in types carry the three derives every generated type carries
    // (design decision 7), because that is what the real `ridl.std` package
    // generates. Without them the proof fails on the stand-in rather than on
    // the code under test: a struct with a cross-package field still derives
    // `Debug`, `Clone` and `PartialEq`, and those three reach the field's type.
    // The conditional derives are deliberately absent here — a cross-package
    // reference disables them on this side, so the proof would not notice if
    // the stand-in had them.
    const PRELUDE: &str = "\
pub mod ridl {
    pub mod std {
        #[derive(Debug, Clone, PartialEq)]
        pub struct Name(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Message(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Label(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Timestamp(pub i64);
        impl Default for Timestamp {
            fn default() -> Self {
                Timestamp(0)
            }
        }
    }
}
";
    let source = format!("{PRELUDE}\n{rust_source}");

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("appendix_b.rs");
    let meta_path = dir.path().join("appendix_b.rmeta");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());

    // `non_snake_case` is denied so that a field name reaching generated Rust
    // verbatim fails this run rather than warning in it — the assertion below
    // is on the exit status, which a warning does not change. It is inert on
    // Appendix B, whose every field name is a single word; the proof that
    // guards issue #243 is `appendix_a_compiles_with_rustc`. The deny here is
    // what makes this proof stay a proof if a multi-word field name is ever
    // added to the fixture. An enum variant keeps its typl `SCREAMING_SNAKE`
    // spelling and draws `non_camel_case_types`, a different lint, which
    // stays undenied.
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
            "-D",
            "non_snake_case",
        ])
        .arg("-o")
        .arg(&meta_path)
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");

    assert!(
        status.success(),
        "generated Rust for Appendix B must compile under `-D non_snake_case`, \
         source:\n{source}"
    );
}

/// The generated conversions are compiled **and run**.
///
/// Every other proof in this file stops at `--emit metadata`, which
/// type-checks the emitted source and never evaluates it. That leaves the
/// semantics of the validating seam resting on the snapshots alone, and the
/// task's own workflow blesses a snapshot with `--accept`, so a wrong
/// emission introduced alongside a right one is written into the `.snap` in
/// the same command and never fails again. Inverting the enum set's mask test
/// to `value & Self::DECLARED_MASK != 0` type-checks, so only an executed
/// assertion catches it.
#[test]
fn the_generated_conversions_run() {
    let source = format!(
        "{}\n{}",
        rust_for(vec![gear_position_decl(), features_decl()]),
        r#"
fn main() {
    // The declared discriminants are 0, 1, 7, 9 — not contiguous, so a
    // conversion keyed on the variant's position would map 7 to nothing.
    match GearPosition::try_from(7) {
        Ok(GearPosition::REVERSE) => {}
        _ => panic!("7 is REVERSE"),
    }
    // 2 is a gap in the declared discriminants, so it is out of contract.
    match GearPosition::try_from(2) {
        Err(v) => assert_eq!(v.rule, ::ridl_rt::payload::Rule::Variant),
        Ok(_) => panic!("2 names no declared variant"),
    }
    assert_eq!(i64::from(GearPosition::NEUTRAL), 9);

    // Bits 0 to 3 are declared, so the mask is 0b1111.
    assert_eq!(Features::DECLARED_MASK, 15);
    // Bits 0 and 2, both declared.
    match Features::try_from(5) {
        Ok(f) => assert_eq!(f.get(), 5),
        Err(_) => panic!("5 carries only declared bits"),
    }
    // Bit 4 is not declared. This is the assertion that fails if the mask
    // test is inverted.
    match Features::try_from(16) {
        Err(v) => assert_eq!(v.rule, ::ridl_rt::payload::Rule::Variant),
        Ok(_) => panic!("16 carries an undeclared bit"),
    }
    // A declared bit on its own is accepted, so the test above is not passing
    // because everything is refused.
    match Features::try_from(8) {
        Ok(f) => assert_eq!(f.get(), 8),
        Err(_) => panic!("8 is the declared bit 3"),
    }
    assert_eq!(i64::from(Features::LOW_FUEL), 1);
}
"#
    );

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("conversions.rs");
    let bin_path = dir.path().join("conversions");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());

    let status = std::process::Command::new("rustc")
        .args(["--edition", "2024", "--crate-type", "bin"])
        .arg("-o")
        .arg(&bin_path)
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "the generated conversions must compile, source:\n{source}"
    );

    let run = std::process::Command::new(&bin_path)
        .output()
        .expect("the compiled program runs");
    assert!(
        run.status.success(),
        "the generated conversions must behave as declared, stderr:\n{}",
        String::from_utf8_lossy(&run.stderr)
    );
}

/// A package whose collection fields are Default-constructible, so the array
/// and map default forms (`core::array::from_fn`, range-map collect) are
/// emitted and compiled.
#[test]
fn constructible_collections_compile() {
    let bag = v2::StructDef {
        members: vec![
            field_member(array_field("fixed", "Speed", 3, 3)),
            field_member(v2::Field {
                ordinal: 2,
                ..array_field("bounded", "Speed", 2, 5)
            }),
            field_member(v2::Field {
                r#type: Some(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
                        key: Some(Box::new(v2::FieldType {
                            optional: false,
                            kind: Some(v2::field_type::Kind::Named("Counter".to_string())),
                        })),
                        value: Some(Box::new(v2::FieldType {
                            optional: false,
                            kind: Some(v2::field_type::Kind::Named("Speed".to_string())),
                        })),
                        min: 1,
                        max: 4,
                    }))),
                }),
                ..named_field("pairs", 3, "", false, init_value(true, None))
            }),
        ],
        fixed_layout: false,
    };
    let decls = vec![
        speed_decl(),
        counter_decl(),
        public_decl("Bag", v2::decl::Kind::StructDef(bag)),
    ];
    let Generated { rust_source, .. } = generate(&package("veh.common", decls)).expect("generates");

    assert!(
        rust_source.contains("impl Default for Bag"),
        "Bag with derivable collection fields must get a Default, got:\n{rust_source}"
    );

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("bag.rs");
    let meta_path = dir.path().join("bag.rmeta");
    std::fs::write(&source_path, &rust_source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());
    // `-D non_snake_case` is inert on this fixture, whose every field name is
    // a single word. It is denied for the same reason as in
    // `appendix_b_compiles_with_rustc`: to keep this proof a proof if a
    // multi-word field name is ever added. Issue #243 is guarded by
    // `appendix_a_compiles_with_rustc`.
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
            "-D",
            "non_snake_case",
        ])
        .arg("-o")
        .arg(&meta_path)
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc runs");
    assert!(
        status.success(),
        "the collection default forms must compile under `-D non_snake_case`, \
         source:\n{rust_source}"
    );
}

#[test]
fn keyword_field_name_is_raw_escaped() {
    // `override` is a reserved Rust keyword; it must be emitted as a raw
    // identifier rather than panicking the emitter.
    let struct_def = v2::StructDef {
        members: vec![field_member(named_field(
            "override",
            1,
            "Speed",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let source = rust_for(vec![
        speed_decl(),
        public_decl("Config", v2::decl::Kind::StructDef(struct_def)),
    ]);
    assert!(
        source.contains("r#override"),
        "a keyword field name must be raw-escaped, got:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// Epic E1 whole-epic review — regression fixtures.
// ---------------------------------------------------------------------------

/// C1b: a non-optional self-reference `struct S { next: S }` is a cycle. The
/// checker rejects it (TYPL-206), but the backend must not trust that gate:
/// the Default recursion must terminate rather than overflow the stack.
#[test]
fn recursive_struct_default_terminates() {
    let recursive = v2::StructDef {
        members: vec![field_member(named_field(
            "next",
            1,
            "S",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let generated = generate(&package(
        "veh.common",
        vec![public_decl("S", v2::decl::Kind::StructDef(recursive))],
    ))
    .expect("a cyclic struct's Default derivation must terminate, not overflow");
    assert!(
        !generated.rust_source.contains("impl Default for S"),
        "a cyclic struct must get no Default, got:\n{}",
        generated.rust_source
    );
}

/// I1: `type Plate : string [8..9 match P] = "AA-000-AA"` — the declared init
/// makes the type derivable and IS its default, so the backend emits the
/// declared value, never an empty string.
#[test]
fn declared_string_init_becomes_the_default() {
    let plate = v2::decl::Kind::TypeDef(v2::TypeDef {
        backing: Some(v2::Backing {
            kind: Some(v2::backing::Kind::Primitive(
                v2::PrimitiveType::String as i32,
            )),
        }),
        constraint: Some(v2::Constraint {
            len_min: Some(8),
            len_max: Some(9),
            ..constraint(None, None, None)
        }),
        declared_init: Some("AA-000-AA".to_string()),
        init: Some(init_value(true, Some("AA-000-AA"))),
        width: None,
    });
    let source = rust_for(vec![public_decl("Plate", plate)]);
    assert!(
        source.contains("impl Default for Plate"),
        "a declared-init string type gets a Default, got:\n{source}"
    );
    assert!(
        source.contains("\"AA-000-AA\"") && source.contains("to_string"),
        "the Default must be the declared init, not an empty string, got:\n{source}"
    );
    assert!(
        !source.contains("String::new()"),
        "the empty-string form is only for the derived case, got:\n{source}"
    );
}

/// I2: a cross-package field with a declared init cannot be faithfully wrapped
/// without the remote backing; emitting the referenced type's own default would
/// be a wrong value, so the whole struct gets no Default.
#[test]
fn cross_package_declared_init_omits_the_default() {
    let field = v2::Field {
        declared_init: Some("1".to_string()),
        ..named_field(
            "gearIndex",
            1,
            "veh.other.GearIndex",
            false,
            init_value(true, Some("1")),
        )
    };
    let struct_def = v2::StructDef {
        members: vec![field_member(field)],
        fixed_layout: false,
    };
    let source = rust_for(vec![public_decl(
        "Selection",
        v2::decl::Kind::StructDef(struct_def),
    )]);
    assert!(
        !source.contains("impl Default for Selection"),
        "a struct with a cross-package declared-init field must get no Default, got:\n{source}"
    );
}

/// A `Selection` struct holding one `GearIndex` field whose declared init is
/// the value 1. The `range` argument carries the named type's constraint,
/// which decides whether the wrapping constructor is `new_unchecked` or
/// `new`.
fn selection_with_gear_index(range: Option<v2::Constraint>) -> String {
    let mut gear_kind = primitive_type(
        v2::PrimitiveType::Integer,
        init_value(true, Some("0")),
        Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
    );
    if let v2::decl::Kind::TypeDef(td) = &mut gear_kind {
        td.constraint = range;
    }
    let gear_index = public_decl("GearIndex", gear_kind);
    let field = v2::Field {
        declared_init: Some("1".to_string()),
        ..named_field(
            "gearIndex",
            1,
            "GearIndex",
            false,
            init_value(true, Some("1")),
        )
    };
    let struct_def = v2::StructDef {
        members: vec![field_member(field)],
        fixed_layout: false,
    };
    rust_for(vec![
        gear_index,
        public_decl("Selection", v2::decl::Kind::StructDef(struct_def)),
    ])
}

/// I2: the same-package equivalent CAN be wrapped: the backend knows
/// `GearIndex`'s integer backing, so the declared init 1 wraps to
/// `GearIndex::new_unchecked(1)`.
#[test]
fn same_package_declared_init_gets_the_correct_default() {
    let source = selection_with_gear_index(Some(constraint(Some("0"), Some("8"), None)));
    assert!(
        source.contains("impl Default for Selection"),
        "the same-package equivalent gets a Default, got:\n{source}"
    );
    assert!(
        source.contains("GearIndex::new_unchecked(1)"),
        "the declared init 1 must wrap to GearIndex::new_unchecked(1), got:\n{source}"
    );
}

/// The same wrapping on a vacuous named type. It has no `new_unchecked`
/// (`emit_vacuous_type_def`), so the declared init wraps through its `const
/// fn new` instead — the same substitution `emit_const` makes.
#[test]
fn same_package_declared_init_of_a_vacuous_type_wraps_through_new() {
    let source = selection_with_gear_index(None);
    assert!(
        source.contains("GearIndex::new(1)") && !source.contains("GearIndex::new_unchecked(1)"),
        "the declared init 1 must wrap to GearIndex::new(1), got:\n{source}"
    );
}

/// M1: the IR stores a regex constant's source with its `/…/` delimiters; the
/// emitted `&str` must hold the pattern only.
#[test]
fn regex_const_strips_its_delimiters() {
    let source = rust_for(vec![public_decl(
        "PLATE_PATTERN",
        v2::decl::Kind::ConstDef(v2::ConstDef {
            type_ref: None,
            value: String::new(),
            regex: Some("/^[A-Z]{2}-[0-9]{3}$/".to_string()),
        }),
    )]);
    assert!(
        source.contains("PLATE_PATTERN: &str = \"^[A-Z]{2}-[0-9]{3}$\""),
        "the regex const must emit its pattern without delimiters, got:\n{source}"
    );
    assert!(
        !source.contains("/^[A-Z]"),
        "the surrounding slash delimiters must be stripped, got:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// Identifier totality.
// ---------------------------------------------------------------------------

/// `ident` is total. A valid typl name can never be empty (typl §2.3), so an
/// empty string only reaches here from malformed IR — but the backend is fed
/// by `ridlc::compile`, whose documented contract is that it never panics, and
/// by the language server, which sees IR lowered from in-progress source. An
/// empty name therefore lowers to `_` instead of reaching `Ident::new_raw`,
/// which panics on the empty string.
#[test]
fn ident_is_total_on_the_empty_name() {
    assert_eq!(super::ident("").to_string(), "_");
}

/// A typl name of `_` keeps its own mangling, so the empty-name placeholder
/// can never be confused with a real declaration.
#[test]
fn ident_maps_the_underscore_name_away_from_the_placeholder() {
    assert_eq!(super::ident("_").to_string(), "__");
}

/// The limit of the `_` placeholder, pinned rather than assumed. syn accepts
/// `_` in *field* position, so the `syn::parse2` gate does not catch an
/// empty-named field. A derived `Default` usually catches it instead, because
/// the struct expression it builds has no valid `Member` — but
/// `defaults::struct_default` returns `None` for a non-constructible field (a
/// cross-package reference carrying a declared init), and then nothing is left
/// to catch it and `generate` returns `Ok`.
///
/// This is unreachable from source today: `Parser::block_body` announces a
/// member only on `SyntaxKind::Ident`, so a nameless `FieldDef` is never
/// built. The test exists so that a change making one reachable shows up here
/// rather than as silently emitted Rust.
#[test]
fn generate_emits_an_empty_field_name_without_a_derivable_default() {
    let field = v2::Field {
        name: String::new(),
        ordinal: 1,
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Named("other.pkg.Thing".to_string())),
        }),
        // A declared init on a cross-package reference makes the field
        // non-constructible, so no `Default` is derived.
        declared_init: Some("1".to_string()),
        init: Some(init_value(false, None)),
        doc: String::new(),
        labels: Vec::new(),
        deprecated: None,
    };
    let decls = vec![public_decl(
        "S",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(field)],
            fixed_layout: false,
        }),
    )];
    let generated = generate(&package("app", decls)).expect("the parse gate does not catch `_`");
    assert!(
        generated.rust_source.contains("pub _:"),
        "expected an emitted `_` field, got:\n{}",
        generated.rust_source,
    );
    assert!(
        !generated.rust_source.contains("impl Default for S"),
        "the struct must not derive Default, got:\n{}",
        generated.rust_source,
    );
}

/// An empty-named *declaration* is reported, not emitted. `_` is illegal in a
/// Rust declaration-name position, so the `syn::parse2` gate in `generate`
/// turns it into a `GenerateError` — the codegen totality contract
/// (ADR-0004 §5) holds without the malformed name becoming plausible-looking
/// output.
#[test]
fn generate_reports_an_empty_named_decl_instead_of_panicking() {
    let decls = vec![public_decl(
        "",
        primitive_type(
            v2::PrimitiveType::Boolean,
            init_value(true, Some("false")),
            None,
        ),
    )];
    let error = generate(&package("app", decls)).expect_err("an empty name cannot generate");
    assert!(
        error.message.contains("does not parse"),
        "expected the parse gate to reject `_`, got: {}",
        error.message,
    );
}

// ---------------------------------------------------------------------------
// Interactions and services (E2 task 15) — fixture builders.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Per-kind interaction snapshots.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Appendix A — the ridl reference corpus package `veh.cluster`.
// ---------------------------------------------------------------------------

/// The ridl reference Appendix A package `veh.cluster`, as **`ridl-sem`
/// actually lowers it**.
///
/// The IR is not rebuilt here. It is deserialized from the golden that
/// `ridl-sem` writes for its own `appendix_a_ir` test, so this backend and the
/// lowering that feeds it cannot drift: there is one artifact, and a change in
/// lowering reaches this test the moment that golden is regenerated. A
/// hand-built copy could not do that — it would keep compiling happily while
/// describing an IR the compiler no longer produces, which for the E2 exit
/// criterion's compile proof would make the proof about the fixture rather
/// than about the pipeline.
///
/// Cross-package references to `veh.common` and `ridl.std` stay fully
/// qualified, as the resolver leaves them (typl §3.2).
///
/// One residual is worth recording. The coupling holds as long as the golden is
/// a live artifact: if the `ridl-sem` test that writes it were deleted and the
/// `.snap` file left behind, this loader would keep reading an orphan and keep
/// passing. `cargo insta test --unreferenced` detects exactly that, and it is
/// not in the local gate — adding it is a repo-wide call for the epic
/// close-out, not this backend's to make. Deleting the file outright is caught
/// here immediately, so the gap is narrow: an orphaned snapshot, not a missing
/// one.
fn appendix_a() -> v2::Package {
    // `CARGO_MANIFEST_DIR` is `<workspace>/crates/ridl-backend-rust`.
    let golden = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../ridl-sem/src/snapshots/ridl_sem__check__tests__appendix_a_ir.snap"
    );
    let text = std::fs::read_to_string(golden).unwrap_or_else(|err| {
        panic!(
            "the ridl-sem Appendix A golden must be readable at {golden}: {err}\n\
             this test consumes that crate's lowering rather than a copy of it"
        )
    });

    // An insta snapshot is a YAML header, a `---` line, then the payload.
    let body = text
        .split_once("\n---\n")
        .map(|(_, body)| body)
        .unwrap_or(&text);
    let package = v2::from_json(body)
        .expect("the ridl-sem Appendix A golden deserializes as an IR v2 package");

    // The golden is the whole point, so its shape is asserted rather than
    // assumed: a silently empty or renamed package would turn the compile proof
    // below into a proof about nothing.
    assert_eq!(package.name, "veh.cluster");
    assert_eq!(
        package.interfaces.len(),
        1,
        "Appendix A declares exactly one interface"
    );
    assert!(
        package.services.is_empty(),
        "Appendix A declares no service — services are covered by their own tests"
    );
    package
}

/// The generated Rust for the full Appendix A package compiles with `rustc` —
/// the E2 exit criterion's proof for the Rust half. A minimal prelude stands in
/// for the `veh.common` and `ridl.std` types the package imports, declared in
/// the module path the cross-package references map to.
#[test]
fn appendix_a_compiles_with_rustc() {
    let Generated { rust_source, .. } = generate(&appendix_a()).expect("Appendix A generates");

    // Every stand-in carries the three derives a generated type always
    // carries (design decision 7), because the real packages generate them
    // and the importing package's own derives reach these types through its
    // fields. The conditional ones are left off: a cross-package reference
    // disables them on the importing side, so the proof cannot observe them.
    const PRELUDE: &str = "\
pub mod ridl {
    pub mod std {
        #[derive(Debug, Clone, PartialEq)]
        pub struct Message(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Label(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Version(pub String);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Duration(pub i64);
        #[derive(Debug, Clone, PartialEq, Default)]
        pub struct Timestamp(pub i64);
    }
}
pub mod veh {
    pub mod common {
        #[derive(Debug, Clone, PartialEq)]
        pub struct Speed(pub f64);
        #[derive(Debug, Clone, PartialEq)]
        pub struct Temperature(pub f64);
        #[derive(Debug, Clone, PartialEq)]
        pub struct WarningFlags(pub i64);
        #[derive(Debug, Clone, PartialEq)]
        pub enum GearPosition {
            PARK = 0,
            DRIVE = 1,
        }
    }
}
";
    let source = format!("{PRELUDE}\n{rust_source}");

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("appendix_a.rs");
    let meta_path = dir.path().join("appendix_a.rmeta");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());

    // `non_snake_case` is denied by name, and this is the proof that guards
    // issue #243: the Appendix A IR carries the field names `sensorId` and
    // `isOpen`, so a field name reaching generated Rust verbatim fails this
    // run. The assertion is otherwise on the exit status, which a warning
    // does not change. `non_camel_case_types`, which a screaming-case enum
    // variant draws by design, stays undenied.
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
            "-D",
            "non_snake_case",
        ])
        .arg("-o")
        .arg(&meta_path)
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");

    assert!(
        status.success(),
        "generated Rust for Appendix A must compile under `-D non_snake_case`, \
         source:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// Transport identity inside an inline service shape.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Contract data.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Streams, services, and vocabulary collisions.
// ---------------------------------------------------------------------------

/// A package with no interactions is unaffected by the collision check: the
/// vocabulary is not emitted, so the name is free.
#[test]
fn a_typl_only_package_may_declare_a_vocabulary_name() {
    let source = rust_for(vec![public_decl(
        "Provenance",
        primitive_type(
            v2::PrimitiveType::Integer,
            init_value(true, Some("0")),
            derived_int_width(),
        ),
    )]);
    assert!(source.contains("struct Provenance"), "got:\n{source}");
    assert!(
        !source.contains("enum Provenance"),
        "the vocabulary is not emitted for a typl-only package, got:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// The generated-name classes a package must not collide with.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// What the check must NOT reject: Rust's namespaces genuinely separate these.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Nested tuple names.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Generated names colliding with each other.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// `internal` visibility on the interaction layer (ADR-0008 decision 7).
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// The package-segment spelling shared with `ridlc`'s module tree.
// ---------------------------------------------------------------------------

/// `module_segment` exists so that the module tree `ridlc` writes for
/// `--emit rust` and the paths `type_path` emits cannot drift apart: a tree
/// that spells a segment differently from the reference emits a module the
/// reference cannot name. Nothing pinned that agreement at the definition
/// site, so a change to either side that kept both internally consistent went
/// unnoticed here.
///
/// The segments are the ones that force a spelling. `is_valid_name_segment`
/// accepts any lowercase ASCII segment, so `veh.mod`, `veh.type`, `veh.fn`,
/// `veh.crate`, `veh.self` and `veh.super` are all legal typl package names.
/// `mod`, `type` and `fn` become raw identifiers; `crate`, `self` and `super`
/// cannot be raw identifiers at all and take a trailing underscore instead.
#[test]
fn module_segment_spells_a_segment_the_way_type_path_does() {
    for segment in ["mod", "type", "fn", "crate", "self", "super", "speed"] {
        let rendered = super::type_path(&format!("{segment}.T")).to_string();
        let expected = format!("crate :: {} :: T", super::module_segment(segment));
        assert_eq!(
            rendered, expected,
            "a cross-package reference into `{segment}` and the module tree's spelling of \
             `{segment}` must agree, or the crate root emits a module the reference cannot name"
        );
    }
}

// ---------------------------------------------------------------------------
// Derives (design decision 7, Task 6).
// ---------------------------------------------------------------------------

/// The trait names inside the `#[derive(...)]` attribute that belongs to the
/// item whose rendered header is `header` (for example `pub struct Bag {`).
///
/// The attribute is found by scanning backwards from the header to the nearest
/// `#[derive(`, and the text between that attribute and the header is required
/// to hold nothing but further attributes and doc comments. Without that guard
/// the helper would silently report the *previous* item's derive for an item
/// that carries none, which is exactly the failure mode a negative assertion
/// has to rule out. prettyplease may wrap a long trait list over several
/// lines, so the list is split on commas and each name trimmed rather than
/// compared as one string.
fn derives_of(source: &str, header: &str) -> Vec<String> {
    let header_at = source
        .find(header)
        .unwrap_or_else(|| panic!("`{header}` must be emitted, got:\n{source}"));
    let open = "#[derive(";
    let attr_at = source[..header_at]
        .rfind(open)
        .unwrap_or_else(|| panic!("`{header}` must carry a derive attribute, got:\n{source}"));
    let list_at = attr_at + open.len();
    let close = source[list_at..header_at]
        .find(")]")
        .unwrap_or_else(|| panic!("the derive attribute must close, got:\n{source}"));
    let list = &source[list_at..list_at + close];
    let gap = &source[list_at + close + ")]".len()..header_at];
    for line in gap.lines().map(str::trim).filter(|line| !line.is_empty()) {
        assert!(
            line.starts_with("#[") || line.starts_with("///") || line.starts_with("//"),
            "the derive attribute found for `{header}` belongs to another item; \
             the text between them is:\n{gap}"
        );
    }
    list.split(',')
        .map(|name| name.trim().to_string())
        .filter(|name| !name.is_empty())
        .collect()
}

/// Every generated type carries `Debug`, `Clone` and `PartialEq` — the three
/// that are sound on every backing (design decision 7). Asserted as the
/// positive companion of each negative assertion below.
fn assert_always_derived(derived: &[String], header: &str) {
    for name in ["Debug", "Clone", "PartialEq"] {
        assert!(
            derived.iter().any(|d| d == name),
            "`{header}` must derive {name}, got {derived:?}"
        );
    }
}

#[test]
fn float_backed_scalar_derives_partial_ord_but_not_ord() {
    let source = rust_for(vec![speed_decl()]);
    let derived = derives_of(&source, "pub struct Speed(f64);");
    assert_always_derived(&derived, "Speed");
    // Ord requires Eq, and f64 is neither Eq nor Hash.
    assert_eq!(
        derived,
        ["Debug", "Clone", "Copy", "PartialEq", "PartialOrd"]
    );
}

#[test]
fn integer_backed_scalar_derives_the_full_ordering_set() {
    let source = rust_for(vec![counter_decl()]);
    let derived = derives_of(&source, "pub struct Counter(i64);");
    assert_always_derived(&derived, "Counter");
    assert_eq!(
        derived,
        [
            "Debug",
            "Clone",
            "Copy",
            "PartialEq",
            "Eq",
            "Hash",
            "PartialOrd",
            "Ord"
        ]
    );
}

#[test]
fn string_backed_scalar_is_not_copy() {
    let decls = vec![public_decl(
        "Label",
        bounded_string_type(init_value(true, Some(""))),
    )];
    let source = rust_for(decls);
    let derived = derives_of(&source, "pub struct Label(String);");
    assert_always_derived(&derived, "Label");
    // A String is Eq and Hash but not Copy, and a string backing is not
    // numeric, so it takes no ordering.
    assert_eq!(derived, ["Debug", "Clone", "PartialEq", "Eq", "Hash"]);
}

/// A struct whose transitive closure reaches a float is neither `Eq` nor
/// `Hash`, but is still `Copy` — the two conditions are independent.
#[test]
fn struct_with_a_float_field_is_not_eq() {
    let speed_field = named_field("speed", 1, "Speed", false, init_value(true, None));
    let telemetry = public_decl(
        "Telemetry",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(speed_field)],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![speed_decl(), telemetry]);
    let derived = derives_of(&source, "pub struct Telemetry {");
    assert_always_derived(&derived, "Telemetry");
    assert_eq!(derived, ["Debug", "Clone", "Copy", "PartialEq"]);
}

/// A struct whose closure holds no float is `Eq` and `Hash`. This is the
/// positive companion of [`struct_with_a_float_field_is_not_eq`]: without it,
/// a rule that never emits `Eq` would pass that test.
#[test]
fn struct_over_integers_only_is_eq_and_hash() {
    let count_field = named_field("count", 1, "Counter", false, init_value(true, None));
    let tally = public_decl(
        "Tally",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(count_field)],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), tally]);
    let derived = derives_of(&source, "pub struct Tally {");
    assert_always_derived(&derived, "Tally");
    assert_eq!(
        derived,
        ["Debug", "Clone", "Copy", "PartialEq", "Eq", "Hash"]
    );
}

/// Ordering is a named-scalar property. A struct takes none of it, because
/// ordering a struct's fields lexicographically is not something typl states
/// (design decision 7).
#[test]
fn a_struct_takes_no_ordering() {
    let count_field = named_field("count", 1, "Counter", false, init_value(true, None));
    let tally = public_decl(
        "Tally",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(count_field)],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), tally]);
    let derived = derives_of(&source, "pub struct Tally {");
    // The positive companion: the numeric named scalar in the same package
    // does take both, so an emitter that never emits ordering at all cannot
    // pass this pair.
    let scalar = derives_of(&source, "pub struct Counter(i64);");
    assert!(
        scalar.iter().any(|d| d == "PartialOrd") && scalar.iter().any(|d| d == "Ord"),
        "the numeric named scalar must take both, got {scalar:?}"
    );
    assert!(
        !derived.iter().any(|d| d == "PartialOrd" || d == "Ord"),
        "a struct must take no ordering, got {derived:?}"
    );
}

/// A union takes no ordering either, for the same reason: arm declaration
/// order is not a contract typl states.
#[test]
fn a_union_takes_no_ordering() {
    let arm_struct = |name: &str, field: &str| {
        public_decl(
            name,
            v2::decl::Kind::StructDef(v2::StructDef {
                members: vec![field_member(named_field(
                    field,
                    1,
                    "Counter",
                    false,
                    init_value(true, None),
                ))],
                fixed_layout: false,
            }),
        )
    };
    let union = public_decl(
        "Outcome",
        v2::decl::Kind::UnionDef(v2::UnionDef {
            arms: vec![
                v2::UnionArm {
                    name: "ok".to_string(),
                    ordinal: 1,
                    type_ref: "Reading".to_string(),
                    doc: String::new(),
                },
                v2::UnionArm {
                    name: "err".to_string(),
                    ordinal: 2,
                    type_ref: "Fault".to_string(),
                    doc: String::new(),
                },
            ],
            is_result: true,
            reserved: Vec::new(),
        }),
    );
    let source = rust_for(vec![
        counter_decl(),
        arm_struct("Reading", "value"),
        arm_struct("Fault", "code"),
        union,
    ]);
    let derived = derives_of(&source, "pub enum Outcome {");
    assert_always_derived(&derived, "Outcome");
    assert_eq!(
        derived,
        ["Debug", "Clone", "Copy", "PartialEq", "Eq", "Hash"]
    );
}

/// A union whose arm reaches a float loses `Eq` and `Hash` through the arm,
/// which is the recursion working through a union rather than a struct.
#[test]
fn a_union_arm_reaching_a_float_loses_eq() {
    let reading = public_decl(
        "Reading",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(named_field(
                "value",
                1,
                "Speed",
                false,
                init_value(true, None),
            ))],
            fixed_layout: false,
        }),
    );
    let union = public_decl(
        "Outcome",
        v2::decl::Kind::UnionDef(v2::UnionDef {
            arms: vec![v2::UnionArm {
                name: "ok".to_string(),
                ordinal: 1,
                type_ref: "Reading".to_string(),
                doc: String::new(),
            }],
            is_result: false,
            reserved: Vec::new(),
        }),
    );
    let source = rust_for(vec![speed_decl(), reading, union]);
    let derived = derives_of(&source, "pub enum Outcome {");
    assert_always_derived(&derived, "Outcome");
    assert_eq!(derived, ["Debug", "Clone", "Copy", "PartialEq"]);
}

/// An unresolvable cross-package reference disables every conditional derive.
/// An unsound `#[derive(Copy)]` is a hard error in the consumer's build, so
/// the backend cannot be optimistic the way `defaults.rs` is.
#[test]
fn struct_with_a_cross_package_field_drops_conditional_derives() {
    let field = named_field("speed", 1, "veh.other.Speed", false, init_value(true, None));
    let telemetry = public_decl(
        "Telemetry",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(field)],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![telemetry]);
    let derived = derives_of(&source, "pub struct Telemetry {");
    assert_always_derived(&derived, "Telemetry");
    assert_eq!(derived, ["Debug", "Clone", "PartialEq"]);
}

/// A collection field keeps `Eq` but never `Copy`: the emitted Rust is a
/// `Vec`, which is not `Copy`.
#[test]
fn a_collection_field_keeps_eq_and_loses_copy() {
    let bag = public_decl(
        "Bag",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(array_field("counts", "Counter", 2, 8))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), bag]);
    let derived = derives_of(&source, "pub struct Bag {");
    assert_always_derived(&derived, "Bag");
    assert_eq!(derived, ["Debug", "Clone", "PartialEq", "Eq", "Hash"]);
}

/// A reserved tombstone emits no field (typl §7.4), so it constrains nothing.
///
/// The fixture is integer-only on purpose. `struct_with_optional_and_reserved`
/// also holds a tombstone, but it holds a `String` leaf and an `f64` leaf as
/// well, so its struct already meets to no conditional derive and a tombstone
/// that contributed `Eligibility::NONE` would change nothing there. Here the
/// fields alone permit `Copy`, `Eq` and `Hash`, so the tombstone is the only
/// thing that could take them away.
#[test]
fn a_reserved_tombstone_does_not_constrain_the_derives() {
    let ledger = public_decl(
        "Ledger",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                field_member(named_field(
                    "count",
                    1,
                    "Counter",
                    false,
                    init_value(true, None),
                )),
                reserved_member(2, "legacyChecksum"),
                field_member(named_field(
                    "total",
                    3,
                    "Counter",
                    false,
                    init_value(true, None),
                )),
            ],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), ledger]);
    let derived = derives_of(&source, "pub struct Ledger {");
    assert_always_derived(&derived, "Ledger");
    assert_eq!(
        derived,
        ["Debug", "Clone", "Copy", "PartialEq", "Eq", "Hash"],
        "a reserved tombstone must not take a conditional derive away"
    );
}

/// A map field at the given key and value type, holding up to 32 entries.
fn map_field(name: &str, key: &str, value: &str) -> v2::Field {
    let named = |type_ref: &str| {
        Some(Box::new(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Named(type_ref.to_string())),
        }))
    };
    v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: named(key),
                value: named(value),
                min: 0,
                max: 32,
            }))),
        }),
        ..named_field(name, 1, "", false, init_value(true, None))
    }
}

/// A map emits `Vec<(K, V)>`, which is not `Copy` however `Copy` its halves
/// are. The fixture's key and value are both integer-backed, so the leaves
/// alone would permit `Copy`; the map position is what refuses it.
#[test]
fn a_map_field_loses_copy() {
    let table = public_decl(
        "Table",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(map_field("meta", "Counter", "Counter"))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), table]);
    assert!(
        source.contains("Vec<(Counter, Counter)>"),
        "the map must emit the Vec form this test reasons about, got:\n{source}"
    );
    let derived = derives_of(&source, "pub struct Table {");
    assert_always_derived(&derived, "Table");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq", "Eq", "Hash"],
        "a map field must lose Copy and keep the equality pair"
    );
}

/// A map whose value reaches a float loses `Eq` and `Hash`: `f64` has neither,
/// and `Vec<(K, V)>` has them only when both halves do. The key is
/// integer-backed, so the float reaches the struct through the value half
/// alone.
#[test]
fn a_map_whose_value_reaches_a_float_loses_eq() {
    let table = public_decl(
        "Table",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(map_field("meta", "Counter", "Speed"))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![speed_decl(), counter_decl(), table]);
    let derived = derives_of(&source, "pub struct Table {");
    assert_always_derived(&derived, "Table");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq"],
        "a map whose value reaches a float must lose Eq and Hash"
    );
}

/// A map whose **key** reaches a float loses `Eq` and `Hash`, for the same
/// reason the value half does. This is the mirror of
/// [`a_map_whose_value_reaches_a_float_loses_eq`], and it is a separate test
/// because both halves of `eq: key.eq && value.eq` need pinning: with only
/// the value case covered, dropping `key.eq` passes the whole suite.
///
/// The shape is reachable from a typl source. `Checker::lower_map_key`
/// accepts a bare primitive key under TYPL-209, so a float key lowers with no
/// diagnostic, and deriving `Eq` on the resulting `Vec<(f64, Counter)>` would
/// not compile.
#[test]
fn a_map_whose_key_reaches_a_float_loses_eq() {
    let table = public_decl(
        "KeyTable",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(map_field("meta", "Speed", "Counter"))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![speed_decl(), counter_decl(), table]);
    assert!(
        source.contains("Vec<(Speed, Counter)>"),
        "the fixture must emit the map shape it reasons about, got:\n{source}"
    );
    let derived = derives_of(&source, "pub struct KeyTable {");
    assert_always_derived(&derived, "KeyTable");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq"],
        "a map whose key reaches a float must lose Eq and Hash"
    );
}

/// A cyclic IR takes no conditional derive.
///
/// A cycle is TYPL-206 upstream, but this pass does not trust that gate: on a
/// repeat visit it returns `Eligibility::NONE` rather than recursing forever.
/// [`recursive_struct_default_terminates`] pins that the recursion terminates;
/// this pins what it terminates *with*, which a guard returning
/// `Eligibility::ALL` would also satisfy.
#[test]
fn a_cyclic_struct_takes_no_conditional_derives() {
    let recursive = v2::StructDef {
        members: vec![field_member(named_field(
            "next",
            1,
            "S",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let source = rust_for(vec![public_decl("S", v2::decl::Kind::StructDef(recursive))]);
    let derived = derives_of(&source, "pub struct S {");
    assert_always_derived(&derived, "S");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq"],
        "a cycle must refuse every conditional derive"
    );
}

/// A `Stream` position refuses every conditional derive.
///
/// A stream is an interaction-position type (ridl §12.3) and never reaches a
/// struct field in checked IR. The fixture is built by hand to exercise the
/// backend's totality over an IR it did not lower itself: the field emits
/// `()`, and the conservative answer is what the arm returns.
#[test]
fn a_stream_field_takes_no_conditional_derives() {
    let feed = public_decl(
        "Feed",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(shaped_field(
                "items",
                1,
                v2::field_type::Kind::Stream(v2::StreamType {
                    element: Some(v2::stream_type::Element::Primitive(
                        v2::PrimitiveType::String as i32,
                    )),
                }),
            ))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![feed]);
    let derived = derives_of(&source, "pub struct Feed {");
    assert_always_derived(&derived, "Feed");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq"],
        "a stream position must refuse every conditional derive"
    );
}

/// An `Unspecified` field primitive refuses every conditional derive.
///
/// This is the field-primitive path only. An `Unspecified` *backing* never
/// reaches it: `backing_scalar` maps an unspecified primitive backing to
/// [`ScalarBacking::Bytes`], so such a type emits `Vec<u8>` and is
/// `Eq` and `Hash` without being `Copy` — which is what
/// [`string_backed_scalar_is_not_copy`] already covers for the other
/// allocating backing.
///
/// [`ScalarBacking::Bytes`]: super::ScalarBacking::Bytes
#[test]
fn an_unspecified_field_primitive_takes_no_conditional_derives() {
    let hole = public_decl(
        "Hole",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(shaped_field(
                "nothing",
                1,
                v2::field_type::Kind::Primitive(v2::PrimitiveType::Unspecified as i32),
            ))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![hole]);
    let derived = derives_of(&source, "pub struct Hole {");
    assert_always_derived(&derived, "Hole");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq"],
        "an Unspecified field primitive must refuse every conditional derive"
    );
}

/// A **fixed** array refuses `Copy` too, and that is a policy rather than a
/// soundness rule: `[Counter; 4]` is `Copy` in Rust, so deriving it would
/// compile. The backend refuses it anyway, so that `Copy` never depends on the
/// array bounds being equal — a rule no reader of the generated crate could
/// predict from the declaration.
///
/// [`a_collection_field_keeps_eq_and_loses_copy`] covers the bounded form,
/// where `Vec<T>` makes the refusal a soundness rule instead.
#[test]
fn a_fixed_array_field_loses_copy_by_policy() {
    let readings = public_decl(
        "Readings",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(array_field("counts", "Counter", 4, 4))],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![counter_decl(), readings]);
    assert!(
        source.contains("[Counter; 4]"),
        "the array must emit the fixed form this test reasons about, got:\n{source}"
    );
    let derived = derives_of(&source, "pub struct Readings {");
    assert_always_derived(&derived, "Readings");
    assert_eq!(
        derived,
        ["Debug", "Clone", "PartialEq", "Eq", "Hash"],
        "a fixed array must lose Copy even though [T; N] would permit it"
    );
}

/// `Default` is never derived (design decision 8): it comes from the typl init
/// value through `defaults.rs`, which may be a declared `= 0.5` that
/// `#[derive(Default)]` would silently replace with the backing's zero.
///
/// The fixture covers every declaration kind that receives a derive attribute
/// — `type`, `struct`, `enum`, `enum set` and `union` — not just the scalars.
/// `defaults.rs` emits an `impl Default` for several of them, so a rule that
/// derived `Default` on the composites while sparing the scalars would be an
/// easy thing to write and would otherwise go unnoticed here.
#[test]
fn default_is_never_derived() {
    let tally = public_decl(
        "Tally",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(named_field(
                "count",
                1,
                "Counter",
                false,
                init_value(true, None),
            ))],
            fixed_layout: false,
        }),
    );
    let outcome = public_decl(
        "Outcome",
        v2::decl::Kind::UnionDef(v2::UnionDef {
            arms: vec![v2::UnionArm {
                name: "ok".to_string(),
                ordinal: 1,
                type_ref: "Tally".to_string(),
                doc: String::new(),
            }],
            is_result: false,
            reserved: Vec::new(),
        }),
    );
    let source = rust_for(vec![
        speed_decl(),
        counter_decl(),
        features_decl(),
        gear_position_decl(),
        tally,
        outcome,
    ]);
    for header in [
        "pub struct Speed(f64);",
        "pub struct Counter(i64);",
        "pub struct Features(i64);",
        "pub enum GearPosition {",
        "pub struct Tally {",
        "pub enum Outcome {",
    ] {
        let derived = derives_of(&source, header);
        assert!(
            !derived.iter().any(|d| d == "Default"),
            "`{header}` must not derive Default, got {derived:?}"
        );
    }
    // The positive companion: the Default the backend does emit is an impl
    // built from the init value, not a derive.
    for emitted in [
        "impl Default for Speed",
        "impl Default for GearPosition",
        "impl Default for Tally",
    ] {
        assert!(
            source.contains(emitted),
            "the init-value Default is still emitted (`{emitted}`), got:\n{source}"
        );
    }
}

/// An induced tuple struct carries its own derive attribute. It has to: the
/// struct that holds it derives `Debug`, `Clone` and `PartialEq`
/// unconditionally, and those derives do not compile unless the tuple struct
/// has them too.
///
/// The fixture is deliberately heterogeneous, and the tuple's answer is
/// deliberately different from its holder's. The tuple is an integer and a
/// float, so it is `Copy` and not `Eq` — neither `Eligibility::ALL` nor
/// `Eligibility::NONE`, so a `tuple_derive_attr` that ignored the eligibility
/// computation and returned a fixed answer could not pass. The holder adds a
/// `String`-backed field, so it is neither `Copy` nor `Eq`, and the two
/// attributes cannot be each other's.
#[test]
fn an_induced_tuple_struct_carries_its_derives() {
    let range = v2::Field {
        r#type: Some(v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
                fields: vec![tuple_field("min", "Counter"), tuple_field("max", "Speed")],
            })),
        }),
        ..named_field("range", 1, "", false, init_value(true, None))
    };
    let label = public_decl("Label", bounded_string_type(init_value(true, Some(""))));
    let bounds = public_decl(
        "Bounds",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![
                field_member(range),
                field_member(named_field(
                    "name",
                    2,
                    "Label",
                    false,
                    init_value(true, None),
                )),
            ],
            fixed_layout: false,
        }),
    );
    let source = rust_for(vec![speed_decl(), counter_decl(), label, bounds]);
    let tuple = derives_of(&source, "pub struct BoundsRange {");
    assert_always_derived(&tuple, "BoundsRange");
    assert_eq!(
        tuple,
        ["Debug", "Clone", "Copy", "PartialEq"],
        "the tuple's own closure is an integer and a float: Copy, not Eq"
    );
    let outer = derives_of(&source, "pub struct Bounds {");
    assert_always_derived(&outer, "Bounds");
    assert_eq!(
        outer,
        ["Debug", "Clone", "PartialEq"],
        "the holder reaches a String as well as a float, so it takes neither"
    );
}

/// An enum set is `Copy`, and that is what lets a struct field holding one be
/// read through a shared reference.
///
/// `get` takes `self` by value (driftsys/ridl#433), so `warnings.flags.get()`
/// behind a `&Warnings` moves out of the borrow and rustc reports E0507
/// unless the enum set is `Copy`. #433 declined to fix that and recorded it as
/// this task's to cover, so the proof is a `rustc` run rather than a string
/// assertion: the string says `Copy` is in the list, the compile says the list
/// is enough.
#[test]
fn an_enum_set_in_a_struct_field_is_readable_through_a_shared_reference() {
    let warnings = public_decl(
        "Warnings",
        v2::decl::Kind::StructDef(v2::StructDef {
            members: vec![field_member(named_field(
                "flags",
                1,
                "Features",
                false,
                init_value(true, None),
            ))],
            fixed_layout: false,
        }),
    );
    let generated = rust_for(vec![features_decl(), warnings]);
    let derived = derives_of(&generated, "pub struct Features(i64);");
    assert_always_derived(&derived, "Features");
    assert!(
        derived.iter().any(|d| d == "Copy"),
        "an enum set must be Copy, got {derived:?}"
    );

    let source = format!(
        "{generated}\n{}",
        r#"
pub fn read_through_a_shared_reference(warnings: &Warnings) -> i64 {
    warnings.flags.get()
}
"#
    );

    let dir = tempfile::tempdir().expect("a temp dir is created");
    let source_path = dir.path().join("enum_set_read.rs");
    let meta_path = dir.path().join("enum_set_read.rmeta");
    std::fs::write(&source_path, &source).expect("the generated source is written");
    let rlib = ridl_rt_rlib(dir.path());
    let status = std::process::Command::new("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--emit",
            "metadata",
        ])
        .arg("-o")
        .arg(&meta_path)
        .arg("--extern")
        .arg(format!("ridl_rt={}", rlib.display()))
        .arg(&source_path)
        .status()
        .expect("rustc must be installed and runnable for this test to be meaningful");
    assert!(
        status.success(),
        "an enum set held in a struct field must be readable through a shared \
         reference, source:\n{source}"
    );
}

/// The derive attribute is placed under the declaration's doc comment, not
/// above it. A naive prepend in `emit_decl` renders it above, which is
/// backwards from how Rust is written everywhere else.
#[test]
fn the_derive_attribute_sits_under_the_doc_comment() {
    let source = rust_for(vec![speed_decl()]);
    let doc_at = source
        .find("/// Vehicle speed over ground")
        .expect("the doc comment is emitted");
    let derive_at = source.find("#[derive(").expect("the derive is emitted");
    assert!(
        doc_at < derive_at,
        "the doc comment must come first, got:\n{source}"
    );
    let repr_at = source
        .find("#[repr(transparent)]")
        .expect("the repr is emitted");
    assert!(
        derive_at < repr_at,
        "the derive must precede the repr, got:\n{source}"
    );
}

// ---------------------------------------------------------------------------
// The FlatBuffers size bound's refusal (design note D-7, stages K4 and K5).
//
// `check_flatbuffers_bound` is called per type by the codec emitter (stage
// K5). These tests call it directly over hand-built IR, because no typl
// source reaches an unbounded type — D-7's diagnostic is totality over the
// IR, not a case a user meets.
// ---------------------------------------------------------------------------

/// Runs the per-type refusal over every declaration of `package`, which is
/// what the codec emitter does one declaration at a time, and returns the
/// first refusal.
fn check_flatbuffers_bounds(package: &v2::Package) -> Result<(), super::GenerateError> {
    let ctx = Ctx::new(package);
    for decl in &package.decls {
        check_flatbuffers_bound(&ctx, package, decl)?;
    }
    Ok(())
}

/// A struct whose only field is a bounded named scalar sizes to a finite
/// buffer: this is the shape the corpus proves after driftsys/ridl#459, and
/// the refusal must not fire on it.
#[test]
fn flatbuffers_bound_accepts_a_bounded_struct() {
    let holder = v2::StructDef {
        members: vec![field_member(named_field(
            "speed",
            1,
            "Speed",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![
            speed_decl(),
            public_decl("Holder", v2::decl::Kind::StructDef(holder)),
        ],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a struct with only bounded fields must not be refused"
    );
}

/// A bare `string` map key with no length bound has no finite FlatBuffers
/// size — [`ridl_ir::projection::flatbuffers::max_size`]'s own doc lists it
/// first among the `None` cases, and
/// `ridl_ir::projection::flatbuffers::tests::a_bare_string_map_key_has_no_bound`
/// pins the fact this test pins the refusal over. typl never hands the
/// compiler one: §4.4–§4.5 default a bare `string` or `bytes` at a map key to
/// `[0..256]` (TYPL-103, driftsys/ridl#459), so this is IR built directly,
/// the same as every other fixture in this module that documents "the
/// checker rejects this, but the backend must not trust that gate".
#[test]
fn flatbuffers_bound_refuses_a_bare_string_map_key() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "byId",
            1,
            v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Primitive(
                        v2::PrimitiveType::String as i32,
                    )),
                })),
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Primitive(
                        v2::PrimitiveType::Boolean as i32,
                    )),
                })),
                min: 0,
                max: 8,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("a bare string map key has no bound");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "the refusal must name the package, the declaration, and the member"
    );
}

/// The unbounded member is named even when a sibling member is one this
/// backend cannot judge: the cross-package exemption is per-member, not
/// per-declaration, so it must not swallow a genuine refusal over another
/// member of the same struct.
#[test]
fn flatbuffers_bound_names_the_unbounded_member_beside_an_exempt_one() {
    let holder = v2::StructDef {
        members: vec![
            field_member(shaped_field(
                "byId",
                1,
                v2::field_type::Kind::Map(Box::new(v2::MapType {
                    key: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::String as i32,
                        )),
                    })),
                    value: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::Boolean as i32,
                        )),
                    })),
                    min: 0,
                    max: 8,
                })),
            )),
            field_member(named_field(
                "speed",
                2,
                "veh.other.Speed",
                false,
                init_value(true, None),
            )),
        ],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg)
        .expect_err("the unbounded member must still be refused beside an exempt one");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "the cross-package field must not exempt the whole declaration"
    );
}

/// The reverse order: the exempt member comes first in declaration order,
/// which must not short-circuit the walk before the unbounded member is
/// reached.
#[test]
fn flatbuffers_bound_names_the_unbounded_member_after_an_exempt_one() {
    let holder = v2::StructDef {
        members: vec![
            field_member(named_field(
                "speed",
                1,
                "veh.other.Speed",
                false,
                init_value(true, None),
            )),
            field_member(shaped_field(
                "byId",
                2,
                v2::field_type::Kind::Map(Box::new(v2::MapType {
                    key: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::String as i32,
                        )),
                    })),
                    value: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::Boolean as i32,
                        )),
                    })),
                    min: 0,
                    max: 8,
                })),
            )),
        ],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg)
        .expect_err("the unbounded member must still be refused after an exempt one");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "declaration order must not change the attribution"
    );
}

/// A union arm that is individually unbounded is named the same way a
/// struct field is.
#[test]
fn flatbuffers_bound_names_the_unbounded_union_arm() {
    // `Reading` is a named scalar, and ADR-0019 decision 8 gives one a box
    // root of its own, so the outer walk in `check_flatbuffers_bounds` now
    // refuses it in its own right too — over the box's `value` field, which
    // `flatbuffers_bound_names_an_unbounded_box_root` covers. What this test
    // isolates is the arm, so the union is declared first and the walk reaches
    // it before the scalar.
    let bad_arm = v2::UnionArm {
        name: "reading".to_string(),
        ordinal: 1,
        type_ref: "Reading".to_string(),
        doc: String::new(),
    };
    let union_def = v2::UnionDef {
        arms: vec![bad_arm],
        is_result: false,
        reserved: Vec::new(),
    };
    let pkg = package(
        "veh.cruise",
        vec![
            public_decl("Outcome", v2::decl::Kind::UnionDef(union_def)),
            public_decl(
                "Reading",
                primitive_type(v2::PrimitiveType::String, init_value(false, None), None),
            ),
        ],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("an unbounded union arm has no bound");
    assert_eq!(
        err.message, "`veh.cruise.Outcome.reading` has no finite FlatBuffers bound",
        "the refusal must name the union's arm"
    );
}

/// A named scalar with **no backing at all** is malformed IR, not an
/// unbounded shape, and the refusal says so.
///
/// This is what the front end leaves behind after a parse error such as
/// `type X:`, and `ridlc::compile` runs the backend even when the front end
/// already reported one — so the message a reader meets beside their parse
/// error should not tell them a length bound is missing. The review of
/// 2026-09-21 found the box branch attributing it as unbounded.
#[test]
fn flatbuffers_bound_names_a_box_root_with_no_backing_as_untyped() {
    let pkg = package(
        "veh.cruise",
        vec![public_decl(
            "X",
            v2::decl::Kind::TypeDef(v2::TypeDef::default()),
        )],
    );

    let err = check_flatbuffers_bounds(&pkg).expect_err("a backing-less named scalar has no bound");
    assert_eq!(
        err.message,
        "`veh.cruise.X.value` carries no type, so `veh.cruise.X` has no FlatBuffers bound",
        "the refusal must say the declaration carries no type, not that it is unbounded"
    );
}

/// A named scalar with no finite bound is refused in its own right, over the
/// `value` field of the box ADR-0019 decision 8 roots it in.
#[test]
fn flatbuffers_bound_names_an_unbounded_box_root() {
    // A bare `string` with no length bound is the one shape `max_size` cannot
    // charge, and the compiler never hands one over (typl §4.4 defaults it to
    // `[0..256]`), so this is totality over IR handed in directly — the same
    // standing every other case of this refusal has.
    let pkg = package(
        "veh.cruise",
        vec![public_decl(
            "Reading",
            primitive_type(v2::PrimitiveType::String, init_value(false, None), None),
        )],
    );

    let err = check_flatbuffers_bounds(&pkg).expect_err("an unbounded box root has no bound");
    assert_eq!(
        err.message, "`veh.cruise.Reading.value` has no finite FlatBuffers bound",
        "the refusal must name the box's own field"
    );
}

/// A same-package cycle is left alone even beside an unrelated bounded
/// member: the cycle exemption is per-member, and it must not stop the walk
/// from checking the rest of the struct's own fields (there are none of
/// concern here, so this pins that the walk does not error over the cycle
/// alone).
///
/// The cycle exemption beside an *unbounded* member is pinned separately, by
/// [`flatbuffers_bound_names_the_unbounded_member_beside_a_cycle`] — the
/// third gap design note §4a left to stage K5.
#[test]
fn flatbuffers_bound_leaves_a_cycle_alone_beside_a_bounded_member() {
    let recursive = v2::StructDef {
        members: vec![
            field_member(named_field("next", 1, "S", false, init_value(true, None))),
            field_member(named_field(
                "speed",
                2,
                "Speed",
                false,
                init_value(true, None),
            )),
        ],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![
            speed_decl(),
            public_decl("S", v2::decl::Kind::StructDef(recursive)),
        ],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a cycle beside a bounded member must not be refused"
    );
}

/// A same-package cycle beside a genuinely unbounded member refuses over the
/// unbounded one and names it. The cycle is exempted, the sibling is not.
///
/// This is the third gap design note §4a carried forward: the path was
/// believed correct and was covered by no test.
#[test]
fn flatbuffers_bound_names_the_unbounded_member_beside_a_cycle() {
    let recursive = v2::StructDef {
        members: vec![
            field_member(named_field("next", 1, "S", false, init_value(true, None))),
            // A bare `string` at a map key, with no length bound: the one
            // shape this module already uses for "unbounded".
            field_member(shaped_field(
                "byId",
                2,
                v2::field_type::Kind::Map(Box::new(v2::MapType {
                    key: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::String as i32,
                        )),
                    })),
                    value: Some(Box::new(v2::FieldType {
                        optional: false,
                        kind: Some(v2::field_type::Kind::Primitive(
                            v2::PrimitiveType::Boolean as i32,
                        )),
                    })),
                    min: 0,
                    max: 8,
                })),
            )),
        ],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("S", v2::decl::Kind::StructDef(recursive))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("the map key has no bound");
    assert_eq!(
        err.message, "`veh.common.S.byId` has no finite FlatBuffers bound",
        "the cycle is exempted and the unbounded sibling is still named"
    );
}

/// An anonymous composite that mixes a leaf this backend cannot judge with
/// one that is genuinely unbounded is refused over the unbounded leaf.
///
/// This is the first gap design note §4a carried forward. The exemption used
/// to answer for the whole member: `member_resolves_locally` reached the
/// cross-package key, said `false`, and the bare `string` value inside the
/// same map was never probed. `judge` now descends into an array, a map and a
/// tuple rather than exempting one whole.
#[test]
fn flatbuffers_bound_names_an_unbounded_leaf_beside_an_unjudgeable_one() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "byId",
            1,
            v2::field_type::Kind::Map(Box::new(v2::MapType {
                // Cross-package: this backend resolves none, so it cannot
                // judge the key.
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
                })),
                // Bare `string`, no length bound: genuinely unbounded.
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Primitive(
                        v2::PrimitiveType::String as i32,
                    )),
                })),
                min: 0,
                max: 8,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg)
        .expect_err("an unbounded leaf beside an unjudgeable one is still unbounded");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "the member is named over its unbounded leaf, not exempted over its unjudgeable one"
    );
}

/// A collection whose **count alone** is unbounded is refused, even when its
/// element is one this backend cannot judge.
///
/// `judge` descends into an anonymous composite, but a collection carries a
/// bound of its own that its elements have nothing to do with:
/// `fb_projection::max_size` charges `count × element` and answers `None`
/// when the total overflows `u64` or exceeds `MAX_ENCODABLE`. A count of
/// 2^40 is over the ceiling at one byte an element, so it is over it
/// whatever the element turns out to be. Answering `Unjudgeable` for the
/// whole position would exempt this silently, while the same field over a
/// local element is refused.
#[test]
fn flatbuffers_bound_names_a_collection_whose_count_alone_is_unbounded() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "readings",
            1,
            v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
                })),
                min: 0,
                // Over `fb_projection::MAX_ENCODABLE` at one byte an element.
                max: 1 << 40,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("the count alone is over the ceiling");
    assert_eq!(
        err.message, "`veh.cruise.Holder.readings` has no finite FlatBuffers bound",
        "the count is judged even though the element is not"
    );
}

/// The same, one level down: an unbounded count inside a collection whose own
/// count is fine. The whole position is probed once over a `boolean` in the
/// element's place, so the inner count is charged through the outer one.
#[test]
fn flatbuffers_bound_names_a_nested_collection_whose_count_alone_is_unbounded() {
    let inner = v2::FieldType {
        optional: false,
        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
            element: Some(Box::new(v2::FieldType {
                optional: false,
                kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
            })),
            min: 0,
            max: 1 << 40,
        }))),
    };
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "grid",
            1,
            v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(inner)),
                min: 0,
                max: 2,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("the inner count is over the ceiling");
    assert_eq!(
        err.message, "`veh.cruise.Holder.grid` has no finite FlatBuffers bound",
        "a nested count is judged the same way"
    );
}

/// A map's entry count is judged on the same footing as an array's.
#[test]
fn flatbuffers_bound_names_a_map_whose_entry_count_alone_is_unbounded() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "byId",
            1,
            v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Key".to_string())),
                })),
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
                })),
                min: 0,
                max: 1 << 40,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("the entry count is over the ceiling");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "a map's entry count is judged even though neither half is"
    );
}

/// The control for the three above: a collection with a count that fits and
/// an element this backend cannot judge stays exempt. Without it, the three
/// would pass for a `judge` that simply stopped exempting a collection.
#[test]
fn flatbuffers_bound_leaves_a_collection_with_a_bounded_count_alone() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "readings",
            1,
            v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
                })),
                min: 0,
                max: 4,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a count that fits leaves the verdict to the element, which is unjudgeable"
    );
}

// The four shapes the review of 2026-09-21's second pass found still exempt:
// each is unbounded by a product of counts, or by a count over a locally
// known element, that a probe of one nesting level at a time never charged.
// `judge` now replaces every unjudgeable leaf by a `boolean` and probes the
// whole position once, so the product is charged (design note §4b).

/// A `boolean`-typed position.
fn boolean_type() -> v2::FieldType {
    v2::FieldType {
        optional: false,
        kind: Some(v2::field_type::Kind::Primitive(
            v2::PrimitiveType::Boolean as i32,
        )),
    }
}

/// A position typed by a reference this backend does not resolve.
fn foreign_type(reference: &str) -> v2::FieldType {
    v2::FieldType {
        optional: false,
        kind: Some(v2::field_type::Kind::Named(reference.to_string())),
    }
}

fn array_type(element: v2::FieldType, max: u64) -> v2::FieldType {
    v2::FieldType {
        optional: false,
        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
            element: Some(Box::new(element)),
            min: 0,
            max,
        }))),
    }
}

/// A struct `veh.cruise.Holder` over the given fields, ordinals in order.
fn holder_over(fields: Vec<(&str, v2::FieldType)>) -> v2::Package {
    let holder = v2::StructDef {
        members: fields
            .into_iter()
            .enumerate()
            .map(|(index, (name, ty))| {
                field_member(v2::Field {
                    ordinal: index as u32 + 1,
                    r#type: Some(ty),
                    name: name.to_string(),
                    ..Default::default()
                })
            })
            .collect(),
        fixed_layout: false,
    };
    package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    )
}

/// `[[veh.other.Speed; 0..2^20]; 0..2^20]`: each count fits on its own and
/// their product does not. Its purely local twin, `[[boolean; 0..2^20];
/// 0..2^20]`, is refused, and this one must be too.
#[test]
fn flatbuffers_bound_names_a_nested_collection_whose_counts_multiply_over_the_ceiling() {
    let pkg = holder_over(vec![(
        "grid",
        array_type(
            array_type(foreign_type("veh.other.Speed"), 1 << 20),
            1 << 20,
        ),
    )]);
    let err = check_flatbuffers_bounds(&pkg).expect_err("the product of the counts is over");
    assert_eq!(
        err.message, "`veh.cruise.Holder.grid` has no finite FlatBuffers bound",
        "the product of two counts is charged even though the element is not judged"
    );
    let local = holder_over(vec![(
        "grid",
        array_type(array_type(boolean_type(), 1 << 20), 1 << 20),
    )]);
    assert_eq!(
        check_flatbuffers_bounds(&local).map_err(|err| err.message),
        Err("`veh.cruise.Holder.grid` has no finite FlatBuffers bound".to_string()),
        "the local twin is refused the same way"
    );
}

/// `map<veh.other.Key, [boolean; 0..2^20]; 0..2^20>`: an unjudgeable key
/// beside a local value whose count, times the entry count, is over.
#[test]
fn flatbuffers_bound_names_a_map_whose_entry_count_times_its_value_count_is_over_the_ceiling() {
    let pkg = holder_over(vec![(
        "byId",
        v2::FieldType {
            optional: false,
            kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(foreign_type("veh.other.Key"))),
                value: Some(Box::new(array_type(boolean_type(), 1 << 20))),
                min: 0,
                max: 1 << 20,
            }))),
        },
    )]);
    let err = check_flatbuffers_bounds(&pkg).expect_err("the entry count times the value is over");
    assert_eq!(
        err.message, "`veh.cruise.Holder.byId` has no finite FlatBuffers bound",
        "a map's entry count is multiplied into its value's own count"
    );
}

/// `[(veh.other.Speed, [boolean; 0..2^31]); 0..4]`: the inner array fits on
/// its own, and four of them exceed `MAX_ENCODABLE`.
#[test]
fn flatbuffers_bound_names_an_array_of_tuples_whose_local_half_is_over_the_ceiling_in_total() {
    let pkg = holder_over(vec![(
        "rows",
        array_type(
            v2::FieldType {
                optional: false,
                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
                    fields: vec![
                        v2::TupleField {
                            name: "speed".to_string(),
                            r#type: Some(foreign_type("veh.other.Speed")),
                        },
                        v2::TupleField {
                            name: "flags".to_string(),
                            r#type: Some(array_type(boolean_type(), 1 << 31)),
                        },
                    ],
                })),
            },
            4,
        ),
    )]);
    let err = check_flatbuffers_bounds(&pkg).expect_err("four inner arrays exceed the ceiling");
    assert_eq!(
        err.message, "`veh.cruise.Holder.rows` has no finite FlatBuffers bound",
        "the outer count is charged over the tuple's locally known half"
    );
}

/// Two local `[boolean; 0..2^31]` members beside one foreign field: each
/// member is bounded on its own, the two together are over the ceiling, and
/// the foreign field must not shield that sum. Without it the pair is
/// refused as an aggregate cause, and with it the pair is refused the same
/// way.
#[test]
fn flatbuffers_bound_names_the_declaration_when_the_aggregate_is_over_beside_a_foreign_member() {
    let aggregate = "`veh.cruise.Holder` has no finite FlatBuffers bound: every member is bounded \
                     on its own and the total is not";
    let with_foreign = holder_over(vec![
        ("a", array_type(boolean_type(), 1 << 31)),
        ("b", array_type(boolean_type(), 1 << 31)),
        ("speed", foreign_type("veh.other.Speed")),
    ]);
    assert_eq!(
        check_flatbuffers_bounds(&with_foreign).map_err(|err| err.message),
        Err(aggregate.to_string()),
        "a foreign member does not shield an aggregate over the ceiling"
    );
    let without = holder_over(vec![
        ("a", array_type(boolean_type(), 1 << 31)),
        ("b", array_type(boolean_type(), 1 << 31)),
    ]);
    assert_eq!(
        check_flatbuffers_bounds(&without).map_err(|err| err.message),
        Err(aggregate.to_string()),
        "the same pair without the foreign member is the aggregate case"
    );
}

/// The control for the four above, in the shape of the first: a nested
/// collection whose counts multiply to something that fits, over the same
/// unjudgeable element, stays exempt. Without it the four would pass for a
/// `judge` that refused every nested collection over a foreign leaf.
#[test]
fn flatbuffers_bound_leaves_a_nested_collection_whose_counts_multiply_under_the_ceiling_alone() {
    let pkg = holder_over(vec![(
        "grid",
        array_type(
            array_type(foreign_type("veh.other.Speed"), 1 << 10),
            1 << 10,
        ),
    )]);
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a product of counts that fits at one byte an element leaves the element unjudged"
    );
}

/// `[veh.other.Speed; 0..2^31]` stays exempt, and that is an honest limit
/// rather than a hole: at one byte an element the count fits, and this
/// backend cannot learn the foreign element's width to say more. It is what
/// the stand-in being a lower bound means — it can prove a position
/// unbounded and never prove one bounded.
#[test]
fn flatbuffers_bound_leaves_a_large_count_over_a_foreign_element_alone_when_one_byte_each_fits() {
    let pkg = holder_over(vec![(
        "readings",
        array_type(foreign_type("veh.other.Speed"), 1 << 31),
    )]);
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a count that fits at one byte an element says nothing about the real element"
    );
}

/// The same shape with **no** unbounded leaf beside the unjudgeable one is
/// still exempt. Without this, the test above would pass for a `judge` that
/// simply stopped exempting anything.
#[test]
fn flatbuffers_bound_leaves_an_unjudgeable_leaf_alone_when_nothing_beside_it_is_unbounded() {
    let holder = v2::StructDef {
        members: vec![field_member(shaped_field(
            "byId",
            1,
            v2::field_type::Kind::Map(Box::new(v2::MapType {
                key: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Named("veh.other.Speed".to_string())),
                })),
                value: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Primitive(
                        v2::PrimitiveType::Boolean as i32,
                    )),
                })),
                min: 0,
                max: 8,
            })),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a cross-package leaf with nothing unbounded beside it is exempt"
    );
}

/// Two members on one ordinal is a layout error over the whole declaration,
/// and it is reported as one: every member probes as bounded, so an
/// attribution that only looked at members would call it an aggregate
/// overflow. The second gap design note §4a carried forward.
#[test]
fn flatbuffers_bound_reports_a_layout_error_over_the_declaration() {
    let holder = v2::StructDef {
        members: vec![
            field_member(named_field("a", 1, "Speed", false, init_value(true, None))),
            field_member(named_field("b", 1, "Speed", false, init_value(true, None))),
        ],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![
            speed_decl(),
            public_decl("Holder", v2::decl::Kind::StructDef(holder)),
        ],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("two members on one ordinal");
    assert!(
        err.message
            .starts_with("`veh.common.Holder` has no FlatBuffers table layout:"),
        "a layout error is told apart from an aggregate overflow, got: {}",
        err.message
    );
    assert!(
        err.message.contains("two struct members with ordinal 1"),
        "the projection's own message is carried through, got: {}",
        err.message
    );
}

/// A member with no type at all is named as such rather than folded into the
/// aggregate case. The second gap design note §4a carried forward, second
/// cause.
#[test]
fn flatbuffers_bound_names_a_member_with_no_type() {
    let holder = v2::StructDef {
        members: vec![field_member(v2::Field {
            r#type: None,
            ..named_field("mystery", 1, "Speed", false, init_value(true, None))
        })],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("a member with no type has no bound");
    assert_eq!(
        err.message,
        "`veh.common.Holder.mystery` carries no type, so `veh.common.Holder` has no FlatBuffers \
         bound",
        "an untyped member is named, and told apart from an aggregate overflow"
    );
}

/// An `Unspecified` field primitive is exempted rather than refused, on the
/// same footing as a `Stream`: both emit `()`, both are charged nothing, and
/// `derives` lists the two side by side among its refusing positions.
#[test]
fn flatbuffers_bound_leaves_an_unspecified_primitive_alone() {
    let hole = v2::StructDef {
        members: vec![field_member(shaped_field(
            "nothing",
            1,
            v2::field_type::Kind::Primitive(v2::PrimitiveType::Unspecified as i32),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("Hole", v2::decl::Kind::StructDef(hole))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "an unspecified field primitive must not be refused"
    );
}

/// A `Stream` field position is left alone, the same as an unresolved
/// reference: it never reaches a struct field in checked IR, and
/// `fb_projection::max_size` charges nothing for it, so a probe would answer
/// `None` for a case this backend does not consider a bound failure.
#[test]
fn flatbuffers_bound_leaves_a_stream_field_alone() {
    let feed = v2::StructDef {
        members: vec![field_member(shaped_field(
            "items",
            1,
            v2::field_type::Kind::Stream(v2::StreamType {
                element: Some(v2::stream_type::Element::Primitive(
                    v2::PrimitiveType::String as i32,
                )),
            }),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("Feed", v2::decl::Kind::StructDef(feed))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a Stream field position must not be refused"
    );
}

/// When every individual member is bounded but their sum exceeds
/// `fb_projection::MAX_ENCODABLE`, the refusal names the declaration alone:
/// there is no single member to attribute an aggregate overflow to.
#[test]
fn flatbuffers_bound_names_the_declaration_when_the_cause_is_aggregate() {
    fn huge_integer_array(name: &str, ordinal: u32) -> v2::StructMember {
        field_member(shaped_field(
            name,
            ordinal,
            v2::field_type::Kind::Array(Box::new(v2::ArrayType {
                element: Some(Box::new(v2::FieldType {
                    optional: false,
                    kind: Some(v2::field_type::Kind::Primitive(
                        v2::PrimitiveType::Integer as i32,
                    )),
                })),
                min: 0,
                max: 300_000_000,
            })),
        ))
    }
    // Each array alone charges roughly 2.4 GB, well under
    // `fb_projection::MAX_ENCODABLE` (`u32::MAX`, ~4.29 GB); the two together
    // charge roughly 4.8 GB, over it.
    let holder = v2::StructDef {
        members: vec![huge_integer_array("a", 1), huge_integer_array("b", 2)],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.cruise",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    let err = check_flatbuffers_bounds(&pkg).expect_err("the summed size exceeds MAX_ENCODABLE");
    assert_eq!(
        err.message,
        "`veh.cruise.Holder` has no finite FlatBuffers bound: every member is bounded on its own \
         and the total is not",
        "an aggregate cause must name the declaration alone, with no member"
    );
}

/// A struct that reaches a cross-package reference is left alone: this
/// backend resolves no cross-package reference itself
/// (`struct_with_a_cross_package_field_drops_conditional_derives` already
/// pins that `generate` still emits one), so `fb_projection::max_size` cannot
/// tell "unresolved here" from "unbounded", and `decl_resolves_locally`
/// answers `false` rather than letting it guess.
#[test]
fn flatbuffers_bound_leaves_a_cross_package_reference_alone() {
    let holder = v2::StructDef {
        members: vec![field_member(named_field(
            "speed",
            1,
            "veh.other.Speed",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("Holder", v2::decl::Kind::StructDef(holder))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a cross-package reference must not be refused: this backend cannot judge it"
    );
}

/// A same-package struct that reaches itself is left alone, the same as a
/// cross-package reference: `recursive_struct_default_terminates` and
/// `a_cyclic_struct_takes_no_conditional_derives` already pin that `generate`
/// still emits `S`'s domain type over exactly this shape, and this refusal
/// must not take that away before K5 has a codec to withhold instead.
#[test]
fn flatbuffers_bound_leaves_a_cycle_alone() {
    let recursive = v2::StructDef {
        members: vec![field_member(named_field(
            "next",
            1,
            "S",
            false,
            init_value(true, None),
        ))],
        fixed_layout: false,
    };
    let pkg = package(
        "veh.common",
        vec![public_decl("S", v2::decl::Kind::StructDef(recursive))],
    );
    assert_eq!(
        check_flatbuffers_bounds(&pkg),
        Ok(()),
        "a same-package cycle must not be refused before K5 has a codec to withhold"
    );
}

/// `generate_with` resolves a reference into another package of the build,
/// and `generate` — which is `generate_with(package, &[])` — does not
/// (driftsys/ridl#467).
///
/// This is the entry point's own guard. Every other test of cross-package
/// resolution goes through the pipeline or through a corpus fixture that
/// happens to name a standard type, so a change to the standard package's
/// shape could take the only coverage away without anything here failing.
///
/// The two halves matter together: the withheld note is what a consumer used
/// to get for every such type, and the point of the story is that it is gone
/// when the other package is in hand.
#[test]
fn generate_with_resolves_a_reference_into_another_package() {
    let foreign = package(
        "px.a",
        vec![public_decl(
            "Point",
            v2::decl::Kind::StructDef(v2::StructDef {
                members: vec![field_member(named_field(
                    "x",
                    1,
                    "Level",
                    false,
                    init_value(true, None),
                ))],
                fixed_layout: false,
            }),
        )],
    );
    // `Level` is the foreign package's own named scalar, so `Point` is a
    // type that only resolves once `px.a` is in hand.
    let mut foreign = foreign;
    foreign.decls.push(public_decl(
        "Level",
        primitive_type(
            v2::PrimitiveType::Integer,
            init_value(true, Some("0")),
            Some(v2::type_def::Width::IntWidth(v2::IntWidth::U16 as i32)),
        ),
    ));

    let local = package(
        "px.b",
        vec![struct_with_field("Line", "from", "px.a.Point")],
    );

    let alone = generate(&local).expect("the package generates").rust_source;
    assert!(
        alone.contains("__RIDL_FB_NO_CODEC"),
        "without the other package the type is withheld a codec, got:\n{alone}"
    );

    let with_others = generate_with(&local, &[&foreign])
        .expect("the package generates against the build")
        .rust_source;
    assert!(
        !with_others.contains("__RIDL_FB_NO_CODEC"),
        "with the other package in hand nothing is withheld, got:\n{with_others}"
    );
    assert!(
        with_others.contains("crate :: px :: a :: PointFbView")
            || with_others.contains("crate::px::a::PointFbView"),
        "the foreign view is named by a path through the module tree, got:\n{with_others}"
    );
}