ridl-core 0.6.0

The RIDL family compiler core: the incremental database, diagnostics, and the package and workspace model.
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
//! The coded diagnostic model every compiler pass emits (ADR-0004 §5, ADR-0007 decision 2).
//!
//! A [`Diagnostic`] is a first-class homegrown value — a stable [`DiagCode`], a
//! [`Severity`], a message, a primary source [`Span`], secondary [`Label`]s, and
//! optional [`FixIt`]s — held as the single source of truth and accumulated in a
//! `Vec`, never modeled as an error return (ADR-0004 §5). The struct maps two
//! ways: to a terminal renderer for the CLI ([`render`](render::render), over
//! `codespan-reporting`) and, in a later epic, to LSP `Diagnostic` for editors.
//!
//! # Namespaces (ADR-0007 decision 2)
//!
//! Codes are grouped by hundreds and never renumbered or reused; a code
//! retired from the `RIDL-` or `TYPL-` catalogue is listed in
//! [`RETIRED_RIDL_CODES`] or [`RETIRED_TYPL_CODES`], and a guard keeps it out.
//! Five namespaces are in play across the family, one catalogue each:
//!
//! - `FORM-…` — the shared family grammar: lexical `0xx`, parse `1xx`, and the
//!   general form §4.3 attribute rules. Named after the general form's own
//!   "shared form namespace". [`FORM_CATALOG`].
//! - `TYPL-…` — typl semantic rules, defined by the typl reference §16.
//!   [`TYPL_CATALOG`].
//! - `RIDL-…` — ridl interaction rules, defined by the ridl reference §16.
//!   [`RIDL_CATALOG`].
//! - `RSDL-…` — rsdl system rules, defined by the rsdl reference §16.
//!   [`RSDL_CATALOG`].
//! - `MANI-…` — manifest, lockfile, cache, and fetch: the manifest `0xx` codes
//!   and the distribution `1xx` codes. [`MANI_CATALOG`].
//!
//! This module is the SSOT the error index reads. Every code is declared
//! once, by [`diag_codes!`], which expands one entry into both the `DiagCode`
//! constant and its catalogue row — a code with no entry cannot be written
//! (ADR-0008 decision 21). A catalogue lists a code even when no pass emits it
//! yet.
//!
//! # The [`FileId`] bridge
//!
//! A [`Span`] locates its range inside a file identified by an interned
//! [`FileId`]. [`SourceMap`] issues those ids: a pass that holds a file's path
//! and text calls [`SourceMap::file_id`] to obtain the id it stamps into its
//! spans. The [`SourceMap`] is the only bridge between a diagnostic and the
//! source text the renderer needs.

use rowan::{TextRange, TextSize};
use serde::{Serialize, Serializer};

pub mod render;
pub mod sarif;

pub use render::render;

/// A stable diagnostic code, e.g. `"FORM-101"` or `"TYPL-108"` (ADR-0007
/// decision 2). The empty string means "no code yet" — a diagnostic that has
/// not been assigned a catalogue code renders as a plain message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct DiagCode(pub &'static str);

impl DiagCode {
    /// The code string.
    pub fn as_str(&self) -> &'static str {
        self.0
    }

    /// Whether this is the sentinel "no code yet" value.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The sentinel for a diagnostic that carries no catalogue code yet, such
    /// as the checker's "expected a type, but `X` names a constant / an
    /// interface" errors (typl §16 defines no code for either) or the Rust
    /// backend's codegen error. A diagnostic carrying it renders with no code
    /// after its severity word (`error:`, `warning:`), and the book harness
    /// can never allow one.
    pub const NONE: DiagCode = DiagCode("");
}

/// Declares every diagnostic code exactly once (ADR-0008 decision 21).
///
/// One entry expands to both the `DiagCode` constant and the [`CatalogEntry`]
/// that names it, so a code with no catalogue entry cannot be written: there is
/// no second list to forget.
///
/// A Warning or Info row ends with `lint = "<name>"`, which becomes
/// [`CatalogEntry::lint`]; a row without it gets `None`. The guard
/// `lint_names_are_present_exactly_on_warnings_and_infos_and_unique` checks
/// which rows carry a name.
///
/// A lint row may follow its name with `default = allow`, which sets
/// [`CatalogEntry::allow_by_default`] (ADR-0024 decision 1). `allow` is the
/// only default a row can declare: any other word is a compile error. The
/// guard `allow_by_default_is_only_on_warning_or_info_rows` checks that only a
/// lint row declares it.
///
/// The macro also generates [`ALL_CATALOGS`], which the guards read to find
/// every catalogue. That makes it invocable only once **per module** — a second
/// invocation beside this one redefines the constant and the crate stops
/// compiling. It does **not** make it invocable once per crate: a second
/// invocation inside a child module of `diag` compiles, and its catalogue is
/// invisible to `ALL_CATALOGS` here. What covers that case is
/// `codes_written_as_string_literals_are_all_catalogued`, and it covers it for a
/// structural reason rather than by luck — `$code:literal` guarantees every code
/// the macro declares is spelled as a literal in a `.rs` file, so a catalogue
/// the guards cannot see still puts its codes where the scan can.
///
/// This replaces the pair of hand-maintained arrays `FORM_CATALOG` and
/// `MANI_CATALOG` carried until E2 close-out, each guarded by a test that
/// compared it against a *second hand-written list inside the test*. That pair
/// checked that two lists agreed; it never checked either against the codes
/// actually declared, so a constant added to neither compiled and turned nothing
/// red. `RIDL` and `TYPL` had no catalogue at all.
///
/// The remedy available in `crates/ridl-diff` — make the guard an exhaustive `match`
/// and let the compiler enforce totality — does not exist here: `DiagCode` is a
/// newtype over `&'static str`, not an enum, so there is no variant set to match
/// on. Declaring the constant and its entry from one line is the shape that
/// works for a newtype.
macro_rules! diag_codes {
    (@lint) => { None };
    (@lint $lint:literal) => { Some($lint) };
    (@allow) => { false };
    (@allow allow) => { true };
    (
        $(
            $(#[$catalog_doc:meta])*
            $catalog:ident {
                $(
                    $(#[$code_doc:meta])*
                    $konst:ident = $code:literal, $severity:ident,
                        $summary:literal $(, lint = $lint:literal $(, default = $default:ident)?)?;
                )+
            }
        )+
    ) => {
        impl DiagCode {
            $($(
                $(#[$code_doc])*
                pub const $konst: DiagCode = DiagCode($code);
            )+)+
        }

        $(
            $(#[$catalog_doc])*
            pub const $catalog: &[CatalogEntry] = &[
                $(CatalogEntry {
                    code: DiagCode::$konst,
                    severity: Severity::$severity,
                    summary: $summary,
                    lint: diag_codes!(@lint $($lint)?),
                    allow_by_default: diag_codes!(@allow $($($default)?)?),
                },)+
            ];
        )+

        /// Every catalogue this module declares, each paired with its constant's
        /// name. The error index reads this rather than naming the
        /// catalogues one at a time, and so do the guards below.
        pub const ALL_CATALOGS: &[(&str, &[CatalogEntry])] = &[
            $((stringify!($catalog), $catalog),)+
        ];

        /// Each constant's name paired with the code string it expands to, so a
        /// guard can check the two agree. Generated rather than written down —
        /// a hand-written copy would be the shadow this macro exists to remove.
        #[cfg(test)]
        const CODE_CONSTANT_NAMES: &[(&str, &str)] = &[
            $($((stringify!($konst), $code),)+)+
        ];
    };
}

/// The `RIDL-` codes retired from the catalogue. A code is never renumbered or
/// reused (ADR-0008 decision 13). The interface lock (lock design §9) retired
/// RIDL-146 to RIDL-148, which guarded the slot model of a service's list — a
/// shape re-declared under a service-level `reserved` name, one interface name on two shapes, and a
/// nameless service-level tombstone — and left the catalogue with that model
/// on 2026-09-15. Held as integers rather than `"RIDL-146"` literals, because
/// a string literal of a code that is in no catalogue fails
/// `codes_written_as_string_literals_are_all_catalogued`; the guard
/// `retired_ridl_codes_are_never_redeclared` keeps the numbers out of
/// [`RIDL_CATALOG`].
///
/// RIDL-415 (`package-fan-out`) was a design-lint calibration candidate that
/// did not ship; its number is retired too.
pub const RETIRED_RIDL_CODES: &[u16] = &[146, 147, 148, 415];

/// The `TYPL-` codes retired without shipping. TYPL-223
/// (`inconsistent-abbreviation`) was a design-lint calibration candidate that
/// the corpus calibration did not ship; its number is never reused.
/// `retired_typl_codes_are_never_redeclared` keeps it out of [`TYPL_CATALOG`].
pub const RETIRED_TYPL_CODES: &[u16] = &[223];

diag_codes! {
    /// The FORM catalogue (ADR-0007 decision 2): lexical `0xx`, parse `1xx`, and
    /// the attribute-semantics codes 106-108 the checker emits for the general
    /// form §4.3 allow-list. Every FORM code is listed even when no pass emits
    /// it yet, so the error index has one authoritative source. FORM diagnostics
    /// are all errors.
    FORM_CATALOG {
        /// Invalid character.
        FORM_001 = "FORM-001", Error,
            "invalid character";

        /// Unterminated string literal.
        FORM_002 = "FORM-002", Error,
            "unterminated string literal";

        /// Unterminated regex literal.
        FORM_003 = "FORM-003", Error,
            "unterminated regex literal";

        /// Unterminated block comment.
        FORM_004 = "FORM-004", Error,
            "unterminated block comment";

        /// Leading zeros in an integer literal.
        FORM_005 = "FORM-005", Error,
            "leading zeros in integer literal";

        /// Expected a specific token, or a construct the grammar admits here.
        /// Most call sites name a token (`` expected `]` ``); the interaction
        /// positions name the shapes instead — a return type is one of four,
        /// and saying which is the point of the message.
        FORM_101 = "FORM-101", Error,
            "expected a specific token, or a construct the grammar admits here";

        /// Unexpected token — also the code for nesting past the depth the
        /// parser follows (`MAX_TYPE_DEPTH` in `ridl-syntax`): a type, an
        /// attribute value, a parenthesised group, or an expression tree,
        /// whose height each binary operator, member access, group and
        /// prefix raises by one level.
        FORM_102 = "FORM-102", Error,
            "unexpected token";

        /// Unclosed delimiter.
        FORM_103 = "FORM-103", Error,
            "unclosed delimiter";

        /// Missing `package` declaration.
        FORM_104 = "FORM-104", Error,
            "missing `package` declaration";

        /// Reserved word used as an identifier.
        FORM_105 = "FORM-105", Error,
            "reserved word used as an identifier";

        /// Unknown attribute key — not a key the general form §4.3 table defines.
        FORM_106 = "FORM-106", Error,
            "unknown attribute key";

        /// Attribute key not allowed on this declaration kind (general form §4.3).
        FORM_107 = "FORM-107", Error,
            "attribute key not allowed on this declaration kind";

        /// Duplicate attribute key in one `[ ]` block (general form §4.3).
        FORM_108 = "FORM-108", Error,
            "duplicate attribute key in one block";
    }

    /// The typl catalogue (ADR-0008 decision 21): every `TYPL-` code declared in
    /// this module, with the severity the typl reference §16 tables classify it
    /// at. Five codes the reference documents are absent because no constant
    /// declares them and no pass emits them — TYPL-107, TYPL-112, TYPL-205, and
    /// the two `@labels` assurance codes TYPL-402 and TYPL-403 (TYPL-401 is
    /// declared, as `broken-doc-link`, under ADR-0026). That inventory
    /// is recorded in issue #172; closing it means minting the constants, which
    /// is a change to what the compiler declares, not a catalogue edit.
    TYPL_CATALOG {
        /// More than one `package` declaration in a single file (typl §16.1).
        /// Emitted by the package loader.
        TYPL_001 = "TYPL-001", Error,
            "more than one `package` declaration in a file";

        /// Package name does not mirror the directory path relative to the
        /// manifest root (typl §16.1, ADR-0002 §1). Emitted by the package loader.
        /// Single-file mode is exempt.
        TYPL_002 = "TYPL-002", Error,
            "package name does not mirror the directory path";

        /// Wildcard, relative, or re-exporting import (typl §16.1, ADR-0002 §2).
        /// Emitted by the resolver.
        TYPL_003 = "TYPL-003", Error,
            "wildcard, relative, or re-exporting import";

        /// Circular package imports (typl §16.1, ADR-0002 §6). Emitted by the
        /// resolver from a depth-first walk over package import edges.
        TYPL_004 = "TYPL-004", Error,
            "circular package imports";

        /// A public declaration exposes an `internal` type in its fields, arms,
        /// backing, or a range-bound constant (typl §3.3, §16.1). Emitted by the
        /// checker over every top-level declaration, the ridl `interface`
        /// and `service` included: an interaction payload, parameter, return arm,
        /// or stream element is an exposure position exactly as a struct field is.
        /// A `service` naming an `internal` interface is RIDL-143 instead.
        TYPL_005 = "TYPL-005", Error,
            "a public declaration exposes an `internal` type";

        /// Conflicting imports without an alias (typl §16.1, ADR-0002 §2).
        /// Emitted by the resolver.
        TYPL_006 = "TYPL-006", Error,
            "conflicting imports without an alias";

        /// Unused import (typl §16.1). Emitted by the resolver as a warning.
        TYPL_007 = "TYPL-007", Warning,
            "unused import", lint = "unused-import";

        /// Import alias without an actual collision (typl §16.1, ADR-0002 §2).
        /// Emitted by the resolver as a warning.
        TYPL_008 = "TYPL-008", Warning,
            "import alias without an actual collision", lint = "unneeded-import-alias";

        /// Duplicate definition of the same name in a package (typl §16.1).
        TYPL_009 = "TYPL-009", Error,
            "duplicate definition of the same name in a package";

        /// A package declaring a name the compiler provides itself (typl
        /// §3.1, §16.1). Error, and not a warning, because such a package can
        /// never work: `ridl.std` is implicitly imported by every package
        /// (typl §3.2) rather than resolved through an import, so a user copy
        /// is unreachable by its own name. In package and workspace mode the
        /// generated artifact is overwritten by the standard package's too,
        /// because the output base is the package name; in single-file mode
        /// the base is the file stem, so that second consequence follows only
        /// when the stem is itself `ridl.std`, whatever the extension.
        /// Reported on the `package` declaration, in a workspace member and
        /// in single-file mode alike.
        TYPL_010 = "TYPL-010", Error,
            "package name is reserved for a package the compiler provides";

        /// A type reference names no visible declaration (typl §3.2, §3.3,
        /// §16.1): the path resolves neither in the package's own scope, nor
        /// in `ridl.std`, nor through an import, nor as a qualified
        /// `pkg.Name` — a qualified reference to another package's `internal`
        /// declaration included. Emitted by the checker on the written path,
        /// in every position that takes a type reference — for example a
        /// field, a parameter, a query return, a stream element, a payload,
        /// a union arm, a map key or a constant's type. A reference that resolves to a declaration of the
        /// wrong kind (a constant, an interface) is a different error and
        /// still carries no code (driftsys/ridl#543).
        TYPL_011 = "TYPL-011", Error,
            "type reference names no visible declaration";

        /// `integer` without a range constraint (typl §16.2). Warning.
        TYPL_101 = "TYPL-101", Warning,
            "`integer` without a range constraint", lint = "unbounded-integer";

        /// `float` without both a range and a `step` (typl §16.2). Warning.
        TYPL_102 = "TYPL-102", Warning,
            "`float` without both a range and a `step`", lint = "unbounded-float";

        /// `string`/`bytes` without explicit bounds — the default `[0..256]` is
        /// applied (typl §4.4–§4.5, §16.2). Warning.
        TYPL_103 = "TYPL-103", Warning,
            "`string`/`bytes` without explicit bounds", lint = "unbounded-length";

        /// Range `min > max` (typl §16.2).
        TYPL_104 = "TYPL-104", Error,
            "range `min > max`";

        /// `step` type mismatch, non-positive, or larger than the range
        /// (typl §16.2). Also borrowed by the checker for a range bound
        /// that references a non-numeric constant, a malformed bound const for
        /// which §16.2 defines no dedicated code.
        TYPL_105 = "TYPL-105", Error,
            "`step` type mismatch, non-positive, or larger than the range";

        /// Invalid regex syntax in a `match` constraint or a regex `const`
        /// (typl §16.2). Validated with the `regress` ECMA-262 engine (ADR-0007
        /// decision 10). A pattern `regress` accepts and the Rust `regex`
        /// crate refuses is TYPL-220. Emitted by the checker.
        TYPL_106 = "TYPL-106", Error,
            "invalid regex syntax in `match` or a regex `const`";

        /// `const` value violates its declared type constraints (typl §16.2).
        TYPL_108 = "TYPL-108", Error,
            "`const` value violates its declared type constraints";

        /// Init (`= value`) incompatible with the type/field constraints
        /// (typl §16.2).
        TYPL_109 = "TYPL-109", Error,
            "init `= value` incompatible with the type or field constraints";

        /// Unknown or malformed UCUM unit expression (typl §16.2).
        TYPL_110 = "TYPL-110", Error,
            "unknown or malformed UCUM unit expression";

        /// Integer range bound (or enumset bit position) outside the `int64`
        /// domain (typl §4.2, §16.2).
        TYPL_111 = "TYPL-111", Error,
            "integer range bound outside the `int64` domain";

        /// Type has no derivable init value and no declared `= value`
        /// (typl §5.8, §16.2). Info — escalated to an error only by consumers
        /// that require an init (e.g. a ridl signal payload).
        TYPL_115 = "TYPL-115", Info,
            "type has no derivable init value and no declared `= value`", lint = "no-init-value";

        /// Array without explicit bounds (typl §16.3).
        TYPL_201 = "TYPL-201", Error,
            "array without explicit bounds";

        /// Map without explicit bounds (typl §16.3).
        TYPL_202 = "TYPL-202", Error,
            "map without explicit bounds";

        /// Enum values not unique / not explicitly assigned (typl §16.3).
        TYPL_203 = "TYPL-203", Error,
            "enum values not unique or not explicitly assigned";

        /// Union arm with a primitive type (typl §16.3).
        TYPL_204 = "TYPL-204", Error,
            "union arm with a primitive type";

        /// Recursive composite reference, direct or transitive (typl §16.3).
        TYPL_206 = "TYPL-206", Error,
            "recursive composite reference, direct or transitive";

        /// Enumset bit positions not unique (typl §16.3).
        TYPL_207 = "TYPL-207", Error,
            "enumset bit positions not unique";

        /// `string`/`bytes` used directly as a field type (typl §16.3).
        TYPL_208 = "TYPL-208", Error,
            "`string`/`bytes` used directly as a field type";

        /// Map key is not a named string type or a primitive (typl §16.3).
        TYPL_209 = "TYPL-209", Error,
            "map key is not a named string type or a primitive";

        /// Field, arm, or enum value re-declared under a `reserved` name or value
        /// (typl §16.3).
        TYPL_210 = "TYPL-210", Error,
            "field, arm, or enum value re-declared under a `reserved` entry";

        /// Duplicate `reserved` entry (typl §16.3). Warning. The "dangling"
        /// half of the §16.3 rule (a name/value never previously used) needs the
        /// previous IR snapshot and belongs to `ridl-diff`.
        TYPL_211 = "TYPL-211", Warning,
            "duplicate `reserved` entry", lint = "duplicate-reserved";

        /// `error` modifier on a declaration other than `enum`, `struct`, `union`
        /// (typl §16.3).
        TYPL_212 = "TYPL-212", Error,
            "`error` modifier on a declaration other than `enum`, `struct`, `union`";

        /// Union mixing error and non-error arms without the result-union shape
        /// (typl §16.3).
        TYPL_213 = "TYPL-213", Error,
            "union mixes error and non-error arms without the result-union shape";

        /// `error union` containing a non-error-typed arm (typl §16.3).
        TYPL_214 = "TYPL-214", Error,
            "`error union` contains a non-error-typed arm";

        /// A field name declared twice in one struct or one tuple (typl §7,
        /// §11, §16.3). Distinct from RIDL-149: that code fires when two
        /// distinct struct field names collide only after a pinned name
        /// transform, and this one fires when the two source names are
        /// already the same, before any transform runs. Both fields still
        /// lower — this check reports and does not drop.
        TYPL_215 = "TYPL-215", Error,
            "field name declared twice in one struct or one tuple";

        /// An enum value name declared twice in one `enum` (typl §8, §16.3).
        /// Distinct from RIDL-149: that code fires when two distinct source
        /// names collide only after a pinned name transform, and this one
        /// fires when the two source names are already the same, before any
        /// transform runs. TYPL-203 checks the values' integers, not their
        /// names, so it does not cover this case.
        TYPL_216 = "TYPL-216", Error,
            "enum value name declared twice in one enum";

        /// A union arm name declared twice in one `union` (typl §10, §16.3).
        /// Distinct from RIDL-149: that code fires when two distinct source
        /// names collide only after a pinned name transform, and this one
        /// fires when the two source names are already the same, before any
        /// transform runs.
        TYPL_217 = "TYPL-217", Error,
            "union arm name declared twice in one union";

        /// A bit name declared twice in one standalone `enumset` (typl §9.1,
        /// §16.3). TYPL-207 checks the bits' positions, not their names, so
        /// it does not cover this case. A derived `enumset` copies its bits
        /// from the backing enum, where a repeated name is TYPL-216.
        TYPL_218 = "TYPL-218", Error,
            "enumset bit name declared twice in one enumset";

        /// A standalone `enumset` bit position that is not a number with an
        /// integer value — a string, a boolean, a fractional number, a regex,
        /// or a constant reference, even one naming an integer constant (typl
        /// §9.1, §16.3). `1.0` has an integer value and is accepted as bit 1. The bit has no position to lower, so it is left out of the
        /// IR. An integer outside the `int64` domain is TYPL-111, not this
        /// code. A non-integer `enum` value is TYPL-203.
        TYPL_219 = "TYPL-219", Error,
            "enumset bit position is not a number with an integer value";

        /// A `match` pattern or regex `const` that is valid ECMA-262 syntax
        /// (so not TYPL-106) but that the Rust `regex` crate cannot compile —
        /// for example lookaround, a backreference, `\cX`, `\0`, `[]`, `[^]`,
        /// `{,n}`, or a pattern over the crate's compiled-size limit; typl
        /// §2.7 lists more, and neither list is complete (typl §2.7, §6.2,
        /// §16.3). The Rust backend emits a `match` on a `String`-backed type
        /// as a `regex::Regex::new(..).expect(..)` call under the generated
        /// crate's `validate-pattern` feature, so without this check such a
        /// pattern panics in the consumer's process (issue #437). A regex
        /// constant is emitted as a `&str` and not compiled, but a `match`
        /// naming it is. This code guarantees only that the Rust output can
        /// compile the pattern, not that every engine matches the same strings
        /// with it (issue #597). Emitted by the checker.
        TYPL_220 = "TYPL-220", Error,
            "regex pattern the Rust `regex` crate cannot compile";

        /// One exact site name is used with different canonical units across
        /// the checked workspace. Emitted by the design lint pass. Info from
        /// the corpus calibration (`evals/calibration/summary.md`).
        TYPL_222 = "TYPL-222", Info,
            "one field name used with different units", lint = "inconsistent-unit";

        // TYPL-223 (`inconsistent-abbreviation`) was a calibration candidate
        // that the corpus calibration did not ship; the number is not reused.

        /// Two differently named declarations have equal field or variant sets.
        /// Emitted by the design lint pass. Info from the corpus calibration
        /// (`evals/calibration/summary.md`).
        TYPL_224 = "TYPL-224", Info,
            "duplicate declaration shape", lint = "duplicate-shape";

        /// Stream type `<T>` outside interaction position (typl §16.4, ridl
        /// §12.3). Emitted by the parser in a `.typl` parse and by the checker
        /// for struct fields and collections in a `.ridl` file.
        TYPL_301 = "TYPL-301", Error,
            "stream type `<T>` outside interaction position";

        /// Timing annotation or duration literal in a typl context (typl §16.4).
        TYPL_302 = "TYPL-302", Error,
            "timing annotation or duration literal in a typl context";

        /// `require`/`ensure` attribute in a typl context (typl §16.4): the two
        /// contract attributes at declaration-start position in a `.typl` parse.
        /// Emitted by the parser as a bare string literal rather than
        /// through this constant — see `codes_written_as_string_literals_are_all
        /// _catalogued`.
        TYPL_303 = "TYPL-303", Error,
            "`require`/`ensure` attribute in a typl context";

        /// Interaction declaration in a typl context (typl §16.4, ADR-0007
        /// decision 10): one of the nine ridl words at declaration-start position
        /// in a `.typl` parse. Emitted by the parser.
        TYPL_304 = "TYPL-304", Error,
            "interaction declaration in a typl context";

        /// A doc link or an `@see` target that does not resolve (typl §14,
        /// §16.5; ADR-0026): the name is unknown, is `internal` in another
        /// package, or names no member of the declaration. Warning. Emitted by
        /// the checker, which resolves every link candidate.
        TYPL_401 = "TYPL-401", Warning,
            "doc link or `@see` target that does not resolve", lint = "broken-doc-link";

        /// Blank line between a doc comment and its carrier (typl §14, §16.5;
        /// ADR-0026 extends it from declarations to every carrier). Warning.
        /// Emitted by the doc lints (`ridl_sem::doc_lint`).
        TYPL_404 = "TYPL-404", Warning,
            "blank line between a doc comment and its carrier", lint = "detached-doc-comment";

        /// `@deprecated` doc tag without a reason string (typl §14.2, §16.5).
        /// Warning. Emitted by the checker.
        TYPL_405 = "TYPL-405", Warning,
            "`@deprecated` doc tag without a reason string", lint = "deprecated-without-reason";

        /// A covered item with no doc (ADR-0026): a declaration that is not
        /// `internal`, a member of one, or an rsdl declaration. A doc made only
        /// of tags counts as missing. Warning. Emitted by the doc lints
        /// (`ridl_sem::doc_lint`).
        TYPL_406 = "TYPL-406", Warning,
            "item without a doc comment", lint = "missing-docs";

        /// Doc comment in a position that is not a carrier (ADR-0026): before
        /// `package`, an `import`, a return type or an attribute block, or at
        /// the end of a file or a body. Warning. Emitted by the doc lints
        /// (`ridl_sem::doc_lint`).
        TYPL_407 = "TYPL-407", Warning,
            "doc comment in a position that is not a carrier", lint = "misplaced-doc-comment";

        /// A doc tag other than `@see`, `@since`, `@deprecated` and `@labels`
        /// (typl §14.2, ADR-0026). Warning. Emitted by the doc lints
        /// (`ridl_sem::doc_lint`).
        TYPL_408 = "TYPL-408", Warning,
            "doc tag other than `@see`, `@since`, `@deprecated` and `@labels`", lint = "unknown-doc-tag";

        /// `@see` or `@since` with a missing or malformed value (ADR-0026).
        /// Warning. Emitted by the doc lints (`ridl_sem::doc_lint`).
        TYPL_409 = "TYPL-409", Warning,
            "`@see` or `@since` with a missing or malformed value", lint = "malformed-doc-tag";

        /// Doc comment written as `/** */` (ADR-0026). Warning, `allow` by
        /// default, so a project opts in to requiring `///`. Emitted by the
        /// doc lints (`ridl_sem::doc_lint`).
        TYPL_410 = "TYPL-410", Warning,
            "doc comment written as `/** */`", lint = "doc-comment-style", default = allow;
    }

    /// The ridl catalogue (ADR-0008 decision 21): every `RIDL-` code declared in
    /// this module, with the severity the ridl reference §16 tables classify it
    /// at. RIDL-140, RIDL-141, and RIDL-143 to RIDL-145 sit in the 1xx band
    /// while the reference lists them under the §16.4 evolution table — a
    /// documented anomaly kept as written (ADR-0008 decision 6). RIDL-111 and
    /// RIDL-142 are reserved by ADR-0008 decision 21 and are not declared yet,
    /// so they are absent here too.
    ///
    /// Adding a code here does **not** make it show up in a corpus fixture.
    /// `RIDL_PROFILE_CODES` in `crates/ridlc/tests/corpus.rs` — the list that
    /// gives every ridl code a living example — is a list of code *strings*
    /// with no link to these constants, so a code minted here and omitted there
    /// is caught by a string-set equality standing beside the declaration
    /// (`ridl_profile_codes_match_the_catalogue`) rather than by the declaration
    /// itself. Decision 21 asks the declare-once mechanism to cover that list as
    /// well, and it does not: the list carries a `Provoked` discriminator this
    /// catalogue has no equivalent of. Stated here as decision 21 requires; the
    /// gap is separate work, tracked in issue #172.
    RIDL_CATALOG {
        /// `signal` or `event` without a timing annotation — the default
        /// `[100ms..1000ms]` (or the configured `[defaults].timing`) is applied
        /// (ridl §9.1, §16.1). Warning. Emitted by the checker.
        RIDL_100 = "RIDL-100", Warning,
            "`signal` or `event` without a timing annotation", lint = "missing-timing";

        /// A range annotation `@[X..Y]` whose lower bound exceeds its upper bound
        /// (ridl §9.2, §16.1). Emitted by the checker.
        RIDL_101 = "RIDL-101", Error,
            "timing range `@[X..Y]` with `X > Y`";

        /// A zero or negative timing duration (ridl §9.2, §16.1). Emitted by the
        /// checker.
        RIDL_102 = "RIDL-102", Error,
            "zero or negative timing duration";

        /// A strict-periodic `@Xms` annotation on a kind other than `signal` —
        /// the isochronous mode belongs to state alone (ridl §9.2, §16.1).
        /// Widened from "on an `event`" by ADR-0015 decision 6 when `command`
        /// and `query` gained the range form: the same rule, stated
        /// over the three kinds it excludes instead of one. Emitted by the
        /// checker.
        RIDL_103 = "RIDL-103", Error,
            "strict-periodic `@Xms` on a kind other than `signal`";

        /// Explicit return type on a `command` — a command always returns `()`
        /// (ridl §6.1, §16.1). Emitted by the checker.
        RIDL_104 = "RIDL-104", Error,
            "explicit return type on a `command`";

        /// `query` returning `()` — use `command` (ridl §7.1, §16.1). Emitted by
        /// the checker.
        RIDL_105 = "RIDL-105", Error,
            "`query` returning `()`";

        /// A timing annotation on `fixed` — the one kind that carries none —
        /// or an attribute block on `fixed` (ridl §8, §9, §16.1). Emitted by
        /// the checker.
        ///
        /// Narrowed by ADR-0015 decision 6: `command` and `query` admit
        /// the range form now, so the two RPC kinds left this rule and only
        /// `fixed` remains in both halves. The callables drew FORM-102 until
        /// the E2 close-out, so one rule sat under two codes and one of them
        /// was a parse code whose catalogue meaning is "unexpected token" —
        /// for a token the grammar accepts on purpose, precisely so the
        /// narrowing can be a semantic rule with a semantic message.
        RIDL_106 = "RIDL-106", Error,
            "timing annotation on `fixed`, or attribute block on `fixed`";

        /// Type declaration inside an `interface` or `service` body — typl
        /// declarations live at package level (ridl §14.1, §16.1).
        ///
        /// Emitted by the **parser**, as a bare string literal (`ridl-syntax`
        /// cannot reference [`DiagCode`]), at the point where it recognises the
        /// keyword and recovers the declaration into an `ErrorNode`. The
        /// checker used to code that node a second time, so every RIDL-107
        /// arrived paired with a contradicting FORM-102 at the same span; the
        /// parser knows exactly what the construct is, so it is the one that
        /// names it. RIDL-403 and TYPL-304 are parser-raised for the same
        /// reason. The constant is kept for the catalogue and for the error
        /// index.
        RIDL_107 = "RIDL-107", Error,
            "type declaration inside an `interface` or `service` body";

        /// A range annotation `@[X..X]` whose bounds are equal — a degenerate
        /// range, the rate floor equal to its staleness bound, on a `signal` and an
        /// `event` alike (ridl §9.2, §16.1; ADR-0008 decision 17). Not a spelling
        /// of the strict-periodic `@Xms`, which is a separate `TimingMode`.
        /// Warning. Emitted by the checker.
        RIDL_108 = "RIDL-108", Warning,
            "degenerate timing range `@[X..X]`", lint = "degenerate-timing-range";

        /// Signal payload type has no derivable init value and no `= value`
        /// override (ridl §4.4, §16.1). Emitted by the checker.
        RIDL_109 = "RIDL-109", Error,
            "signal payload has no derivable init and no `= value` override";

        /// Signal `= value` init override violates the payload type's constraints
        /// (ridl §4.4, §16.1). Emitted by the checker.
        RIDL_110 = "RIDL-110", Error,
            "signal `= value` init override violates the payload constraints";

        /// A `command` or `query` with no declared response bound — no `@`
        /// annotation at all, or the half-open `@[min..]` that declares a
        /// throttle only (ridl §9.3, §16.1; ADR-0015 decisions 4 and 6). The
        /// checker applies the response-bound default for the member's kind —
        /// `[defaults].command_timing` or `[defaults].query_timing`, or the
        /// built-in `[..1s]` or `[..3s]` — and this warning names the bounds
        /// applied. Warning; an active profile may escalate it to an error,
        /// the same two-step §9.1 gives an untimed signal or event. The RPC
        /// counterpart of RIDL-100, kept as its own code so that the
        /// `missing-response-bound` lint level is set apart from the signal
        /// and event one. RIDL-111 is reserved for the interface-used-as-a-type
        /// error (ADR-0008 decision 21), so 112 is the first free code in the
        /// band. Emitted by the checker.
        RIDL_112 = "RIDL-112", Warning,
            "`command` or `query` takes the default response bound", lint = "missing-response-bound";

        /// Duplicate `service` name across the whole workspace — the service
        /// catalog is a flat global namespace (ridl §14.5, §16.4). Emitted
        /// workspace-wide by `service_catalog`. The reference numbers
        /// it in the 1xx band while listing it under the §16.4 evolution/profile
        /// table — a documented anomaly kept as written (ADR-0008 decision 6).
        RIDL_140 = "RIDL-140", Error,
            "duplicate `service` name across the workspace";

        /// A `service` names a type that is not an `interface`, and has no inline
        /// shape (ridl §14.5, §16.4). Emitted per-package by the checker. Kept in
        /// the 1xx band per ADR-0008 decision 6 (see RIDL-140).
        /// Applies per shape in the service's shape list since ADR-0015
        /// decision 18: the rule is unchanged, the span reports against
        /// the offending list element.
        RIDL_141 = "RIDL-141", Error,
            "`service` names a type that is not an `interface`";

        /// A `service` publishes an `internal` interface (ridl §14.5, §16.4).
        /// Emitted per-package by the checker's exposure pass. Distinct from
        /// TYPL-005: what leaks is an interface rather than a type, and a service
        /// takes no `internal` modifier, so the TYPL-005 remedy — make the
        /// exposing declaration internal too — does not exist here. Kept in the
        /// 1xx band beside RIDL-140/-141 per ADR-0008 decision 6. RIDL-111 and
        /// RIDL-142 are reserved by decision 21 and not yet implemented, so 143 is
        /// the next free code; decision 13's allocation ledger needs the ninth
        /// entry (issue #169). Applies per shape in the service's shape list
        /// since ADR-0015 decision 18: the rule is unchanged, the span
        /// reports against the offending list element.
        RIDL_143 = "RIDL-143", Error,
            "`service` publishes an `internal` interface";

        /// Duplicate member name across a service's interfaces (ridl §14.5,
        /// §16.4; ADR-0015 decisions 16 and 18): two composed interfaces both
        /// declaring `status` would give `service.status` two referents, which
        /// flat addressing cannot express. Emitted per-package by the checker
        /// The service codes sit in the 1xx band (see RIDL-140);
        /// RIDL-112 is minted by ADR-0015 decision 6, so 144 is the first free
        /// code.
        RIDL_144 = "RIDL-144", Error,
            "duplicate member name across a service's interfaces";

        /// The same interface named twice in one service (ridl §14.5, §16.4;
        /// ADR-0015 decision 18). Its own code rather than a fall-through to
        /// RIDL-144: listing a shape twice makes every member collide, so
        /// RIDL-144 alone would emit one diagnostic per member and bury the
        /// actual mistake. Emitted per-package by the checker; lowering
        /// keeps the first listing only, which holds the slot, and the
        /// diagnostic's secondary label points at it.
        RIDL_145 = "RIDL-145", Error,
            "the same interface named twice in one service";

        /// Two names in one scope that collide after a pinned name transform
        /// (ridl §16.4; ADR-0016 decision 3). Neither transform is
        /// injective and no case-folding transform can be, so
        /// `parseHTTPResponse` and `parseHttpResponse` both project to
        /// `parse_http_response` and a target whose namespace is snake_case
        /// would carry one identifier twice — in Rust, one trait with two
        /// methods of the same name, or one function with two identically
        /// named arguments. The projection contract's injectivity obligation
        /// is discharged here, on the package, because it cannot be carried
        /// by the function. Its own code rather than RIDL-402 — that rule is
        /// the same name declared twice — because the remedy differs: these
        /// names are distinct in source and only their projections collide.
        /// Scoped to the members of one interface, the parameters of one
        /// interaction (decision 4), the fields of one struct, which joined
        /// in the commit where the proto3 backend started projecting them onto proto3, the
        /// arms of one union, which joined with the ADR-0016 amendment of
        /// 2026-09-20, and the values of one enum, which joined with the
        /// amendment of 2026-09-26. The first three namespaces are checked
        /// under `snake_case` alone; a union's arms are checked under
        /// `snake_case` and `camel_case` both, because a union arm reaches
        /// both namespaces and the two collision sets are incomparable; an
        /// enum's values are checked under `pascal_case` alone, because its
        /// collision set contains `snake_case`'s. The message names the
        /// transform that collided. Emitted per-package by the checker.
        RIDL_149 = "RIDL-149", Error,
            "two names in one scope collide after a pinned name transform";

        /// Stream `<T>` on a `signal` or `event` payload (ridl §12.3, §16.2).
        /// Emitted by the checker.
        RIDL_201 = "RIDL-201", Error,
            "stream `<T>` on a `signal` or `event` payload";

        /// Stream element type not a named type, `string`, or `bytes` (ridl
        /// §12.2, §16.2). Emitted by the checker.
        RIDL_202 = "RIDL-202", Error,
            "stream element type not a named type, `string`, or `bytes`";

        /// `require` or `ensure` on `signal`, `event`, or `fixed` (ridl §13,
        /// §16.3). Emitted by the checker.
        RIDL_301 = "RIDL-301", Error,
            "`require` or `ensure` on `signal`, `event`, or `fixed`";

        /// `ensure` on `command` — a command has no result to observe (ridl §6.1,
        /// §16.3). Emitted by the checker.
        RIDL_302 = "RIDL-302", Error,
            "`ensure` on `command`";

        /// A fallible query return with no success path (ridl §10.1, §16.3; general
        /// form §6.1): a bare `error` type in return position, an `error`-typed
        /// success (left) arm of an inline `T | E`, or a non-error error (right)
        /// arm. Error. Emitted by the checker.
        RIDL_303 = "RIDL-303", Error,
            "fallible query return with no success path";

        /// An `error`-typed or result-union parameter on a `command` or `query` —
        /// failure flowing toward a provider (ridl §10.1, §16.3). Warning. Emitted
        /// by the checker.
        RIDL_304 = "RIDL-304", Warning,
            "`error`-typed or result-union parameter on a `command` or `query`",
                lint = "error-typed-parameter";

        /// An `ensure` clause that never references `result` — well-typed but
        /// suspicious (ridl §13, §16.3; expr-core specification §8). Warning.
        /// Emitted by the checker.
        RIDL_305 = "RIDL-305", Warning,
            "`ensure` clause that never references `result`", lint = "ensure-without-result";

        /// A `require`/`ensure` expression outside the guaranteed subset (ridl §13,
        /// §16.3; expr-core specification §8 — one code for the whole boundary,
        /// with a message naming the offending form). Error. Emitted by the checker.
        RIDL_306 = "RIDL-306", Error,
            "`require`/`ensure` expression outside the guaranteed subset";

        /// An `error` enum declares a Stratum-2 contract-error category name
        /// (`INVALID_VALUE`, `PRECONDITION_FAILED`, `CONTRACT_BROKEN`,
        /// `UNKNOWN_INTERACTION`) — reserved vocabulary (ridl §10.2, §16.3).
        /// Warning. Emitted by the checker.
        RIDL_307 = "RIDL-307", Warning,
            "contract-error category name declared in an `error` enum",
                lint = "contract-error-name-in-enum";

        /// A named result union in query return position — the inline `T | E`
        /// spelling is canonical there (general form §6.1, ADR-0008 decision 13).
        /// Warning; the named spelling stays legal typl data, so this is a lint,
        /// not an error. Emitted by the lint pass.
        RIDL_308 = "RIDL-308", Warning,
            "named result union in query return position", lint = "named-result-union-in-query";

        /// Interaction re-declared under a `reserved` name (ridl §11, §16.4).
        /// Emitted by the checker.
        RIDL_401 = "RIDL-401", Error,
            "interaction re-declared under a `reserved` name";

        /// Duplicate interaction name in one interaction body — an `interface`
        /// or a service's inline shape (ridl §14.1, §16.4). Emitted by the
        /// checker; lowering keeps the first declaration only, and
        /// the diagnostic's secondary label points at it.
        RIDL_402 = "RIDL-402", Error,
            "duplicate interaction name in one interaction body";

        /// Behaviour, user-interaction, or architecture declaration in a ridl
        /// context (ridl §16.4): a reserved word of the uxdl/rmdl/rsdl profiles at
        /// declaration-start position in a `.ridl` parse. Emitted by the parser.
        RIDL_403 = "RIDL-403", Error,
            "behaviour, user-interaction, or architecture declaration in a ridl context";

        /// A query named like a mutation — `set…`, `reset…`, and the rest of the
        /// mutating verb set (ridl §7.2, §16.4): a state-mutating request belongs
        /// to `command`. Warning. Emitted by the lint pass.
        RIDL_404 = "RIDL-404", Warning,
            "query named like a mutation", lint = "query-named-like-mutation";

        /// One `error` type used as the failure arm of queries in three or more
        /// distinct interfaces — the "shared across unrelated failure domains"
        /// heuristic (ridl §10.1, §16.4). Info. Emitted by the lint pass; the
        /// threshold is three, so two interfaces stay silent.
        RIDL_405 = "RIDL-405", Info,
            "one `error` type shared across unrelated failure domains", lint = "shared-error-type";

        /// A `signal` or `event` payload whose struct re-declares envelope
        /// metadata — publication time or a frame counter (ridl §3.1, §16.4). Info;
        /// domain time distinct from transport time is legitimate, so the message
        /// says so. Emitted by the lint pass.
        RIDL_406 = "RIDL-406", Info,
            "payload struct re-declares envelope metadata", lint = "redeclared-envelope-metadata";

        /// An interaction's, struct field's or union arm's ordinal (typl §7.4)
        /// changed against a published baseline snapshot
        /// (ridl §11, general form §6.3). Warning. Emitted by the `ridl check`
        /// desk check, never by the compiler: the comparison
        /// reads a workspace-local baseline, which is outside `ridlc`'s
        /// source→IR function (ADR-0008 decisions 9 and 13). For a struct
        /// field or union arm the desk reads the verdict `ridl diff` gates
        /// on, so the two agree by construction (driftsys/ridl#533): one
        /// warning per change the diff reports as breaking. That is a member
        /// inserted above a live one or into a retired slot; a member
        /// removed, with or without a tombstone, because `ridl diff` matches
        /// a composite member by name and does not yet read the body's
        /// `reserved` entries; a member whose ordinal moved in an edit that
        /// added or removed none, by a reorder or by a `reserved` entry
        /// added, moved or removed above it; and a member appended beside
        /// any of those, which the diff reports as breaking for that
        /// sibling change — the message also says when the appended struct
        /// field is breaking for its type, and tells the author to declare it
        /// optional (driftsys/ridl#598). An append alone draws nothing, not
        /// even one breaking for its type, which moves no ordinal, except an
        /// arm added to a result union, whose arms are its transport
        /// identity (ADR-0008 decision 4).
        /// The diff reports no reorder beside an addition or a removal, so
        /// the warning for an added or removed member names the siblings
        /// whose ordinal changed. An enum value's or enum-set bit's reorder
        /// is not a change (typl §8, §9) and does not draw this warning
        /// (driftsys/ridl#335); an enum value added or removed is `ridl
        /// diff`'s alone.
        RIDL_407 = "RIDL-407", Warning,
            "interaction, struct field, or union arm ordinal changed against the published \
             baseline", lint = "ordinal-changed";

        /// An interaction of an interface body the baseline being replaced
        /// declares is not carried forward as the tombstone rule requires
        /// (ridl §11), in one of four shapes: it is gone from the source with
        /// no `reserved` tombstone; the source retires it with a tombstone at
        /// an ordinal other than its own; the baseline already retired it and
        /// the source dropped the tombstone; or the source declares a live
        /// interaction under the name a tombstone retires. Error. Emitted by
        /// `ridl baseline` alone, for the interaction level only — a whole
        /// interface or service removed, and a named-form service's shape
        /// list, are outside it. Publication is the last point at which the
        /// change can still be refused, because the snapshot about to be
        /// overwritten is the only record that the ordinal was ever taken.
        /// Distinct from RIDL-407, which is the desk-time warning that an
        /// ordinal moved and which neither classifies nor gates.
        RIDL_408 = "RIDL-408", Error,
            "interaction removed, its tombstone dropped or moved, or its retired name redeclared";

        /// A live entry of the package's `interfaces.lock` names an interface
        /// the package no longer declares (lock design §4, §8) — the interface
        /// was renamed or removed, and the lock does not record which. Error.
        /// Emitted by the checker on the entry's own line of the lock file,
        /// `ridlc` and `ridl` alike. The fix is `ridl lock <pkg> --retire Old`
        /// when the interface is gone, or `ridl lock <pkg> --rename Old=New`
        /// when a declaration without an entry is the same interface under a
        /// new name; the message names only `--retire` when the package has
        /// no declaration without an entry. `ridl check` adds a label naming
        /// the one `--rename` command when the published baseline shows
        /// exactly one declaration without an entry with the old interface's
        /// shape.
        RIDL_409 = "RIDL-409", Error,
            "live `interfaces.lock` entry with no declaration";

        /// The package's `interfaces.lock` is malformed (lock design §2, §8):
        /// no `next` line, `next` not greater than every entry's number, one
        /// number on two entries, one live key on two entries, or a line that
        /// does not parse — git conflict markers included. Error. Emitted by
        /// the loader, on the offending line of the lock file itself (or at
        /// the start of an empty file), so `ridlc` and `ridl` alike stop on
        /// it; the package then compiles without its lock. The fix is to
        /// resolve the conflict or restore the file from version control and
        /// run `ridl lock`.
        RIDL_410 = "RIDL-410", Error,
            "`interfaces.lock` is malformed";

        /// An interface in the snapshot `ridl baseline` is about to publish
        /// carries a provisional number — a declaration with no entry in the
        /// package's `interfaces.lock` (lock design §3, §8). A provisional
        /// number is no identity: `ridl diff` never matches on it, so a
        /// snapshot holding one records nothing a later comparison can hold
        /// the interface to. Error. Emitted by `ridl baseline` alone, at the
        /// declaration's name, for a first publication as for a replacement.
        /// The fix is plain `ridl lock`, which allocates and records the
        /// number, then publish.
        RIDL_411 = "RIDL-411", Error,
            "provisional interface number refused at publication";

        /// An interface number the published baseline holds is absent from
        /// the fresh snapshot and not among its `interfaces.lock` retired
        /// entries (lock design §4, §8) — a lock line deleted by hand, since a
        /// live entry with no declaration already fails the build with
        /// RIDL-409. Publishing would lose the only record that the number was
        /// allocated, and `next` could hand it to a later interface. Error.
        /// Emitted by `ridl baseline` alone, for a published number other
        /// than 0: a snapshot published before the lock existed carries 0,
        /// which is never allocated, and is matched by name. The fix is to
        /// restore the entry's line in `interfaces.lock` from version
        /// control, with `retired` after the number when the interface is
        /// gone.
        RIDL_412 = "RIDL-412", Error,
            "published interface number dropped without a retired entry";

        /// A parameter name declared twice in one `command` or `query`
        /// parameter list (ridl §6.1, §7.1, §16.4). Distinct from RIDL-149:
        /// that code fires when two distinct source names collide only after
        /// a pinned name transform, and this one fires when the two source
        /// names are already the same, before any transform runs. Both
        /// parameters still lower — this check reports and does not drop.
        RIDL_413 = "RIDL-413", Error,
            "parameter name declared twice in one parameter list";

        /// A declared interface has disconnected groups of members under
        /// direct named-type sharing. Info from the corpus calibration
        /// (`evals/calibration/summary.md`).
        RIDL_414 = "RIDL-414", Info,
            "interface members form disconnected type-sharing groups", lint = "low-cohesion-interface";

        // RIDL-415 (`package-fan-out`) was a calibration candidate that the
        // corpus calibration did not ship; the number is not reused. The
        // package coupling metric stays available through `ridl_metrics`.
    }

    /// The rsdl catalogue: every `RSDL-` code declared in this module, with the
    /// severity the rsdl reference §16.1 table classifies it at. A code is
    /// declared with the pass that raises it. The §16.2 reserved codes and the
    /// §16.3 retired codes are never declared. `RSDL_PROFILE_CODES` in
    /// `crates/ridlc/tests/corpus.rs` gives every code here a living example,
    /// and `rsdl_profile_codes_match_the_catalogue` holds the two lists equal.
    RSDL_CATALOG {
        /// `instances` is not a parenthesised list of one or more camelCase
        /// names — `()`, `instances = solo` (rsdl §5, §7, §16.1). Error. Raised
        /// by the rsdl attribute check.
        RSDL_305 = "RSDL-305", Error,
            "`instances` is not a parenthesised list of one or more camelCase names";

        /// A duplicate instance name in one component (rsdl §7, §16.1). Error.
        /// Raised by the rsdl closure check.
        RSDL_306 = "RSDL-306", Error,
            "duplicate instance name in one component";

        /// `Unit` written in source — as a declared instance name, or as the
        /// instance segment of a reference (rsdl §7, §16.1). Error. Raised by
        /// the rsdl closure check.
        RSDL_307 = "RSDL-307", Error,
            "`Unit` written in source";

        /// A component requires an interface listed by a service it offers
        /// (rsdl §3.2, §16.1). Error. Raised by the rsdl closure check.
        RSDL_308 = "RSDL-308", Error,
            "a component requires an interface listed by a service it offers";

        /// The same service on two `offers` lines, or the same interface on two
        /// `requires` lines, of one component (rsdl §3.2, §16.1). Error. Raised
        /// by the rsdl closure check.
        RSDL_309 = "RSDL-309", Error,
            "the same service or interface on two lines of one component";

        /// An `offers` line names something that is not a service, or nothing
        /// (rsdl §3.2, §16.1). Error. Raised by the rsdl closure check.
        RSDL_310 = "RSDL-310", Error,
            "an `offers` line names something that is not a service";

        /// A `requires` line names a service whose shape is a list of
        /// interfaces; the diagnostic lists them (rsdl §3.2, §16.1). Error.
        /// Raised by the rsdl closure check.
        RSDL_311 = "RSDL-311", Error,
            "a `requires` line names a service whose shape is a list of interfaces";

        /// A `requires` line names something that is neither an interface nor
        /// an inline-shape service, or nothing (rsdl §3.2, §16.1). Error. Raised
        /// by the rsdl closure check.
        RSDL_312 = "RSDL-312", Error,
            "a `requires` line names neither an interface nor an inline-shape service";

        /// `external` written with a value — it is a flag (rsdl §5, §16.1).
        /// Error. Raised by the rsdl attribute check.
        RSDL_313 = "RSDL-313", Error,
            "`external` written with a value";

        /// A closure component requires an interface that no closure service
        /// lists — a missing provider (rsdl §8, §16.1). Error. Raised by the rsdl
        /// resolution.
        RSDL_403 = "RSDL-403", Error,
            "a closure component requires an interface no closure service lists";

        /// An interface listed by two services of the closure, raised for every
        /// interface they list (rsdl §8, §16.1). Error. Raised by the rsdl
        /// resolution.
        RSDL_408 = "RSDL-408", Error,
            "an interface listed by two services of the closure";

        /// A `requires` resolves to a redundant provider set — an offering
        /// component with more than one instance (rsdl §7, §16.1). Warning, not
        /// yet realizable: the lowering proceeds. Raised by the rsdl resolution.
        RSDL_409 = "RSDL-409", Warning,
            "a `requires` resolves to a redundant provider set", lint = "redundant-provider-set";

        /// Two closure components offer one service (rsdl §8, §16.1). Error.
        /// Raised by the rsdl resolution.
        RSDL_502 = "RSDL-502", Error,
            "two closure components offer one service";

        /// A member line names a service by its name while a declared component
        /// offers it; the diagnostic names the offerer (rsdl §6, §16.1). Error.
        /// Raised by the rsdl closure check.
        RSDL_504 = "RSDL-504", Error,
            "a member line names a service that a declared component offers";

        /// More than one `system` in the workspace (rsdl §3.1, §16.1). Error.
        /// Raised by the rsdl closure check.
        RSDL_601 = "RSDL-601", Error,
            "more than one `system` in the workspace";

        /// A `system` member line names nothing that is a component or a service
        /// (rsdl §3.1, §16.1). Error. Raised by the rsdl closure check.
        RSDL_602 = "RSDL-602", Error,
            "a `system` member line names neither a component nor a service";

        /// A name listed twice in one `system` body (rsdl §3.1, §16.1). Error.
        /// Raised by the rsdl closure check.
        RSDL_603 = "RSDL-603", Error,
            "a name listed twice in one `system` body";

        /// A declaration of another profile — a type, an interface, a service —
        /// at the top level of an `.rsdl` file (rsdl §2, §16.1). Error. Raised
        /// by the parser.
        RSDL_604 = "RSDL-604", Error,
            "a declaration of another profile in an `.rsdl` file";

        /// An instance of a closure component with no placement in a deployment
        /// (rsdl §9, §16.1). Error; blocks that deployment only (§13). Raised by
        /// the rsdl placement check.
        RSDL_701 = "RSDL-701", Error,
            "an instance of a closure component with no placement in a deployment";

        /// A placement line names a component, instance or service outside the
        /// closure, or a name that resolves to nothing (rsdl §9, §16.1). Error.
        /// Raised by the rsdl placement check.
        RSDL_702 = "RSDL-702", Error,
            "a placement line names something outside the closure, or nothing";

        /// `deployment … for Y` where `Y` resolves to no declared `system`
        /// (rsdl §3.4, §16.1). Error. Raised by the rsdl placement check.
        RSDL_704 = "RSDL-704", Error,
            "a deployment is `for` no declared `system`";

        /// Two machines with one name in one deployment (rsdl §3.5, §16.1).
        /// Error. Raised by the rsdl placement check.
        RSDL_705 = "RSDL-705", Error,
            "two machines with one name in one deployment";

        /// An instance placed twice in one deployment, also `Cruise` together
        /// with `Cruise.primary` (rsdl §9, §16.1). Error. Raised by the rsdl
        /// placement check.
        RSDL_706 = "RSDL-706", Error,
            "an instance placed twice in one deployment";

        /// An `external` machine lists an implemented component (rsdl §9,
        /// §16.1). Error. Raised by the rsdl placement check.
        RSDL_707 = "RSDL-707", Error,
            "an `external` machine lists an implemented component";

        /// Two deployments with one name in the workspace (rsdl §3.4, §16.1).
        /// Error. Raised by the rsdl placement check.
        RSDL_708 = "RSDL-708", Error,
            "two deployments with one name in the workspace";

        /// A `depth`, `slots` or `budget` value that is not an integer literal
        /// within the key's range (rsdl §5, §16.1). Error, scoped to its
        /// deployment (rsdl §13). Raised by the rsdl attribute reader.
        RSDL_709 = "RSDL-709", Error,
            "a `depth`, `slots` or `budget` value is not an integer within its range, or the key \
             is written bare";

        /// A backend key whose namespace no configured backend claims (rsdl §5,
        /// §16.1). Warning: the key is still carried. Raised by `ridlc`, which
        /// knows the configured backends (plan decision P-B4).
        RSDL_804 = "RSDL-804", Warning,
            "a backend key whose namespace no configured backend claims",
                lint = "unclaimed-backend-key";

        /// A declared `depth` below the contract bound `ceil(max / min)` of an
        /// event a covered link consumes (rsdl §5, §16.1). Warning: the
        /// declared value replaces the bound, and occurrences alive at once
        /// can then be dropped. Raised by the rsdl depth check.
        RSDL_805 = "RSDL-805", Warning,
            "a declared `depth` is below `ceil(max / min)` for an event a covered link consumes",
                lint = "depth-below-bound";

        /// An event whose contract bound is not derivable — an explicit
        /// half-open range, or a ratio `ceil(max / min)` outside the `depth`
        /// range — consumed by a link with no declared `depth` (rsdl §5,
        /// §16.1). Warning: the ring depth of the link cannot be derived.
        /// Raised by the rsdl depth check.
        RSDL_806 = "RSDL-806", Warning,
            "an event whose contract bound is not derivable is consumed by a link with no declared `depth`",
                lint = "depth-underivable";

        /// A `PLATFORM` distribution holds a component whose `requires` resolves
        /// into an `APPLICATION` distribution — tier inversion; a distribution
        /// without `tier` is exempt (rsdl §3.3, §16.1). Error. Raised by the
        /// rsdl distribution check.
        RSDL_901 = "RSDL-901", Error,
            "a `PLATFORM` distribution requires into an `APPLICATION` distribution";

        /// A distribution member line names something outside the closure, or
        /// nothing (rsdl §3.3, §16.1). Error. Raised by the rsdl distribution
        /// check.
        RSDL_903 = "RSDL-903", Error,
            "a distribution member line names something outside the closure, or nothing";

        /// An implemented closure component in no distribution, while the
        /// workspace declares at least one (rsdl §3.3, §16.1). Error. Raised by
        /// the rsdl distribution check.
        RSDL_904 = "RSDL-904", Error,
            "an implemented closure component in no distribution";

        /// A component listed by two distributions (rsdl §3.3, §16.1). Error.
        /// Raised by the rsdl distribution check.
        RSDL_905 = "RSDL-905", Error,
            "a component listed by two distributions";

        /// A name listed twice in one distribution body (rsdl §3.3, §16.1).
        /// Error. Raised by the rsdl distribution check.
        RSDL_906 = "RSDL-906", Error,
            "a name listed twice in one distribution body";

        /// An `external` component listed by a distribution (rsdl §3.3, §16.1).
        /// Error. Raised by the rsdl distribution check.
        RSDL_907 = "RSDL-907", Error,
            "an `external` component listed by a distribution";

        /// A `tier` value other than `PLATFORM` or `APPLICATION` (rsdl §5,
        /// §16.1). Error. Raised by the rsdl attribute check.
        RSDL_908 = "RSDL-908", Error,
            "`tier` value other than `PLATFORM` or `APPLICATION`";
    }

    /// The manifest catalogue (ADR-0007 decision 2): the manifest `0xx` codes the
    /// `ridl.toml` parser and the package loader emit, and the
    /// distribution `1xx` codes the import materializer emits. Listed here
    /// even for `MANI-004`, whose emission site is the loader rather than the
    /// standalone parser, so the error index has one authoritative source.
    MANI_CATALOG {
        /// The `ridl.toml` text is not valid TOML.
        MANI_001 = "MANI-001", Error,
            "invalid manifest TOML";

        /// The manifest declares both `[package]` and `[workspace]`; the two modes
        /// are mutually exclusive (ADR-0002 §4).
        MANI_002 = "MANI-002", Error,
            "manifest declares both `[package]` and `[workspace]`";

        /// The manifest declares neither `[package]` nor `[workspace]` (ADR-0002 §4).
        MANI_003 = "MANI-003", Error,
            "manifest declares neither `[package]` nor `[workspace]`";

        /// A workspace member's own manifest declares `[workspace]`; nested
        /// workspaces are forbidden (ADR-0002 §4). Defined here, but emitted by the
        /// package loader when a member manifest is read — a single
        /// manifest parsed in isolation cannot know it is a member.
        MANI_004 = "MANI-004", Error,
            "nested workspace: a member manifest declares `[workspace]`";

        /// An unrecognized key in the manifest or one of its sections (warning).
        MANI_005 = "MANI-005", Warning,
            "unknown manifest key", lint = "unknown-manifest-key";

        /// The package name is not lowercase dot-separated segments (ADR-0002 §1).
        MANI_006 = "MANI-006", Error,
            "invalid package name";

        /// An `[imports]` value is not a valid import URL.
        MANI_007 = "MANI-007", Error,
            "invalid import URL";

        /// A workspace member directory is missing or has no `ridl.toml`. Emitted
        /// by the package loader, which is where member paths are resolved
        /// against the filesystem.
        MANI_008 = "MANI-008", Error,
            "workspace member directory has no `ridl.toml`";

        /// A manifest `[defaults].timing`, `[defaults].command_timing` or
        /// `[defaults].query_timing` value is not a valid range (ridl §9.1,
        /// §9.3, ADR-0008 decision 13); the message names the key. The
        /// manifest parser stores the raw strings unparsed — `ridl-core`
        /// cannot depend on `ridl-sem` — so the checker parses them and emits
        /// this code.
        MANI_009 = "MANI-009", Error,
            "invalid `[defaults]` timing value";

        /// A `[lints]` entry whose key is not a registered lint name, or whose
        /// value is not one of the level strings `allow`, `info`, `warn` and
        /// `deny`; also a `lints` key that is not a table (ADR-0024
        /// decision 11). The entry is ignored and the check goes on.
        MANI_010 = "MANI-010", Warning,
            "`[lints]` entry names no lint, or its value is not a level", lint = "unknown-lint";

        /// The file named by `[codegen] header-file` cannot be used: it cannot
        /// be read (it does not exist, or an I/O error occurred), its text is
        /// not UTF-8, or it contains a control character: any character for which
        /// `char::is_control` holds (C0, DEL and C1) other than a tab and a line
        /// break, or U+2028 or U+2029. The message names the resolved path.
        MANI_011 = "MANI-011", Error,
            "`[codegen] header-file` cannot be read or holds a control character";

        /// A workspace member's manifest sets `[codegen] header-file`. Only the
        /// workspace root's manifest, or a standalone package's manifest, may
        /// set it.
        MANI_012 = "MANI-012", Error,
            "`[codegen] header-file` is set in a workspace member";

        /// A remote import could not be fetched (network failure, a non-2xx HTTP
        /// status, or a value that is not a fetchable `http(s)` URL).
        MANI_101 = "MANI-101", Error,
            "remote import fetch failed";

        /// Fetched content hashes to a value that does not match the SHA-256 the
        /// lockfile pins for the same URL (ADR-0002 §7).
        MANI_102 = "MANI-102", Error,
            "fetched content hash does not match the lockfile";

        /// `--frozen` was requested but the lockfile has no entry for a remote
        /// import; a frozen build never regenerates the lockfile (ADR-0002 §7).
        MANI_103 = "MANI-103", Error,
            "`--frozen`: no lockfile entry for a remote import";

        /// `--frozen` was requested and a lockfile-pinned import is not present in
        /// the cache; a frozen build never fetches (ADR-0002 §7).
        MANI_104 = "MANI-104", Error,
            "`--frozen`: a lockfile-pinned import is not cached";
    }
}

/// A diagnostic's severity. Warnings and info diagnostics arrive with later
/// passes; the codes of the first pipeline are all [`Error`](Severity::Error).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Severity {
    Error,
    Warning,
    Info,
}

/// An interned file id, issued by [`SourceMap::file_id`]. It indexes the file's
/// path and text inside the [`SourceMap`], which the renderer reads to draw the
/// source snippet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct FileId(u32);

impl FileId {
    /// A sentinel id for a diagnostic that is not tied to any source file. The
    /// lockfile, cache, and fetch diagnostics (MANI-1xx) concern a URL rather
    /// than a byte span, so they carry this id; [`render`](render()) draws them as a bare
    /// coded message with no source snippet. No [`SourceMap`] ever issues it.
    pub const DETACHED: FileId = FileId(u32::MAX);
}

/// A source location: a byte range inside a specific file. The range is a
/// `rowan::TextRange` — the same coordinate space parse and semantic passes work
/// in — so an offset never has to be translated on the way into a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Span {
    pub file: FileId,
    #[serde(serialize_with = "serialize_text_range")]
    pub range: TextRange,
}

/// Serializes a `rowan::TextRange` as `{ "start": u32, "end": u32 }`, keeping
/// the byte offsets readable and exact in JSON snapshots.
fn serialize_text_range<S: Serializer>(
    range: &TextRange,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    use serde::ser::SerializeStruct;
    let mut state = serializer.serialize_struct("TextRange", 2)?;
    state.serialize_field("start", &u32::from(range.start()))?;
    state.serialize_field("end", &u32::from(range.end()))?;
    state.end()
}

/// A secondary annotation: a span with a message, drawn under the source
/// alongside the primary span.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Label {
    pub span: Span,
    pub message: String,
}

/// A suggested edit: replace the text at `span` with `replacement`. `label`
/// describes the fix for a human. Rendered as a note under the diagnostic; a
/// later LSP task maps it to a code action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FixIt {
    pub span: Span,
    pub replacement: String,
    pub label: String,
}

/// One coded diagnostic. `primary` is the main span the message points at;
/// `labels` are secondary annotations; `fixits` are suggested edits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Diagnostic {
    pub code: DiagCode,
    pub severity: Severity,
    pub message: String,
    pub primary: Span,
    pub labels: Vec<Label>,
    pub fixits: Vec<FixIt>,
}

/// The path and text of one interned file.
#[derive(Debug)]
struct SourceEntry {
    path: String,
    text: String,
}

/// The file table the renderer reads: it maps every [`FileId`] to the path and
/// text a diagnostic's spans point into. Ids are interned by path, so asking for
/// the same path twice returns the same id.
#[derive(Debug, Default)]
pub struct SourceMap {
    files: Vec<SourceEntry>,
}

impl SourceMap {
    /// An empty source map.
    pub fn new() -> Self {
        Self::default()
    }

    /// The [`FileId`] for `path`, interning `path` and `text` on first sight.
    /// A pass holding a file's path and text calls this to stamp its spans.
    pub fn file_id(&mut self, path: &str, text: &str) -> FileId {
        if let Some(index) = self.files.iter().position(|entry| entry.path == path) {
            return FileId(index as u32);
        }
        let id = FileId(self.files.len() as u32);
        self.files.push(SourceEntry {
            path: path.to_string(),
            text: text.to_string(),
        });
        id
    }

    /// The path an interned [`FileId`] stands for, or `None` for an id this map
    /// never issued (including [`FileId::DETACHED`]). This is the reverse of
    /// [`file_id`](Self::file_id): a caller holding a diagnostic's `FileId` reads
    /// back the file it points at without probing candidate paths.
    pub fn path(&self, id: FileId) -> Option<&str> {
        self.files
            .get(id.0 as usize)
            .map(|entry| entry.path.as_str())
    }

    /// The text an interned [`FileId`] stands for, or `None` for an id this map
    /// never issued (including [`FileId::DETACHED`]).
    pub fn text(&self, id: FileId) -> Option<&str> {
        self.files
            .get(id.0 as usize)
            .map(|entry| entry.text.as_str())
    }
}

/// A 1-based line and column. The column counts Unicode scalar values — Rust
/// `char`s — not UTF-8 bytes and not the UTF-16 code units LSP positions use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct LineCol {
    pub line: u32,
    pub column: u32,
}

/// The line and column of a byte `offset` into `text`. An offset past the end
/// of the text, or inside a multi-byte character, is moved back to the nearest
/// character boundary at or before it.
pub fn line_col(text: &str, offset: TextSize) -> LineCol {
    let mut offset = usize::from(offset).min(text.len());
    while !text.is_char_boundary(offset) {
        offset -= 1;
    }
    let before = &text[..offset];
    let line = before.matches('\n').count() as u32 + 1;
    let column = match before.rfind('\n') {
        Some(newline) => before[newline + 1..].chars().count(),
        None => before.chars().count(),
    } as u32
        + 1;
    LineCol { line, column }
}

/// A span in the JSON diagnostic contract: the file's path as registered in the
/// [`SourceMap`] and 1-based start and end positions. `end` is exclusive: the
/// position one past the last character in the span, not the position of the
/// last character itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonSpan {
    pub path: String,
    pub start: LineCol,
    pub end: LineCol,
}

/// A fix-it in the JSON diagnostic contract, verbatim from the compiler.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonFixIt {
    pub label: String,
    pub replacement: String,
    pub span: JsonSpan,
}

/// A label in the JSON diagnostic contract, verbatim from the compiler.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonLabel {
    pub message: String,
    pub span: JsonSpan,
}

/// One diagnostic in the JSON contract `ridl check --format json` and the MCP
/// `ridl_check` tool emit. This is the first agent-facing diagnostic contract
/// (ADR-0005 §7): a change to its shape is a change to an external contract.
/// `code` passes the diagnostic's [`DiagCode`] through verbatim, including the
/// empty string a diagnostic with no assigned catalogue code carries; the
/// field is always present, never omitted. `labels` passes the diagnostic's
/// secondary annotations through verbatim, in the order the diagnostic holds
/// them; the array is always present, empty when the diagnostic carries none.
/// `lint` is the lint name of the code (docs/book/cli-reference.md), present
/// when the code has one and omitted otherwise; `severity` is the effective
/// one after the `[lints]` levels are applied.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonDiagnostic {
    pub code: String,
    pub severity: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lint: Option<String>,
    pub message: String,
    pub span: JsonSpan,
    pub labels: Vec<JsonLabel>,
    pub fixes: Vec<JsonFixIt>,
}

fn json_span(span: Span, sources: &SourceMap) -> JsonSpan {
    let path = sources.path(span.file).unwrap_or("").to_string();
    let text = sources.text(span.file).unwrap_or("");
    JsonSpan {
        path,
        start: line_col(text, span.range.start()),
        end: line_col(text, span.range.end()),
    }
}

fn severity_name(severity: Severity) -> &'static str {
    match severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "info",
    }
}

/// Projects `diagnostics` onto the JSON contract, resolving every span through
/// `sources`.
pub fn to_json(diagnostics: &[Diagnostic], sources: &SourceMap) -> Vec<JsonDiagnostic> {
    diagnostics
        .iter()
        .map(|diagnostic| JsonDiagnostic {
            code: diagnostic.code.0.to_string(),
            severity: severity_name(diagnostic.severity).to_string(),
            lint: crate::lint::lint_of(diagnostic.code)
                .and_then(|entry| entry.lint)
                .map(str::to_string),
            message: diagnostic.message.clone(),
            span: json_span(diagnostic.primary, sources),
            labels: diagnostic
                .labels
                .iter()
                .map(|label| JsonLabel {
                    message: label.message.clone(),
                    span: json_span(label.span, sources),
                })
                .collect(),
            fixes: diagnostic
                .fixits
                .iter()
                .map(|fixit| JsonFixIt {
                    label: fixit.label.clone(),
                    replacement: fixit.replacement.clone(),
                    span: json_span(fixit.span, sources),
                })
                .collect(),
        })
        .collect()
}

/// Remaps per-package diagnostics onto a renderer's [`SourceMap`] ids.
///
/// The package-scoped passes (`resolve_package`, `check_package` in
/// `ridl-sem`) stamp their spans with a [`FileId`] that indexes the package's
/// `files` **in order** — they run inside salsa queries and cannot share the
/// caller's [`SourceMap`]. A renderer first interns each package file into its
/// own map (collecting the issued ids in the same file order), then calls this
/// to rewrite every span onto those ids. [`FileId::DETACHED`] spans and any
/// index past `render_ids` are left untouched.
pub fn remap_diagnostics(
    diagnostics: impl IntoIterator<Item = Diagnostic>,
    render_ids: &[FileId],
) -> Vec<Diagnostic> {
    let remap_file =
        |file: FileId| -> FileId { render_ids.get(file.0 as usize).copied().unwrap_or(file) };
    diagnostics
        .into_iter()
        .map(|mut diagnostic| {
            diagnostic.primary.file = remap_file(diagnostic.primary.file);
            for label in &mut diagnostic.labels {
                label.span.file = remap_file(label.span.file);
            }
            for fixit in &mut diagnostic.fixits {
                fixit.span.file = remap_file(fixit.span.file);
            }
            diagnostic
        })
        .collect()
}

/// One row of a diagnostic catalogue: a code, its default severity, and a short
/// human summary. The catalogue is the static SSOT the error index reads;
/// the per-diagnostic [`Severity`] a pass emits is set independently.
#[derive(Debug, Clone, Copy)]
pub struct CatalogEntry {
    pub code: DiagCode,
    pub severity: Severity,
    pub summary: &'static str,
    /// The lint name, present exactly when `severity` is Warning or Info
    /// (ADR-0024 decision 1). The catalogue severity is the lint's default
    /// level, unless `allow_by_default` is set. A released name is never
    /// renamed or reused.
    pub lint: Option<&'static str>,
    /// Whether the lint's default level is `allow` rather than the level of
    /// its severity (ADR-0024 decision 1). Only a lint row sets it.
    pub allow_by_default: bool,
}

/// Polishes a raw parser message into the house diagnostic style —
/// description-first, with backticked names (fixes issue #102). Most parser
/// messages are already house-style and pass through unchanged; the parser's
/// `expect` path emits a `Debug`-shaped token name (`expected RBracket`), which
/// this maps to a backticked glyph (`` expected `]` ``).
///
/// Keeping the raw parser message as the input leaves `ridl-syntax` and its
/// tests untouched — they assert on codes and ranges, not message text — while
/// the rendered diagnostics still read in one consistent style.
pub fn house_style_message(raw: &str) -> String {
    if let Some(token) = raw.strip_prefix("expected ")
        && let Some(glyph) = punctuation_glyph(token)
    {
        return format!("expected {glyph}");
    }
    raw.to_string()
}

/// The backticked glyph for a punctuation or operator `SyntaxKind` `Debug`
/// name, or `None` when the name is not a known single-glyph token. Covers every
/// kind the parser can name in a FORM-101 `expected` message, so the mapping
/// stays correct if new `expect` call sites are added — an invariant the
/// `every_expectable_token_has_a_glyph` test enforces against the parser source.
fn punctuation_glyph(debug_name: &str) -> Option<&'static str> {
    Some(match debug_name {
        "Colon" => "`:`",
        "Eq" => "`=`",
        "Semicolon" => "`;`",
        "Comma" => "`,`",
        "LBracket" => "`[`",
        "RBracket" => "`]`",
        "LBrace" => "`{`",
        "RBrace" => "`}`",
        "LParen" => "`(`",
        "RParen" => "`)`",
        "DotDot" => "`..`",
        "Dot" => "`.`",
        "Question" => "`?`",
        "At" => "`@`",
        "Pipe" => "`|`",
        // `>` closes a stream type `<T>` (ridl reference §12), which is the
        // one operator token the parser reaches through `expect`.
        "Gt" => "`>`",
        _ => return None,
    })
}

impl SourceMap {
    /// The interned files, in id order — the renderer replays them into a
    /// `codespan_reporting` file table so `FileId(i)` lines up with codespan id
    /// `i`.
    pub fn iter_files(&self) -> impl Iterator<Item = (&str, &str)> {
        self.files
            .iter()
            .map(|entry| (entry.path.as_str(), entry.text.as_str()))
    }
}

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

    #[test]
    fn source_map_interns_by_path() {
        let mut map = SourceMap::new();
        let a = map.file_id("a.typl", "type A: m");
        let b = map.file_id("b.typl", "type B: s");
        let a_again = map.file_id("a.typl", "type A: m");
        assert_ne!(a, b, "distinct paths get distinct ids");
        assert_eq!(a, a_again, "the same path interns to the same id");
    }

    #[test]
    fn source_map_path_reverses_file_id() {
        let mut map = SourceMap::new();
        let a = map.file_id("a.typl", "type A: m");
        let b = map.file_id("b.typl", "type B: s");
        assert_eq!(map.path(a), Some("a.typl"));
        assert_eq!(map.path(b), Some("b.typl"));
        assert_eq!(
            map.path(FileId::DETACHED),
            None,
            "a detached id has no path"
        );
        assert_eq!(
            map.path(FileId(2)),
            None,
            "an id the map never issued has no path",
        );
    }

    #[test]
    fn remap_diagnostics_rewrites_package_relative_ids() {
        // A render map that already interned an unrelated file, so the render
        // ids do not coincide with the package-relative indices.
        let mut render = SourceMap::new();
        let _other = render.file_id("other.typl", "");
        let a = render.file_id("pkg/a.typl", "type A: m");
        let b = render.file_id("pkg/b.typl", "type B: s");
        let render_ids = vec![a, b];

        let span = |file: FileId| Span {
            file,
            range: TextRange::default(),
        };
        let diagnostic = |file: FileId| Diagnostic {
            code: DiagCode::TYPL_009,
            severity: Severity::Error,
            message: "duplicate declaration of `X`".to_string(),
            primary: span(file),
            labels: vec![Label {
                span: span(file),
                message: "first declared here".to_string(),
            }],
            fixits: Vec::new(),
        };

        // Package-relative ids 0 and 1, plus a detached diagnostic.
        let mut pass_map = SourceMap::new();
        let pkg_a = pass_map.file_id("pkg/a.typl", "type A: m");
        let pkg_b = pass_map.file_id("pkg/b.typl", "type B: s");
        let remapped = remap_diagnostics(
            vec![
                diagnostic(pkg_a),
                diagnostic(pkg_b),
                diagnostic(FileId::DETACHED),
            ],
            &render_ids,
        );

        assert_eq!(remapped[0].primary.file, a);
        assert_eq!(remapped[0].labels[0].span.file, a);
        assert_eq!(remapped[1].primary.file, b);
        assert_eq!(
            remapped[2].primary.file,
            FileId::DETACHED,
            "a detached diagnostic stays detached",
        );
    }

    /// The rendered text for every `SyntaxKind` the parser hands to `expect`.
    ///
    /// One row per kind in the reachable set the
    /// `every_expectable_token_has_a_glyph` test derives, so a wrong glyph is
    /// caught here and a missing one is caught there.
    #[test]
    fn house_style_rewrites_debug_token_names() {
        assert_eq!(house_style_message("expected RBracket"), "expected `]`");
        assert_eq!(house_style_message("expected Colon"), "expected `:`");
        assert_eq!(house_style_message("expected Eq"), "expected `=`");
        assert_eq!(house_style_message("expected Semicolon"), "expected `;`");
        assert_eq!(house_style_message("expected RParen"), "expected `)`");
        assert_eq!(house_style_message("expected DotDot"), "expected `..`");
        // Reached since stream types landed: `query a(): <Speed` with no `>`.
        assert_eq!(house_style_message("expected Gt"), "expected `>`");
    }

    /// Every `SyntaxKind` the parser hands to `expect` has a glyph.
    ///
    /// `expect` is the one call site in the workspace that formats a
    /// `SyntaxKind` `Debug` name into a diagnostic message, and every caller of
    /// [`house_style_message`] feeds it a parser message, so the set of kinds
    /// that can reach [`punctuation_glyph`] is exactly the set of literal
    /// arguments `expect` is called with. A kind outside the table renders as
    /// its raw `Debug` name — `expected Gt` reached users this way, because
    /// stream types added an `expect(SyntaxKind::Gt)` call site and nothing
    /// tied the two files together.
    ///
    /// The first assertion pins that single-producer premise, and pins it
    /// **workspace-wide**: a second `Debug`-shaped emitter anywhere would widen
    /// the reachable set past what the scan below reads, so it has to fail
    /// rather than pass silently. Reading only the parser would leave the
    /// premise's own scope unchecked — the same shape of gap as the one this
    /// test exists to close.
    #[test]
    fn every_expectable_token_has_a_glyph() {
        const CALL: &str = ".expect(SyntaxKind::";

        let root = workspace_root();
        let mut sources = Vec::new();
        collect_rust_sources(&root, &mut sources);
        assert!(
            sources.len() >= 60,
            "the walk found only {} `.rs` files under {} — it is not reaching \
             the workspace",
            sources.len(),
            root.display(),
        );

        let parser = root.join("crates/ridl-syntax/src/parser.rs");
        let emitters: Vec<String> = sources
            .iter()
            .filter(|path| {
                let text = std::fs::read_to_string(path)
                    .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
                let stripped = strip_line_comments(&text);
                stripped
                    .match_indices(r#""expected {"#)
                    .any(|(at, matched)| is_whole_debug_message(&stripped[at + matched.len()..]))
            })
            .map(|path| path.display().to_string())
            .collect();
        assert_eq!(
            emitters,
            vec![parser.display().to_string()],
            "the workspace no longer has exactly one message that is a \
             `Debug`-formatted token name and nothing else, so the reachable \
             kinds are no longer just `expect`'s arguments in the parser. Either \
             route the new emitter through `expect`, or widen the scan below to \
             read its argument too",
        );

        let text = std::fs::read_to_string(&parser)
            .unwrap_or_else(|err| panic!("cannot read {}: {err}", parser.display()));
        let despaced: String = strip_line_comments(&text)
            .chars()
            .filter(|c| !c.is_whitespace())
            .collect();
        let mut expectable = std::collections::BTreeSet::new();
        for (at, _) in despaced.match_indices(CALL) {
            let rest = &despaced[at + CALL.len()..];
            let end = rest
                .find(')')
                .expect("an `expect` call closes its parenthesis");
            expectable.insert(rest[..end].to_string());
        }

        assert!(
            expectable.len() >= 7,
            "the scan found only {} expectable kinds in {} — it is not reading \
             the call sites",
            expectable.len(),
            parser.display(),
        );
        for kind in &expectable {
            assert!(
                punctuation_glyph(kind).is_some(),
                "the parser can emit `expected {kind}`, which renders the raw \
                 `Debug` name to the user. Add `{kind}` to `punctuation_glyph`.",
            );
        }
    }

    #[test]
    fn house_style_passes_through_already_styled_messages() {
        // Already description-first with backticks — unchanged.
        assert_eq!(house_style_message("expected a name"), "expected a name");
        assert_eq!(house_style_message("unclosed `{`"), "unclosed `{`");
        assert_eq!(
            house_style_message("missing `package` declaration"),
            "missing `package` declaration",
        );
    }

    /// Every catalogue entry is well formed, every catalogue is sorted, and no
    /// code is declared twice.
    ///
    /// This is what is left to check once [`diag_codes!`] produces the
    /// catalogues. Completeness is structural — the constant and its entry come
    /// out of the same line — so the assertions here cover only the properties
    /// the expansion does not fix. There is deliberately no expected list of
    /// codes: comparing a catalogue against a second hand-written list is the
    /// guard this change removed.
    /// A retired code is never declared again (ADR-0008 decision 13): every
    /// number in [`RETIRED_RIDL_CODES`] stays out of the `RIDL-` catalogue.
    #[test]
    fn retired_ridl_codes_are_never_redeclared() {
        for entry in RIDL_CATALOG {
            let code = entry.code.as_str();
            let number: u16 = code
                .strip_prefix("RIDL-")
                .and_then(|digits| digits.parse().ok())
                .unwrap_or_else(|| panic!("`{code}` is not spelled `RIDL-NNN`"));
            assert!(
                !RETIRED_RIDL_CODES.contains(&number),
                "`{code}` is retired and must not be declared again",
            );
        }
    }

    /// A retired `TYPL-` code is never declared again: every number in
    /// [`RETIRED_TYPL_CODES`] stays out of the `TYPL-` catalogue.
    #[test]
    fn retired_typl_codes_are_never_redeclared() {
        for entry in TYPL_CATALOG {
            let code = entry.code.as_str();
            let number: u16 = code
                .strip_prefix("TYPL-")
                .and_then(|digits| digits.parse().ok())
                .unwrap_or_else(|| panic!("`{code}` is not spelled `TYPL-NNN`"));
            assert!(
                !RETIRED_TYPL_CODES.contains(&number),
                "`{code}` is retired and must not be declared again",
            );
        }
    }

    #[test]
    fn catalog_entries_are_well_formed_ordered_and_unique() {
        let mut seen: Vec<&str> = Vec::new();
        for (name, catalog) in ALL_CATALOGS {
            let prefix = name
                .strip_suffix("_CATALOG")
                .unwrap_or_else(|| panic!("`{name}` is not named `<PREFIX>_CATALOG`"));
            let mut previous = "";
            for entry in *catalog {
                let code = entry.code.as_str();
                let (written_prefix, number) = code
                    .split_once('-')
                    .unwrap_or_else(|| panic!("`{code}` is not spelled `PREFIX-NNN`"));
                assert_eq!(
                    written_prefix, prefix,
                    "`{code}` is listed in {name}, which holds the `{prefix}-` namespace",
                );
                assert!(
                    number.len() == 3 && number.bytes().all(|byte| byte.is_ascii_digit()),
                    "`{code}` does not carry a three-digit number",
                );
                assert!(!entry.summary.is_empty(), "`{code}` has an empty summary");
                // Codes in one catalogue share a prefix and a three-digit
                // number, so byte order is numeric order.
                assert!(
                    previous < code,
                    "{name} is out of order: `{previous}` is listed before `{code}`",
                );
                previous = code;
                assert!(
                    !seen.contains(&code),
                    "`{code}` is declared in more than one catalogue",
                );
                seen.push(code);
            }
        }
        // Width. The loops above say nothing if `ALL_CATALOGS` is ever empty.
        // The macro cannot produce an empty one, but a floor makes a vacuous
        // pass unreachable rather than merely unlikely, and codes are never
        // withdrawn (ADR-0007 decision 2), so the bound only gets safer.
        assert!(
            seen.len() >= 90,
            "only {} codes reached the catalogues — the guards below are \
             checking almost nothing",
            seen.len(),
        );
    }

    /// A row may declare `allow` as its default level (ADR-0024 decision 1),
    /// and only a lint row may: an Error row has no level to declare.
    #[test]
    fn allow_by_default_is_only_on_warning_or_info_rows() {
        for entry in ALL_CATALOGS.iter().flat_map(|(_, c)| c.iter()) {
            if entry.allow_by_default {
                assert_ne!(entry.severity, Severity::Error, "{}", entry.code.as_str());
                assert!(entry.lint.is_some(), "{}", entry.code.as_str());
            }
        }
    }

    /// Every Warning and Info row carries a lint name and no Error row does;
    /// each name is lowercase words joined by `-`; no two rows share a name;
    /// and the `(code, name)` pairs are the expected list below, which mirrors
    /// the table in docs/book/lints.md (`book_lints.rs` checks that table).
    #[test]
    fn lint_names_are_present_exactly_on_warnings_and_infos_and_unique() {
        fn is_lint_name(name: &str) -> bool {
            // `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, checked without a regex crate.
            name.starts_with(|c: char| c.is_ascii_lowercase())
                && name.split('-').all(|word| {
                    !word.is_empty()
                        && word
                            .chars()
                            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
                })
        }

        let mut names = std::collections::BTreeSet::new();
        let mut pairs = std::collections::BTreeSet::new();
        for (_, catalog) in ALL_CATALOGS {
            for entry in *catalog {
                let code = entry.code.as_str();
                match entry.severity {
                    Severity::Error => assert_eq!(
                        entry.lint, None,
                        "`{code}` is an Error and must not have a lint name",
                    ),
                    Severity::Warning | Severity::Info => {
                        let name = entry.lint.unwrap_or_else(|| {
                            panic!("`{code}` is a Warning or Info and has no lint name")
                        });
                        assert!(
                            is_lint_name(name),
                            "`{code}` has the lint name `{name}`, which does not \
                             match `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`",
                        );
                        assert!(
                            names.insert(name),
                            "the lint name `{name}` is used by more than one row",
                        );
                        pairs.insert((code, name));
                    }
                }
            }
        }

        let expected: std::collections::BTreeSet<(&str, &str)> = [
            ("TYPL-007", "unused-import"),
            ("TYPL-008", "unneeded-import-alias"),
            ("TYPL-101", "unbounded-integer"),
            ("TYPL-102", "unbounded-float"),
            ("TYPL-103", "unbounded-length"),
            ("TYPL-115", "no-init-value"),
            ("TYPL-211", "duplicate-reserved"),
            ("TYPL-222", "inconsistent-unit"),
            ("TYPL-224", "duplicate-shape"),
            ("TYPL-401", "broken-doc-link"),
            ("TYPL-404", "detached-doc-comment"),
            ("TYPL-405", "deprecated-without-reason"),
            ("TYPL-406", "missing-docs"),
            ("TYPL-407", "misplaced-doc-comment"),
            ("TYPL-408", "unknown-doc-tag"),
            ("TYPL-409", "malformed-doc-tag"),
            ("TYPL-410", "doc-comment-style"),
            ("RIDL-100", "missing-timing"),
            ("RIDL-108", "degenerate-timing-range"),
            ("RIDL-112", "missing-response-bound"),
            ("RIDL-304", "error-typed-parameter"),
            ("RIDL-305", "ensure-without-result"),
            ("RIDL-307", "contract-error-name-in-enum"),
            ("RIDL-308", "named-result-union-in-query"),
            ("RIDL-404", "query-named-like-mutation"),
            ("RIDL-405", "shared-error-type"),
            ("RIDL-406", "redeclared-envelope-metadata"),
            ("RIDL-407", "ordinal-changed"),
            ("RIDL-414", "low-cohesion-interface"),
            ("RSDL-409", "redundant-provider-set"),
            ("RSDL-804", "unclaimed-backend-key"),
            ("RSDL-805", "depth-below-bound"),
            ("RSDL-806", "depth-underivable"),
            ("MANI-005", "unknown-manifest-key"),
            ("MANI-010", "unknown-lint"),
        ]
        .into_iter()
        .collect();
        assert_eq!(
            pairs, expected,
            "the lint names differ from the expected list in this test"
        );
    }

    /// Each constant's name is the code string it expands to, with `-` written
    /// `_`.
    ///
    /// [`diag_codes!`] takes the two side by side — `TYPL_007 = "TYPL-007"` — so
    /// a typo can still pair a name with another code's string, and every
    /// emission through that constant would then render the wrong code.
    /// `CODE_CONSTANT_NAMES` comes out of the same entries, so this compares the
    /// expansion against itself and not against a list someone maintains.
    #[test]
    fn each_constant_name_is_the_code_it_expands_to() {
        for (name, code) in CODE_CONSTANT_NAMES {
            assert_eq!(
                &name.replace('_', "-"),
                code,
                "`DiagCode::{name}` expands to `{code}`",
            );
        }
        assert!(CODE_CONSTANT_NAMES.len() >= 90, "the entry list went empty");
    }

    /// The two namespace-wide severity rules: every FORM code is an error, and
    /// every MANI code is an error but the unknown-key and unknown-lint warnings.
    ///
    /// Neither rule enumerates codes, so neither is a shadow list — one states a
    /// property of a whole namespace, the other adds two named exceptions.
    /// TYPL and RIDL have no such rule: their severities are per-code, set by
    /// the reference §16 tables, and writing them out here would rebuild exactly
    /// the second list this change removed. A wrong severity on a TYPL or RIDL
    /// entry is not caught by anything in this module.
    #[test]
    fn form_and_mani_severities_follow_their_namespace_rule() {
        for entry in FORM_CATALOG {
            assert_eq!(
                entry.severity,
                Severity::Error,
                "every FORM code is an error, but {} is not",
                entry.code.as_str(),
            );
        }
        for entry in MANI_CATALOG {
            let expected = if entry.code == DiagCode::MANI_005 || entry.code == DiagCode::MANI_010 {
                Severity::Warning
            } else {
                Severity::Error
            };
            assert_eq!(
                entry.severity,
                expected,
                "unexpected severity for {}",
                entry.code.as_str(),
            );
        }
    }

    /// Every `"PREFIX-NNN"` string literal in the workspace's Rust sources names
    /// a catalogued code.
    ///
    /// This is the half [`diag_codes!`] cannot reach, and it is not a handful of
    /// call sites that forgot to use the type — it is a layering fact.
    /// `crates/ridl-syntax` cannot reference [`DiagCode`] at all: `ridl-core`
    /// depends on `ridl-syntax`, so the edge cannot run the other way, and
    /// `SyntaxError::code` is a `&'static str` by construction. Every code the
    /// lexer and parser emit is therefore a bare string literal — 11 distinct
    /// codes across 74 call sites when this guard was written. Five of them have
    /// no `DiagCode::` reference anywhere and their constants are dead
    /// declarations (FORM-005, FORM-104, FORM-105, RIDL-403, TYPL-304); TYPL-303
    /// had no constant at all until this change added one. Repairing that means
    /// moving the codes somewhere both crates can see, which is its own change
    /// (issue #172).
    ///
    /// **What this catches.** A code emitted, asserted, or declared anywhere in
    /// the workspace's `.rs` files that no catalogue lists — a new parser
    /// diagnostic included, verified by renaming the parser's TYPL-303 emission
    /// and watching this fail and name the file.
    ///
    /// **What this does not catch**, and must not be read as covering:
    ///
    /// - a code assembled rather than spelled: `concat!("TYPL-", "303")`, or one
    ///   built at run time. The scan is textual. `diag_codes!` takes a `literal`
    ///   so the assembled form cannot be written inside it, and
    ///   `no_diagnostic_constant_is_declared_outside_the_macro` covers the
    ///   hand-written-constant case; a `concat!` at a *parser* emission site
    ///   evades both;
    /// - a code spelled **inside a longer literal**, such as
    ///   `"error[TYPL-905]: boom"`. A quote is required on both sides of the
    ///   code, which is what keeps prose out, and it is also what lets an
    ///   embedded code through;
    /// - a **four-digit** code, `"TYPL-9060"`. The scan takes exactly three
    ///   digits followed by the closing quote, matching the shape ADR-0007
    ///   decision 2 fixes. Neither of these two is live: an audit of all 104
    ///   `PREFIX-NNN` occurrences in `.rs` sources regardless of quoting found
    ///   the only uncatalogued ones are the reserved codes and the typl §16
    ///   codes named below, every one of them in prose;
    /// - a code written in a **comment**, which is stripped before the scan
    ///   runs. Nothing emits a diagnostic from a comment, and leaving comments
    ///   in made this file report its own prose about reserved and absent
    ///   codes;
    /// - a code written only in Markdown, in a `.typl`/`.ridl` fixture, or in a
    ///   snapshot. The typl reference §16 documents five codes no constant
    ///   declares — TYPL-107, TYPL-112, TYPL-205, TYPL-402 and TYPL-403 — so
    ///   widening the scan to `.md` would fail today. That inventory belongs to
    ///   issue #172, not to this guard;
    /// - a catalogued code that nothing emits. FORM-001 to FORM-004 are declared
    ///   and catalogued and no pass emits them;
    /// - a code **withdrawn** from a catalogue. Deleting an entry deletes its
    ///   constant, so any code a pass emits through `DiagCode::` stops the build
    ///   — but a code nothing references, such as FORM-001, can be removed and
    ///   nothing here notices. The floor in
    ///   `catalog_entries_are_well_formed_ordered_and_unique` catches a bulk
    ///   withdrawal, not a single one;
    /// - a wrong severity, or a summary that describes the wrong rule, on an
    ///   entry that exists.
    #[test]
    fn codes_written_as_string_literals_are_all_catalogued() {
        let root = workspace_root();
        let mut sources = Vec::new();
        collect_rust_sources(&root, &mut sources);

        let catalogued: std::collections::BTreeSet<&str> = ALL_CATALOGS
            .iter()
            .flat_map(|(_, catalog)| catalog.iter().map(|entry| entry.code.as_str()))
            .collect();

        let mut uncatalogued: Vec<String> = Vec::new();
        let mut files_holding_codes = 0usize;
        let mut codes_outside_this_module: std::collections::BTreeSet<String> =
            std::collections::BTreeSet::new();

        for path in &sources {
            let text = std::fs::read_to_string(path)
                .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
            // Comments first: a diagnostic is never emitted from one, and prose
            // about a code that is deliberately absent — a reserved number, a
            // worked example of the shape this file rejects — would otherwise
            // be reported as an escape.
            let text = strip_line_comments(&text);
            let literals = code_literals(&text);
            if !literals.is_empty() {
                files_holding_codes += 1;
            }
            let is_this_module = path.ends_with("ridl-core/src/diag.rs");
            for code in literals {
                if !catalogued.contains(code) {
                    uncatalogued.push(format!("{}: {code}", path.display()));
                }
                if !is_this_module {
                    codes_outside_this_module.insert(code.to_string());
                }
            }
        }

        assert!(
            uncatalogued.is_empty(),
            "these code strings are written in Rust sources but no catalogue \
             lists them, so the error index has nothing to key them on \
             and nothing connects them to a `DiagCode`. Declare each one in \
             `diag_codes!`:\n{}",
            uncatalogued.join("\n"),
        );

        // Width. Every assertion above is vacuous if the walk finds nothing, and
        // a walk rooted at the wrong directory finds nothing quietly. These
        // floors are well under what the workspace holds today — 79 `.rs` files,
        // 21 of them carrying a code, 92 distinct codes outside this module —
        // and fail loudly if the scan stops reaching past its own crate. The
        // three figures are measured, not maintained: they are a comment, and
        // the assertions below hold whether or not they drift.
        assert!(
            sources.len() >= 60,
            "the walk found only {} `.rs` files under {} — it is not reaching \
             the workspace",
            sources.len(),
            root.display(),
        );
        assert!(
            files_holding_codes >= 10,
            "only {files_holding_codes} files carried a code literal",
        );
        assert!(
            codes_outside_this_module.len() >= 60,
            "only {} distinct codes were seen outside `diag.rs` — the scan is \
             checking this module against itself",
            codes_outside_this_module.len(),
        );
    }

    /// No `DiagCode` constant is declared outside [`diag_codes!`], anywhere in
    /// the workspace.
    ///
    /// The scan above already reports a hand-written constant whose code is
    /// spelled as a literal, because the literal is what it looks for — but one
    /// whose code is assembled compiles and slips past it. This catches that
    /// form, and any other, by looking at the declaration rather than at the
    /// code string.
    ///
    /// The surface is the whole workspace, not this crate. An inherent
    /// `impl DiagCode` can only be written here, but the newtype's field is
    /// public, so any crate can construct one and give it a name. A constant of
    /// this type declared in `ridl-sem` with an assembled code compiles and
    /// passes both the suite and clippy when this walks `ridl-core` alone, so it
    /// walks everything.
    ///
    /// Matching is whitespace-insensitive and accepts a path-qualified type,
    /// because a declaration in another crate writes the type as
    /// `ridl_core::diag::…` and rustfmt may break it across lines. Comments are
    /// stripped first, so prose describing the forbidden shape — including this
    /// paragraph — does not report itself; the cost is that a `//` inside a
    /// string literal hides the rest of that line from the scan.
    ///
    /// It remains a textual check: it recognises the two shapes a `DiagCode`
    /// constant is written in and rejects everything else, so a declaration
    /// reworded to avoid both evades it. The two evasions are not symmetric,
    /// and only their combination gets through:
    ///
    /// - a declaration writing the type under an alias (`use … DiagCode as DC;`
    ///   then `const RIDL_199: DC = DC("RIDL-199");`) is invisible here, but its
    ///   code is spelled, so `codes_written_as_string_literals_are_all_catalogued`
    ///   reports it;
    /// - a declaration with an assembled code is invisible to that scan, but
    ///   names the type, so this one reports it — verified against a qualified,
    ///   line-broken `concat!` declaration in `ridl-sem` and against one in a
    ///   child module of `diag`;
    /// - **both at once** — an aliased type and an assembled code — passes the
    ///   whole workspace suite and clippy. That is a surviving escape, and it is
    ///   a deliberate act rather than the omission this file defends against.
    #[test]
    fn no_diagnostic_constant_is_declared_outside_the_macro() {
        // Assembled rather than spelled: this test lives in a file it scans, so
        // writing the shapes out whole would make the test report itself.
        let anchor = format!("DiagCode{}", '=');
        // The macro body, expanding one entry into its constant.
        let in_macro = format!("pubconst$konst:{anchor}DiagCode($code);");
        // The sentinel, which has no catalogue entry by design.
        let sentinel = format!("pubconstNONE:{anchor}DiagCode(\"\");");
        let accepted = [in_macro.as_str(), sentinel.as_str()];

        let root = workspace_root();
        let mut sources = Vec::new();
        collect_rust_sources(&root, &mut sources);
        assert!(
            sources.len() >= 60,
            "the walk found only {} `.rs` files under {} — it is not reaching \
             the workspace",
            sources.len(),
            root.display(),
        );

        let mut declarations = 0usize;
        for path in &sources {
            let text = std::fs::read_to_string(path)
                .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
            let stripped = strip_line_comments(&text);
            let despaced: String = stripped.chars().filter(|c| !c.is_whitespace()).collect();

            for (at, _) in despaced.match_indices(&anchor) {
                let recognised = accepted.iter().any(|form| {
                    let offset = form.find(&anchor).expect("each form holds the anchor");
                    at >= offset && despaced[at - offset..].starts_with(form)
                });
                assert!(
                    recognised,
                    "{}: `…{}…` declares a `DiagCode` constant outside \
                     `diag_codes!`, so it carries no catalogue entry. Move it \
                     into the macro.",
                    path.display(),
                    &despaced[at.saturating_sub(40)..(at + 40).min(despaced.len())],
                );
                declarations += 1;
            }
        }
        assert_eq!(
            declarations, 2,
            "expected exactly two `DiagCode` constant declarations in the \
             workspace — the macro body and the `NONE` sentinel, both in this \
             file",
        );
    }

    /// The family overview's `FORM-` and `MANI-` tables list exactly the codes
    /// this module declares, at the same severities.
    ///
    /// The overview says of those two tables that `crates/ridl-core/src/diag.rs`
    /// "is the single source of truth these two tables mirror" — and until this
    /// test, nothing checked the mirror. A code added to one and not the other
    /// compiled and passed, and so did a severity that disagreed; the drift was
    /// found the ordinary way, by a reviewer reading both.
    ///
    /// **Codes and severities only.** The `Rule` column is prose written for a
    /// reader and the catalogue `summary` is written for the error index, so
    /// they are deliberately not compared — pinning two prose strings to each
    /// other would make every wording improvement a two-file edit for no gain.
    /// What this catches is a code present in one list and absent from the
    /// other, and a severity that disagrees. What it does not catch is a row
    /// whose prose describes the wrong rule.
    ///
    /// TYPL and RIDL have no counterpart here: their tables live in their own
    /// language references, and those tables carry codes no constant declares
    /// yet (typl §16 documents six, recorded in issue #172), so the same
    /// equality would fail today for a reason that is not drift.
    #[test]
    fn the_overview_form_and_mani_tables_mirror_the_catalogues() {
        let overview = workspace_root().join("docs/specification/ridl-family-overview.md");
        let text = std::fs::read_to_string(&overview)
            .unwrap_or_else(|err| panic!("cannot read {}: {err}", overview.display()));

        // `| CODE | rule | severity |`, tolerant of the column padding prim
        // applies. A row whose severity word is unknown is a malformed table,
        // not something to skip quietly.
        let mut documented: Vec<(String, Severity)> = Vec::new();
        for line in text.lines() {
            let mut cells = line.split('|').map(str::trim);
            if cells.next() != Some("") {
                continue;
            }
            let (Some(code), Some(_rule), Some(severity)) =
                (cells.next(), cells.next(), cells.next())
            else {
                continue;
            };
            if !(code.starts_with("FORM-") || code.starts_with("MANI-")) {
                continue;
            }
            let severity = match severity {
                "error" => Severity::Error,
                "warning" => Severity::Warning,
                "info" => Severity::Info,
                other => panic!("{code} in the overview carries no severity: `{other}`"),
            };
            documented.push((code.to_string(), severity));
        }

        let declared: Vec<(String, Severity)> = FORM_CATALOG
            .iter()
            .chain(MANI_CATALOG)
            .map(|entry| (entry.code.as_str().to_string(), entry.severity))
            .collect();

        let names = |rows: &[(String, Severity)]| -> Vec<String> {
            let mut names: Vec<String> = rows.iter().map(|(code, _)| code.clone()).collect();
            names.sort();
            names
        };
        assert_eq!(
            names(&documented),
            names(&declared),
            "the family overview §7 tables and the FORM/MANI catalogues list \
             different codes — {} documents the two namespaces `diag.rs` owns, \
             so a code minted in one belongs in the other",
            overview.display(),
        );

        for (code, severity) in &declared {
            let (_, documented_severity) = documented
                .iter()
                .find(|(name, _)| name == code)
                .expect("the code sets are equal");
            assert_eq!(
                documented_severity, severity,
                "{code} is {severity:?} in the catalogue and \
                 {documented_severity:?} in the overview",
            );
        }

        // Width: a scan that matched nothing would satisfy both assertions
        // against an empty catalogue, and cannot against a real one.
        assert!(
            documented.len() >= 25,
            "only {} rows were read out of the overview tables — the parse is \
             not finding them",
            documented.len(),
        );
    }

    /// Whether `rest` — the source just past a `"expected {` — closes the
    /// format string immediately as `ident:?}"`, making the whole message a
    /// `Debug`-formatted value and nothing else.
    ///
    /// That exact shape is what reaches [`punctuation_glyph`]: anything with
    /// prose after the placeholder (`"expected {text:?} to parse"`) is not a
    /// bare token name, and a `Display` placeholder (`"expected {name}"`) is not
    /// a `Debug` name. Both occur in the workspace and both are correctly
    /// ignored. What this does not catch is an emitter that formats the name
    /// through a variable rather than inline; no such site exists, and the
    /// recurrence worth guarding is a second `expect`-shaped helper.
    fn is_whole_debug_message(rest: &str) -> bool {
        let Some(colon) = rest.find(':') else {
            return false;
        };
        let placeholder = &rest[..colon];
        !placeholder.is_empty()
            && placeholder
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_')
            && rest[colon..].starts_with(":?}\"")
    }

    /// `text` with every `//` line comment removed, so prose about a forbidden
    /// code shape is not mistaken for the shape itself. A `//` inside a string
    /// literal takes the rest of its line with it.
    fn strip_line_comments(text: &str) -> String {
        text.lines()
            .map(|line| match line.find("//") {
                Some(at) => &line[..at],
                None => line,
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The workspace root: two levels above `crates/ridl-core`.
    fn workspace_root() -> std::path::PathBuf {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .and_then(std::path::Path::parent)
            .expect("`crates/ridl-core` sits two levels below the workspace root")
            .to_path_buf();
        let manifest = std::fs::read_to_string(root.join("Cargo.toml"))
            .unwrap_or_else(|err| panic!("no manifest at {}: {err}", root.display()));
        assert!(
            manifest.contains("[workspace]"),
            "{} is not the workspace root",
            root.display(),
        );
        root
    }

    /// Every `.rs` file under `dir`, skipping `target` and dot-directories — the
    /// latter keeps the walk out of `.git` and out of any `.claude/worktrees`
    /// checkout of this same repository.
    fn collect_rust_sources(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        let entries = std::fs::read_dir(dir)
            .unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display()));
        for entry in entries {
            let entry = entry.unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display()));
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.starts_with('.') || name == "target" {
                continue;
            }
            let path = entry.path();
            if path.is_dir() {
                collect_rust_sources(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    /// Every `"PREFIX-NNN"` string literal in `text`, where `PREFIX` is two or
    /// more uppercase ASCII letters.
    ///
    /// The quotes are required on both sides, which is what keeps prose out: the
    /// doc comments in this module name RIDL-111 and RIDL-142 as reserved and
    /// not yet declared, and a scan that read unquoted text would report them.
    /// Matching is position-local rather than quote-pairing, so an escaped quote
    /// earlier in a string cannot shift the scan out of alignment.
    fn code_literals(text: &str) -> Vec<&str> {
        let bytes = text.as_bytes();
        let mut found = Vec::new();
        for dash in 0..bytes.len() {
            if bytes[dash] != b'-' || dash + 4 >= bytes.len() || bytes[dash + 4] != b'"' {
                continue;
            }
            if !bytes[dash + 1..dash + 4].iter().all(u8::is_ascii_digit) {
                continue;
            }
            let mut start = dash;
            while start > 0 && bytes[start - 1].is_ascii_uppercase() {
                start -= 1;
            }
            if dash - start < 2 || start == 0 || bytes[start - 1] != b'"' {
                continue;
            }
            found.push(&text[start..dash + 4]);
        }
        found
    }
}

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

    #[test]
    fn line_col_is_one_based_and_counts_chars() {
        let text = "ab\ncé\n";
        assert_eq!(
            line_col(text, TextSize::from(0)),
            LineCol { line: 1, column: 1 }
        );
        assert_eq!(
            line_col(text, TextSize::from(2)),
            LineCol { line: 1, column: 3 }
        );
        assert_eq!(
            line_col(text, TextSize::from(3)),
            LineCol { line: 2, column: 1 }
        );
        // `é` is two bytes; the column after it is the third character.
        assert_eq!(
            line_col(text, TextSize::from(6)),
            LineCol { line: 2, column: 3 }
        );
        // An offset past the end clamps to the end of the text.
        assert_eq!(
            line_col(text, TextSize::from(99)),
            LineCol { line: 3, column: 1 }
        );
    }

    #[test]
    fn to_json_projects_spans_and_fixits_onto_lines_and_columns() {
        let mut sources = SourceMap::new();
        let file = sources.file_id("a.typl", "package p\ntype X:\n");
        let span = Span {
            file,
            range: TextRange::new(TextSize::from(10), TextSize::from(17)),
        };
        // A different span from the primary one — a different line and a
        // different column — so a fix-it's span cannot pass this test by
        // being serialized from the primary span instead of its own.
        let fixit_span = Span {
            file,
            range: TextRange::new(TextSize::from(8), TextSize::from(9)),
        };
        let diagnostic = Diagnostic {
            // A real catalogued code, not a fabricated literal: the
            // `codes_written_as_string_literals_are_all_catalogued` workspace
            // scan rejects any `PREFIX-NNN` string literal that is not in a
            // catalogue, including one written in a test fixture.
            code: DiagCode::TYPL_009,
            severity: Severity::Error,
            message: "expected a type".to_string(),
            primary: span,
            labels: Vec::new(),
            fixits: vec![FixIt {
                span: fixit_span,
                replacement: "type X: integer".to_string(),
                label: "give `X` a backing type".to_string(),
            }],
        };

        let json = to_json(&[diagnostic], &sources);

        assert_eq!(json.len(), 1);
        let first = &json[0];
        assert_eq!(first.code, "TYPL-009");
        assert_eq!(first.severity, "error");
        assert_eq!(first.message, "expected a type");
        assert_eq!(first.span.path, "a.typl");
        assert_eq!(first.span.start, LineCol { line: 2, column: 1 });
        assert_eq!(first.span.end, LineCol { line: 2, column: 8 });
        assert_eq!(first.fixes.len(), 1);
        assert_eq!(first.fixes[0].label, "give `X` a backing type");
        assert_eq!(first.fixes[0].replacement, "type X: integer");
        assert_eq!(
            first.fixes[0].span.start,
            LineCol { line: 1, column: 9 },
            "the fix-it's span is its own, not the primary span",
        );
        assert_eq!(
            first.fixes[0].span.end,
            LineCol {
                line: 1,
                column: 10
            }
        );
    }

    /// The struct-field assertions in the test above are checked against
    /// `JsonDiagnostic` itself and stay green through a consistent field
    /// rename or an added `#[serde(rename = ...)]` on the struct. This
    /// snapshot instead pins the serialized JSON key names — the actual wire
    /// contract the MCP `ridl_check` tool and `ridl check --format json` are
    /// both required to emit identically.
    #[test]
    fn to_json_snapshot_pins_the_wire_key_names() {
        let mut sources = SourceMap::new();
        let file = sources.file_id("a.typl", "package p\ntype X:\n");
        let span = Span {
            file,
            range: TextRange::new(TextSize::from(10), TextSize::from(17)),
        };
        // A different span from the primary one, so the snapshot cannot pass
        // by serializing the fix-it's span from the primary span instead of
        // its own.
        let fixit_span = Span {
            file,
            range: TextRange::new(TextSize::from(8), TextSize::from(9)),
        };
        let diagnostic = Diagnostic {
            code: DiagCode::TYPL_009,
            severity: Severity::Error,
            message: "expected a type".to_string(),
            primary: span,
            labels: Vec::new(),
            fixits: vec![FixIt {
                span: fixit_span,
                replacement: "type X: integer".to_string(),
                label: "give `X` a backing type".to_string(),
            }],
        };

        insta::assert_json_snapshot!(to_json(&[diagnostic], &sources));
    }

    /// `lint` names the code's lint and is omitted, not `null`, for an Error
    /// code (docs/book/cli-reference.md). The struct assertions check the
    /// value; the snapshot pins that the key is absent from the serialized
    /// element, which no struct assertion can see.
    #[test]
    fn to_json_names_the_lint_and_omits_it_for_an_error_code() {
        let mut sources = SourceMap::new();
        let file = sources.file_id("a.ridl", "package p\n");
        let span = Span {
            file,
            range: TextRange::new(TextSize::from(0), TextSize::from(7)),
        };
        let diagnostic = |code, severity| Diagnostic {
            code,
            severity,
            message: "m".to_string(),
            primary: span,
            labels: Vec::new(),
            fixits: Vec::new(),
        };
        let json = to_json(
            &[
                diagnostic(DiagCode::RIDL_100, Severity::Warning),
                diagnostic(DiagCode::TYPL_009, Severity::Error),
            ],
            &sources,
        );

        assert_eq!(json[0].code, "RIDL-100");
        assert_eq!(json[0].lint.as_deref(), Some("missing-timing"));
        assert_eq!(json[1].code, "TYPL-009");
        assert_eq!(json[1].lint, None);
        insta::assert_json_snapshot!("to_json_lint_field", json);
    }

    #[test]
    fn to_json_tolerates_a_span_on_an_unknown_file() {
        let sources = SourceMap::new();
        let diagnostic = Diagnostic {
            code: DiagCode::MANI_101,
            severity: Severity::Warning,
            message: "detached".to_string(),
            primary: Span {
                file: FileId::DETACHED,
                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
            },
            labels: Vec::new(),
            fixits: Vec::new(),
        };
        let json = to_json(&[diagnostic], &sources);
        assert_eq!(json[0].severity, "warning");
        assert_eq!(json[0].span.path, "");
        assert_eq!(json[0].span.start, LineCol { line: 1, column: 1 });
    }

    /// A source map holding two files, with a diagnostic whose primary span
    /// and label span both point into the second one. Every other JSON
    /// fixture in this module registers exactly one file, under which
    /// `json_span` resolving every span against a hard-coded `FileId(0)`
    /// would still pass. The two files here also lay out their lines
    /// differently, so a wrong-file lookup reads the wrong line and column,
    /// not only the wrong path.
    #[test]
    fn to_json_resolves_spans_in_the_second_of_two_files() {
        let mut sources = SourceMap::new();
        let _first = sources.file_id("a.typl", "package p\n");
        let second = sources.file_id("b.typl", "package p\nimport a\ntype Y:\n");
        let primary = Span {
            file: second,
            range: TextRange::new(TextSize::from(19), TextSize::from(26)),
        };
        let label_span = Span {
            file: second,
            range: TextRange::new(TextSize::from(10), TextSize::from(18)),
        };
        let diagnostic = Diagnostic {
            code: DiagCode::TYPL_009,
            severity: Severity::Error,
            message: "expected a type".to_string(),
            primary,
            labels: vec![Label {
                span: label_span,
                message: "imported here".to_string(),
            }],
            fixits: Vec::new(),
        };

        let json = to_json(&[diagnostic], &sources);

        let first = &json[0];
        assert_eq!(first.span.path, "b.typl");
        assert_eq!(first.span.start, LineCol { line: 3, column: 1 });
        assert_eq!(first.span.end, LineCol { line: 3, column: 8 });
        assert_eq!(first.labels.len(), 1);
        assert_eq!(first.labels[0].message, "imported here");
        assert_eq!(first.labels[0].span.path, "b.typl");
        assert_eq!(first.labels[0].span.start, LineCol { line: 2, column: 1 });
        assert_eq!(first.labels[0].span.end, LineCol { line: 2, column: 9 });
    }

    /// `Severity::Info` renders as `"info"`. The other two variants
    /// (`"error"`, `"warning"`) are already exercised above.
    #[test]
    fn to_json_reports_info_severity() {
        let sources = SourceMap::new();
        let diagnostic = Diagnostic {
            code: DiagCode::TYPL_115,
            severity: Severity::Info,
            message: "type has no derivable init value".to_string(),
            primary: Span {
                file: FileId::DETACHED,
                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
            },
            labels: Vec::new(),
            fixits: Vec::new(),
        };
        let json = to_json(&[diagnostic], &sources);
        assert_eq!(json[0].severity, "info");
    }

    /// `code` stays present on the wire, as an empty string, for a diagnostic
    /// carrying [`DiagCode::NONE`] — never omitted or turned into `null`. A
    /// snapshot pins the whole serialized object, so a `#[serde(skip_serializing_if
    /// = "String::is_empty")]` mutation on `code` (which a struct-field-only
    /// assertion would not catch) drops the key and fails this comparison.
    #[test]
    fn to_json_keeps_the_code_field_present_when_empty() {
        let sources = SourceMap::new();
        let diagnostic = Diagnostic {
            code: DiagCode::NONE,
            severity: Severity::Error,
            message: "expected a type, but `FROB` names a constant".to_string(),
            primary: Span {
                file: FileId::DETACHED,
                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
            },
            labels: Vec::new(),
            fixits: Vec::new(),
        };
        insta::assert_json_snapshot!(to_json(&[diagnostic], &sources));
    }
}