maskforge-core 0.1.1

Bounded JSON Schema constrained-decoding engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
//! The public arena schema IR: a flat, immutable, hash-consed DAG built once through [`Builder`]
//! and consumed directly by the compiler. All fields are private; the only ways in are
//! [`Builder::finish`] and [`SchemaIR::from_wire`], and the only way out is a read-only accessor.

use std::sync::OnceLock;

use bincode::{Decode, Encode};
use fluent_uri::Uri;
use rustc_hash::FxHashMap;

use crate::diagnostics::{Diagnostic, UnsupportedReason};
use crate::error::{CompileError, ErrorCode, Stage};
use crate::primitives::NodeId;
use crate::wire::SchemaIRWire;

/// The IR schema version. Checked exactly on every wire crossing and folded into the content hash.
pub const IR_VERSION: u16 = 6;

// Arena caps, enforced at BOTH construction paths: incrementally by the builder and on the decoded
// value by the wire layer. Chosen so a within-cap arena always encodes below the envelope byte
// limit, which keeps encoding infallible and keeps decode able to accept anything encode produces.
pub(crate) const MAX_NODES: usize = 1 << 18;
pub(crate) const MAX_STRINGS_BYTES: usize = 8 * 1024 * 1024;
pub(crate) const MAX_LITERALS: usize = 1 << 18;
/// Aggregate byte cap over all `ScalarLit::Str` payloads, which the count cap alone does not bound.
pub(crate) const MAX_LITERAL_STR_BYTES: usize = 8 * 1024 * 1024;
pub(crate) const MAX_PROPS: usize = 1 << 18;
pub(crate) const MAX_DEPENDENT_REQUIRED_PAIRS: usize = 1 << 18;
pub(crate) const MAX_REQUIRED_WORDS: usize = 1 << 18;
pub(crate) const MAX_DIAGNOSTICS: usize = 1 << 16;
pub(crate) const MAX_NODE_REFS: usize = 1 << 18;
pub(crate) const MAX_RESOURCES: usize = 1 << 16;
pub(crate) const MAX_ANCHORS: usize = 1 << 18;

/// Total bytes of owned variable-length literal content (`Str` and composite `Json`) in a slice.
/// Both are unbounded String payloads, so both count toward the aggregate byte cap.
pub(crate) fn literal_str_bytes(lits: &[ScalarLit]) -> usize {
    lits.iter()
        .map(|l| match l {
            ScalarLit::Str(s) | ScalarLit::Json(s) => s.len(),
            _ => 0,
        })
        .sum()
}

/// A contiguous run in a side blob: `off` is the start index, `len` the element/field count.
macro_rules! slice_ref {
    ($(#[$m:meta])* $name:ident) => {
        $(#[$m])*
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Encode, Decode)]
        pub struct $name {
            /// Start index into the owning blob.
            pub off: u32,
            /// Element or field count.
            pub len: u32,
        }
    };
}

slice_ref!(
    /// A run of bytes in the `strings` blob (a UTF-8 substring).
    StrRef
);
slice_ref!(
    /// A run of `ScalarLit` values in the `literals` blob.
    LitSlice
);
slice_ref!(
    /// A run of `(name, child)` pairs in the `props` blob.
    PropSlice
);
slice_ref!(
    /// A run of `(trigger, required)` property-name pairs.
    DependentRequiredSlice
);
slice_ref!(
    /// A run of required-flag words in the `required_bits` blob: `off` is the first word, `len`
    /// the field count.
    BitSlice
);
slice_ref!(
    /// A run of `NodeId` branches in the `node_refs` blob, in declaration order.
    RefSlice
);
slice_ref!(
    /// A run of anchor records in the resource metadata table.
    AnchorSlice
);

/// Dense frozen schema-resource identifier.
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Encode, Decode)]
pub struct ResourceId(pub(crate) u32);

impl ResourceId {
    /// Returns the underlying dense index.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// Dense frozen anchor-record identifier.
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Encode, Decode)]
pub struct AnchorId(pub(crate) u32);

impl AnchorId {
    /// Returns the underlying dense index.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// Frozen metadata for one Draft 2020-12 schema resource.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub struct ResourceRecord {
    /// Canonical absolute URI, absent only for an anonymous resource.
    pub canonical_uri: Option<StrRef>,
    /// Root node of this schema resource.
    pub root: NodeId,
    /// Static `$anchor` records owned by this resource.
    pub static_anchors: AnchorSlice,
    /// `$dynamicAnchor` records owned by this resource.
    pub dynamic_anchors: AnchorSlice,
}

/// Frozen static or dynamic anchor declaration.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub struct AnchorRecord {
    /// Resource declaring this anchor.
    pub resource: ResourceId,
    /// Plain-name anchor value.
    pub name: StrRef,
    /// Schema node identified by the anchor.
    pub target: NodeId,
}

/// Builder input for one already-resolved resource. Anchor lists must be name-sorted.
pub(crate) struct ResourceInput {
    pub(crate) canonical_uri: Option<String>,
    pub(crate) root: NodeId,
    pub(crate) static_anchors: Vec<(String, NodeId)>,
    pub(crate) dynamic_anchors: Vec<(String, NodeId)>,
}

/// A literal usable as a `const` value or an `enum` member.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encode, Decode)]
pub enum ScalarLit {
    /// JSON `null`.
    Null,
    /// JSON `true`/`false`.
    Bool(bool),
    /// A signed 64-bit integer.
    Int(i64),
    /// A UTF-8 string.
    Str(String),
    /// A composite value held as its canonical JSON serialization (minimal whitespace, declared key
    /// order); only that one spelling is accepted (see PROVENANCE.md).
    Json(String),
}

/// The byte alphabet a bounded string is drawn from. The discriminant is the stable wire/hash
/// code; variants are append-only (a reorder is a wire break and bumps the envelope format).
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum Charset {
    /// Any UTF-8 body (no length enforcement in this profile).
    Utf8Any = 0,
    /// Printable ASCII excluding `"` and `\`, where one code point equals one byte.
    AsciiPrintableNoQuoteBackslash = 1,
    /// Full JSON-string alphabet where `regex` denotes one code point, so `{min,max}` counts them.
    Utf8CountedCodepoints = 2,
}

/// How an object treats properties not named in `fields`. Discriminant is the stable code.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum ObjectClosure {
    /// An open object (absent or non-`false` additional properties); rejected at compile.
    RejectOpenObjects = 0,
    /// The caller opted in to generating as a closed object.
    AssumeClosedProfile = 1,
    /// `additionalProperties: false` stated by the schema itself.
    Forbidden = 2,
    /// Default: absent `additionalProperties` compiles as truly open (spec-correct `additionalProperties:true`), not rejected.
    AllowOpenProfile = 3,
}

/// How an open object treats keys past `known`/`patterns`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum AdditionalPolicy {
    /// No further keys are allowed.
    Forbid,
    /// Any further key with any JSON value is allowed.
    AllowAny,
    /// Any further key is allowed if its value matches this schema.
    Schema(NodeId),
    /// Allows an unevaluated key to flow to the unevaluated check.
    /// It validates like `AllowAny` but differs in annotation collection.
    Open,
}

/// Which instance type a `Node::Unevaluated` obligation targets.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum UnevaluatedKind {
    /// `unevaluatedProperties`: obligation applies to object members.
    Properties,
    /// `unevaluatedItems`: obligation applies to array elements.
    Items,
}

/// What an array's elements must satisfy. Unlike `AdditionalPolicy`, there is no `Forbid`: an array
/// always accepts elements, only their type may be unconstrained.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum ItemsPolicy {
    /// Every element must match this schema.
    Schema(NodeId),
    /// Any JSON value, arbitrary depth - not a regular language, so this always routes through
    /// `crate::structured`.
    AllowAny,
}

/// What `contains` requires an element to be, independent of `items`/`prefixItems`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum ContainsPolicy {
    /// `contains: false` - no element can ever satisfy it.
    Never,
    /// `contains: true` - every element satisfies it.
    Always,
    /// An element satisfies it by matching this schema.
    Schema(NodeId),
}

/// A `contains` assertion: `min..=max` elements (independent of `items`/`prefixItems`) must
/// satisfy `policy`. Not a regular-language property, so this always needs `crate::structured`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub struct ContainsConstraint {
    /// What counts as a match.
    pub policy: ContainsPolicy,
    /// Inclusive minimum number of matching elements.
    pub min: u32,
    /// Inclusive maximum number of matching elements, when bounded.
    pub max: Option<u32>,
}

/// What the compiler does when an occurrence is `Unsupported`. Discriminant is the stable code.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum UnsupportedPolicy {
    /// Any `Unsupported` occurrence fails the compile with its diagnostics.
    RejectAtCompile = 0,
}

/// Options that govern lowering. Language-affecting choices (`object_closure`, `format_assertion`)
/// are resolved into node fields at build time; `max_diagnostics` bounds the diagnostics buffer.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub struct CompileOptions {
    /// The default closure applied to an object with absent additional properties.
    pub object_closure: ObjectClosure,
    /// Whether `format` keywords are enforced as lexical DFAs.
    pub format_assertion: bool,
    /// The policy for `Unsupported` occurrences.
    pub unsupported_policy: UnsupportedPolicy,
    /// The diagnostics buffer cap; must be at least one.
    pub max_diagnostics: u32,
}

impl Default for CompileOptions {
    fn default() -> Self {
        Self {
            object_closure: ObjectClosure::AllowOpenProfile,
            format_assertion: false,
            unsupported_policy: UnsupportedPolicy::RejectAtCompile,
            max_diagnostics: 8192,
        }
    }
}

/// Above this many fields, a closed object's shuffle-into-one-regex can take unbounded time to even
/// DISCOVER it exceeds `automaton::elimination`'s byte cap (subset explosion over optional fields),
/// so both `requires_structured_backend` and `structured::MatchCache` treat it as a pre-check, never
/// a "try it and see" attempt.
pub(crate) const MAX_SAFE_SHUFFLE_FIELDS: usize = 4;
/// Above this, a counted-codepoint string routes to `crate::structured`'s O(1)-per-char counter
/// instead of an unrolled DFA whose state count is O(max_len).
pub(crate) const MAX_UNROLLED_CODEPOINT_LEN: u32 = 256;
/// Above this `maxItems`, an array routes to `crate::structured`'s native element counter instead of
/// unrolling the element DFA `max_items` times.
pub(crate) const MAX_UNROLLED_ARRAY_ITEMS: u32 = 64;
/// Above this member count, an all-string enum routes to `crate::structured`'s O(log N) binary
/// search instead of a giant alternation DFA (which state-explodes and crashes past ~10k).
pub(crate) const MAX_UNROLLED_ENUM: usize = 128;
/// One arena node. Children are `NodeId` indices; scalars live in side blobs. `#[non_exhaustive]`.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
pub enum Node {
    /// Matches literal `null`.
    Null,
    /// Matches `true` or `false`.
    Boolean,
    /// Matches no value at all (the bare `false` schema). A regular language like any other leaf:
    /// an impossible byte class, dead from the very first byte, never needs the structured backend.
    Never,
    /// A fixed string literal.
    StringConst {
        /// The literal value (a JSON string body, before JSON quoting).
        value: StrRef,
    },
    /// A regular pattern over a chosen byte alphabet, optionally length-bounded.
    StringPattern {
        /// The byte-level regex body.
        regex: StrRef,
        /// Inclusive minimum length in code points, when bounded.
        min_len: Option<u32>,
        /// Inclusive maximum length in code points, when bounded.
        max_len: Option<u32>,
        /// The alphabet the body is drawn from.
        charset: Charset,
    },
    /// A signed 64-bit integer with optional inclusive bounds and an optional exact divisor.
    Integer {
        /// Inclusive lower bound.
        minimum: Option<i64>,
        /// Inclusive upper bound.
        maximum: Option<i64>,
        /// `multipleOf`: the value must be exactly divisible by this positive integer.
        multiple_of: Option<u64>,
    },
    /// Any JSON number with sign, integer part, and optional fraction.
    /// Bounded forms omit exponents; genuinely fractional bounds remain unsupported.
    Number {
        /// Whether the mathematical value, rather than its spelling, must be integral.
        integer_only: bool,
        /// Lower bound as `(scaled_value, scale, exclusive)`: the value is `scaled_value * 10^-scale`
        /// (`scale = 0` is an integer bound), `exclusive = true` for a strict bound.
        minimum: Option<(i128, u32, bool)>,
        /// Upper bound, same `(scaled_value, scale, exclusive)` encoding.
        maximum: Option<(i128, u32, bool)>,
        /// `multipleOf` as `coef * 10^-exp` (exact decimal), when present.
        multiple_of: Option<(u64, u32)>,
    },
    /// A JSON number constrained by lexical digit counts.
    LexicalNumber {
        /// Anchored byte regex for the complete number token.
        regex: StrRef,
    },
    /// A closed set of scalar literals (non-empty, canonically sorted, duplicate-free).
    Enum {
        /// The member values.
        values: LitSlice,
    },
    /// A homogeneous array with a cardinality bound.
    Array {
        /// What every element must satisfy.
        items: ItemsPolicy,
        /// Inclusive minimum item count.
        min_items: u32,
        /// Inclusive maximum item count, when bounded.
        max_items: Option<u32>,
        /// `uniqueItems`: no two items may be the same JSON value. Not a regular-language property
        /// (needs unbounded memory of prior items), so this always routes through `crate::structured`.
        unique_items: bool,
        /// `contains`/`minContains`/`maxContains`, when present.
        contains: Option<ContainsConstraint>,
        /// Whether `items` was textually present (`true` or a schema), for `unevaluatedItems`: an
        /// absent `items` validates identically but annotates no index (proven by the official suite).
        items_annotates: bool,
    },
    /// A positional (tuple) array: `prefix` positions validate in order, `tail` validates the rest
    /// (absent = closed); length runs from `min_items` to `max_items` (and the prefix, if closed).
    Tuple {
        /// The positional element schemas, in array order.
        prefix: RefSlice,
        /// The schema for items past the prefix, or `None` for a closed tuple.
        tail: Option<NodeId>,
        /// Inclusive minimum item count.
        min_items: u32,
        /// Inclusive maximum item count, when bounded.
        max_items: Option<u32>,
        /// `uniqueItems`, same semantics and structured-backend requirement as `Node::Array`'s.
        unique_items: bool,
        /// Whether `items` was textually present past `prefixItems`, mirroring `items_annotates`.
        tail_annotates: bool,
        /// `contains`/`minContains`/`maxContains`, when present.
        contains: Option<ContainsConstraint>,
    },
    /// An object with source-ordered fields, a positional required bitset, and a closure policy.
    Object {
        /// The `(name, child)` fields, in source order.
        fields: PropSlice,
        /// The required-field bitset (indexed by field position).
        required: BitSlice,
        /// How additional properties are treated.
        closure: ObjectClosure,
        /// `dependentSchemas`: when `key` is present, the whole instance must also satisfy
        /// `schema`. Instance-dependent, so a non-empty run always needs `crate::structured`.
        dependent: PropSlice,
        /// `dependentRequired` flattened as decoded trigger/required name pairs.
        dependent_required: DependentRequiredSlice,
    },
    /// An order-independent object: known properties, `patternProperties`, and an additional-key
    /// policy, none of which can be represented as one finite byte-level regex.
    OpenObject {
        /// The exact `(name, child)` properties, matched independent of textual order.
        known: PropSlice,
        /// The required-field bitset, aligned to `known` by position.
        known_required: BitSlice,
        /// The `(pattern, child)` `patternProperties` entries; a key may match more than one.
        patterns: PropSlice,
        /// How a key matching neither `known` nor `patterns` is treated.
        additional: AdditionalPolicy,
        /// An optional schema every key (known, pattern-matched, or additional) must satisfy.
        property_names: Option<NodeId>,
        /// Inclusive minimum property count.
        min_properties: Option<u32>,
        /// Inclusive maximum property count, when bounded.
        max_properties: Option<u32>,
        /// `dependentSchemas`, same semantics as `Node::Object`'s.
        dependent: PropSlice,
        /// `dependentRequired` flattened as decoded trigger/required name pairs.
        dependent_required: DependentRequiredSlice,
    },
    /// A `type` union: matches any of its branches, in declaration order (deduplicated by type).
    Union {
        /// The branch nodes.
        branches: RefSlice,
    },
    /// An `allOf`: matches iff every branch matches (language intersection).
    Intersection {
        /// The branch nodes.
        branches: RefSlice,
    },
    /// A `oneOf`: matches iff exactly one branch matches.
    ExactlyOne {
        /// The branch nodes.
        branches: RefSlice,
    },
    /// Matches complete JSON values that `inner` does not match.
    /// Full JSON-value complement requires `crate::structured`.
    Not {
        /// The negated schema.
        inner: NodeId,
    },
    /// A recursion cut point: a leaf whose body is `def_targets[def]`, an edge free of the back-edge
    /// rule so a `$ref` cycle needs no cyclic child graph. Followed only by `crate::structured`.
    Ref {
        /// Index into the `SchemaIR::def_targets` table naming the definition body.
        def: u32,
    },
    /// A `$dynamicRef` whose initially resolved fragment names a `$dynamicAnchor`.
    DynamicRef {
        /// Statically resolved target used when dynamic scope does not rebind the name.
        initial_target: NodeId,
        /// Initial dynamic-anchor declaration, which supplies the plain-name identity.
        anchor: AnchorId,
    },
    /// Requires unannotated properties or items in `scope` to match `unevaluated`.
    /// Annotation tracking requires `crate::structured`.
    Unevaluated {
        /// Which instance type this obligation targets.
        kind: UnevaluatedKind,
        /// The schema minus the unevaluated keyword (local assertions and in-place applicators).
        scope: NodeId,
        /// The schema each unevaluated member must satisfy (`Never` for `false`).
        unevaluated: NodeId,
    },
    /// An occurrence the dialect does not support. Carries no pointer; provenance is the sidecar.
    Unsupported {
        /// The offending keyword.
        keyword: StrRef,
        /// The machine-stable reason.
        reason: UnsupportedReason,
    },
}

/// The arena IR. Built once and frozen; all fields private.
#[derive(Clone)]
pub struct SchemaIR {
    ir_version: u16,
    root: NodeId,
    nodes: Vec<Node>,
    strings: Vec<u8>,
    literals: Vec<ScalarLit>,
    props: Vec<(StrRef, NodeId)>,
    dependent_required_pairs: Vec<DependentRequiredPair>,
    required_bits: Vec<u64>,
    node_refs: Vec<NodeId>,
    def_targets: Vec<NodeId>,
    retrieval_uri: Option<StrRef>,
    resources: Vec<ResourceRecord>,
    anchors: Vec<AnchorRecord>,
    node_resources: Vec<ResourceId>,
    options: CompileOptions,
    diagnostics: Vec<Diagnostic>,
    cached_hash: OnceLock<[u8; 32]>,
    route_table: OnceLock<crate::routing::RouteTable>,
}

/// One decoded-name presence implication used by `dependentRequired`.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encode, Decode)]
pub struct DependentRequiredPair {
    /// The decoded property name whose presence activates the rule.
    pub trigger: StrRef,
    /// A decoded property name that must be present when the trigger is present.
    pub required: StrRef,
}

impl PartialEq for SchemaIR {
    /// Exact frozen representation equality: every field (arena order, blob offsets, options, and
    /// diagnostics) except the memoized hash. Two IRs with the same schema but a different arena
    /// layout or different rejected sites compare unequal; for language identity use
    /// [`SchemaIR::same_content_address`] or compare [`SchemaIR::canonical_hash`].
    fn eq(&self, other: &Self) -> bool {
        self.ir_version == other.ir_version
            && self.root == other.root
            && self.nodes == other.nodes
            && self.strings == other.strings
            && self.literals == other.literals
            && self.props == other.props
            && self.dependent_required_pairs == other.dependent_required_pairs
            && self.required_bits == other.required_bits
            && self.node_refs == other.node_refs
            && self.def_targets == other.def_targets
            && self.retrieval_uri == other.retrieval_uri
            && self.resources == other.resources
            && self.anchors == other.anchors
            && self.node_resources == other.node_resources
            && self.options == other.options
            && self.diagnostics == other.diagnostics
    }
}

impl Eq for SchemaIR {}

impl std::fmt::Debug for SchemaIR {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SchemaIR")
            .field("ir_version", &self.ir_version)
            .field("root", &self.root)
            .field("nodes", &self.nodes)
            .field("resources", &self.resources)
            .field("diagnostics", &self.diagnostics.len())
            .finish_non_exhaustive()
    }
}

impl SchemaIR {
    /// The IR schema version.
    #[must_use]
    pub fn ir_version(&self) -> u16 {
        self.ir_version
    }

    /// The root node id.
    #[must_use]
    pub fn root(&self) -> NodeId {
        self.root
    }

    /// The node at `id`, or `None` if the id is out of range.
    #[must_use]
    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id.get() as usize)
    }

    /// All nodes in arena order.
    pub fn nodes(&self) -> impl ExactSizeIterator<Item = &Node> {
        self.nodes.iter()
    }

    /// The number of nodes in the arena.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Optional root retrieval URI retained in the compact string blob.
    #[must_use]
    pub fn retrieval_uri(&self) -> Option<&str> {
        self.retrieval_uri.and_then(|uri| self.str_at(uri))
    }

    /// Frozen schema resources in canonical order.
    #[must_use]
    pub fn resources(&self) -> &[ResourceRecord] {
        &self.resources
    }

    /// Frozen static and dynamic anchor records.
    #[must_use]
    pub fn anchors(&self) -> &[AnchorRecord] {
        &self.anchors
    }

    /// Resource that owns `node`, or `None` for an invalid node ID.
    #[must_use]
    pub fn node_resource(&self, node: NodeId) -> Option<ResourceId> {
        self.node_resources.get(node.get() as usize).copied()
    }

    /// Every diagnostic, one per rejected occurrence.
    pub fn diagnostics(&self) -> impl ExactSizeIterator<Item = &Diagnostic> {
        self.diagnostics.iter()
    }

    /// A counted-codepoint string whose bound is past `MAX_UNROLLED_CODEPOINT_LEN`, and whose regex
    /// is exactly `JSON_STRING_CODEPOINT` (the only text the frontend ever pairs with this charset).
    pub(crate) fn is_unrolled_codepoint_string(&self, node: &Node) -> bool {
        let Node::StringPattern {
            regex,
            min_len,
            max_len,
            charset: Charset::Utf8CountedCodepoints,
        } = node
        else {
            return false;
        };
        let long = max_len.is_some_and(|n| n > MAX_UNROLLED_CODEPOINT_LEN)
            || min_len.is_some_and(|n| n > MAX_UNROLLED_CODEPOINT_LEN);
        long && self.str_at(*regex) == Some(crate::frontend::JSON_STRING_CODEPOINT)
    }

    /// A `pattern`/`format` string, as opposed to the unconstrained-body sentinel: its regex must
    /// run over decoded Unicode scalar bytes (`crate::structured`), never raw JSON escape spelling.
    pub(crate) fn is_user_pattern(&self, node: &Node) -> bool {
        let Node::StringPattern {
            regex,
            charset: Charset::Utf8Any,
            ..
        } = node
        else {
            return false;
        };
        self.str_at(*regex) != Some(crate::frontend::JSON_STRING_BODY)
    }

    /// An enum past `MAX_UNROLLED_ENUM` whose members are all strings: compiled as a decoded-value
    /// trie when regular, or matched by the structured backend inside non-regular composition.
    pub(crate) fn is_large_string_enum(&self, node: &Node) -> bool {
        let Node::Enum { values } = node else {
            return false;
        };
        let Some(lits) = self.lits_at(*values) else {
            return false;
        };
        lits.len() > MAX_UNROLLED_ENUM && lits.iter().all(|l| matches!(l, ScalarLit::Str(_)))
    }

    /// Whether any arena node needs `crate::structured` instead of `compile::compile_ir`: an
    /// `OpenObject`, an oversized object shuffle, `uniqueItems`/`contains`, `dependentSchemas`, or an
    /// unrolled-codepoint-count string too long to build as one DFA cheaply.
    #[must_use]
    pub fn requires_structured_backend(&self) -> bool {
        self.route_table()
            .get(self.root)
            .is_none_or(|route| route.kind != crate::routing::ExecutionKind::Regular)
    }

    /// The shared immutable per-node route table, computed once for this frozen IR.
    #[must_use]
    pub fn route_table(&self) -> &crate::routing::RouteTable {
        self.route_table
            .get_or_init(|| crate::routing::analyze(self))
    }

    /// The compile options this IR was built with.
    #[must_use]
    pub fn options(&self) -> &CompileOptions {
        &self.options
    }

    /// Resolves a string reference to its UTF-8 slice, or `None` if the run is out of range.
    #[must_use]
    pub fn str_at(&self, r: StrRef) -> Option<&str> {
        let end = (r.off as usize).checked_add(r.len as usize)?;
        let bytes = self.strings.get(r.off as usize..end)?;
        std::str::from_utf8(bytes).ok()
    }

    /// Resolves a literal run, or `None` if out of range.
    #[must_use]
    pub fn lits_at(&self, r: LitSlice) -> Option<&[ScalarLit]> {
        let end = (r.off as usize).checked_add(r.len as usize)?;
        self.literals.get(r.off as usize..end)
    }

    /// Resolves a property run, or `None` if out of range.
    #[must_use]
    pub fn props_at(&self, r: PropSlice) -> Option<&[(StrRef, NodeId)]> {
        let end = (r.off as usize).checked_add(r.len as usize)?;
        self.props.get(r.off as usize..end)
    }

    /// Resolves a `dependentRequired` pair run, or `None` if out of range.
    #[must_use]
    pub fn dependent_required_at(
        &self,
        r: DependentRequiredSlice,
    ) -> Option<&[DependentRequiredPair]> {
        let end = (r.off as usize).checked_add(r.len as usize)?;
        self.dependent_required_pairs.get(r.off as usize..end)
    }

    /// The definition body a `Node::Ref { def }` names, or `None` if the slot is out of range.
    #[must_use]
    pub fn def_target(&self, def: u32) -> Option<NodeId> {
        self.def_targets.get(def as usize).copied()
    }

    /// Resolves a branch run, or `None` if out of range.
    #[must_use]
    pub fn refs_at(&self, r: RefSlice) -> Option<&[NodeId]> {
        let end = (r.off as usize).checked_add(r.len as usize)?;
        self.node_refs.get(r.off as usize..end)
    }

    /// Whether field `idx` of an object with required set `r` is required.
    #[must_use]
    pub fn is_required(&self, r: BitSlice, idx: u32) -> bool {
        if idx >= r.len {
            return false;
        }
        let word = r.off as usize + (idx / 64) as usize;
        self.required_bits
            .get(word)
            .is_some_and(|w| (w >> (idx % 64)) & 1 == 1)
    }

    /// The memoized blake3 Merkle content address over node semantics (tags, scalars, child digests,
    /// closure, required bits) only; pointers, layout, diagnostics, and `CompileOptions` are excluded.
    #[must_use]
    pub fn canonical_hash(&self) -> [u8; 32] {
        *self.cached_hash.get_or_init(|| self.compute_hash())
    }

    /// Whether two IRs share the same content address. This is cryptographic identity, not a
    /// structural proof: equal addresses mean the schemas are the same up to a BLAKE3 collision,
    /// which is the same guarantee any content-addressed store relies on.
    #[must_use]
    pub fn same_content_address(&self, other: &Self) -> bool {
        self.canonical_hash() == other.canonical_hash()
    }

    /// Serializes the IR into the versioned MFIR envelope.
    #[must_use]
    pub fn to_wire(&self) -> Vec<u8> {
        crate::wire::encode(self)
    }

    /// Deserializes and validates an MFIR envelope into a frozen IR.
    pub fn from_wire(bytes: &[u8]) -> Result<Self, CompileError> {
        crate::wire::decode(bytes)
    }

    /// Builds the wire payload struct (a clone of the semantic fields, without the memo).
    pub(crate) fn to_wire_struct(&self) -> SchemaIRWire {
        SchemaIRWire {
            ir_version: self.ir_version,
            root: self.root,
            nodes: self.nodes.clone(),
            strings: self.strings.clone(),
            literals: self.literals.clone(),
            props: self.props.clone(),
            dependent_required_pairs: self.dependent_required_pairs.clone(),
            required_bits: self.required_bits.clone(),
            node_refs: self.node_refs.clone(),
            def_targets: self.def_targets.clone(),
            retrieval_uri: self.retrieval_uri,
            resources: self.resources.clone(),
            anchors: self.anchors.clone(),
            node_resources: self.node_resources.clone(),
            options: self.options.clone(),
            diagnostics: self.diagnostics.clone(),
        }
    }

    /// The single construction choke point: validate the parts, then freeze with an empty memo.
    /// Panic-free on adversarial input (used by both the builder and the wire decoder).
    pub(crate) fn assemble(wire: SchemaIRWire) -> Result<Self, CompileError> {
        let ir = Self {
            ir_version: wire.ir_version,
            root: wire.root,
            nodes: wire.nodes,
            strings: wire.strings,
            literals: wire.literals,
            props: wire.props,
            dependent_required_pairs: wire.dependent_required_pairs,
            required_bits: wire.required_bits,
            node_refs: wire.node_refs,
            def_targets: wire.def_targets,
            retrieval_uri: wire.retrieval_uri,
            resources: wire.resources,
            anchors: wire.anchors,
            node_resources: wire.node_resources,
            options: wire.options,
            diagnostics: wire.diagnostics,
            cached_hash: OnceLock::new(),
            route_table: OnceLock::new(),
        };
        ir.validate()?;
        Ok(ir)
    }

    /// Structural validation. Total and panic-free: every index is checked, every child is a
    /// strict back-edge, every set is canonical. Rejects a forged arena with a structured error.
    fn validate(&self) -> Result<(), CompileError> {
        if self.ir_version != IR_VERSION {
            return Err(err(
                ErrorCode::ArtifactMismatch,
                "ir_version does not match",
            ));
        }
        if self.options.max_diagnostics == 0 {
            return Err(malformed("max_diagnostics must be at least one"));
        }
        if self.root.get() as usize >= self.nodes.len() {
            return Err(malformed("root node id out of range"));
        }
        if literal_str_bytes(&self.literals) > MAX_LITERAL_STR_BYTES {
            return Err(limit("literal string bytes"));
        }
        if self.dependent_required_pairs.len() > MAX_DEPENDENT_REQUIRED_PAIRS {
            return Err(malformed("dependentRequired pair count exceeds cap"));
        }
        self.validate_resources()?;
        for (i, node) in self.nodes.iter().enumerate() {
            let parent = u32::try_from(i).map_err(|_| limit("node index"))?;
            self.validate_node(node, parent)?;
        }
        for target in &self.def_targets {
            if target.get() as usize >= self.nodes.len() {
                return Err(malformed("def target node id out of range"));
            }
        }
        self.validate_diagnostics()?;
        Ok(())
    }

    /// Re-runs structural validation for benchmark phase attribution.
    #[doc(hidden)]
    #[cfg(feature = "bench-internals")]
    pub fn validate_for_bench(&self) -> Result<(), CompileError> {
        self.validate()
    }

    fn validate_diagnostics(&self) -> Result<(), CompileError> {
        if self.diagnostics.len() as u64 > u64::from(self.options.max_diagnostics) {
            return Err(CompileError::new(
                ErrorCode::TooManyDiagnostics,
                Stage::L2,
                "more diagnostics than the configured cap",
            ));
        }
        for d in &self.diagnostics {
            let node = self
                .nodes
                .get(d.node.get() as usize)
                .ok_or_else(|| malformed("diagnostic references a node out of range"))?;
            let Node::Unsupported { keyword, reason } = node else {
                return Err(malformed("a diagnostic must point at an Unsupported node"));
            };
            if *keyword != d.keyword {
                return Err(malformed("diagnostic keyword disagrees with its node"));
            }
            if *reason != d.reason {
                return Err(malformed("diagnostic reason disagrees with its node"));
            }
            if self.str_at(d.keyword).is_none() || self.str_at(d.json_pointer).is_none() {
                return Err(malformed("diagnostic string reference out of range"));
            }
            if let Some(span) = d.source_span {
                if span.start > span.end {
                    return Err(malformed("diagnostic span start is past its end"));
                }
            }
        }
        Ok(())
    }

    fn validate_node(&self, node: &Node, parent: u32) -> Result<(), CompileError> {
        let child_ok = |c: NodeId| c.get() < parent;
        match node {
            Node::Null | Node::Boolean | Node::Never => Ok(()),
            Node::StringConst { value } => {
                self.str_at(*value)
                    .ok_or_else(|| malformed("string const reference out of range"))?;
                Ok(())
            }
            Node::StringPattern {
                regex,
                min_len,
                max_len,
                charset,
            } => {
                let re = self
                    .str_at(*regex)
                    .ok_or_else(|| malformed("pattern reference out of range"))?;
                if *charset == Charset::Utf8Any && re != crate::frontend::JSON_STRING_BODY {
                    validate_search_pattern(re)?;
                } else {
                    validate_pattern(re)?;
                }
                if let (Some(lo), Some(hi)) = (min_len, max_len) {
                    if hi < lo {
                        return Err(malformed("string maxLength is less than minLength"));
                    }
                }
                Ok(())
            }
            Node::Integer {
                minimum,
                maximum,
                multiple_of,
            } => {
                if let (Some(lo), Some(hi)) = (minimum, maximum) {
                    if hi < lo {
                        return Err(malformed("integer maximum is less than minimum"));
                    }
                }
                if *multiple_of == Some(0) {
                    return Err(malformed("multipleOf must be a positive integer"));
                }
                Ok(())
            }
            Node::Number {
                integer_only: _,
                minimum,
                maximum,
                multiple_of,
            } => {
                if let (Some((lo, ls, lo_excl)), Some((hi, hs, hi_excl))) = (minimum, maximum) {
                    let ord = decimal_cmp((*lo, *ls), (*hi, *hs));
                    if ord == std::cmp::Ordering::Greater
                        || (ord == std::cmp::Ordering::Equal && (*lo_excl || *hi_excl))
                    {
                        return Err(malformed("number maximum is not above minimum"));
                    }
                }
                if let Some((coef, _)) = multiple_of {
                    if *coef == 0 {
                        return Err(malformed("multipleOf must be positive"));
                    }
                }
                Ok(())
            }
            Node::LexicalNumber { regex } => {
                let regex = self
                    .str_at(*regex)
                    .ok_or_else(|| malformed("lexical number pattern out of range"))?;
                validate_pattern(regex)
            }
            Node::Enum { values } => {
                let lits = self
                    .lits_at(*values)
                    .ok_or_else(|| malformed("enum literal run out of range"))?;
                if lits.is_empty() {
                    return Err(malformed("an enum must have at least one value"));
                }
                for pair in lits.windows(2) {
                    if pair[0] >= pair[1] {
                        return Err(malformed(
                            "enum values must be canonically sorted and unique",
                        ));
                    }
                }
                Ok(())
            }
            Node::Array {
                items,
                min_items,
                max_items,
                ..
            } => {
                if let ItemsPolicy::Schema(id) = items {
                    if !child_ok(*id) {
                        return Err(malformed("array item is not a back-edge"));
                    }
                }
                if let Some(max) = max_items {
                    if max < min_items {
                        return Err(malformed("array maxItems is less than minItems"));
                    }
                }
                Ok(())
            }
            Node::Tuple {
                prefix,
                tail,
                min_items,
                max_items,
                ..
            } => {
                let ids = self
                    .refs_at(*prefix)
                    .ok_or_else(|| malformed("tuple prefix run out of range"))?;
                if ids.is_empty() {
                    return Err(malformed("a tuple must have at least one prefix position"));
                }
                for id in ids {
                    if !child_ok(*id) {
                        return Err(malformed("tuple prefix element is not a back-edge"));
                    }
                }
                if let Some(t) = tail {
                    if !child_ok(*t) {
                        return Err(malformed("tuple tail is not a back-edge"));
                    }
                }
                if let Some(max) = max_items {
                    if max < min_items {
                        return Err(malformed("tuple maxItems is less than minItems"));
                    }
                }
                // A closed tuple (no tail) cannot hold more items than the prefix supplies, so a
                // minItems past the prefix length is an empty language, rejected at build.
                if tail.is_none() && *min_items > prefix.len {
                    return Err(malformed("closed tuple minItems exceeds the prefix length"));
                }
                Ok(())
            }
            Node::Object {
                fields,
                required,
                dependent,
                dependent_required,
                ..
            } => {
                let props = self
                    .props_at(*fields)
                    .ok_or_else(|| malformed("object field run out of range"))?;
                let mut seen: FxHashMap<&str, ()> = FxHashMap::default();
                seen.reserve(props.len());
                for (name, child) in props {
                    let key = self
                        .str_at(*name)
                        .ok_or_else(|| malformed("object field name out of range"))?;
                    if seen.insert(key, ()).is_some() {
                        return Err(malformed("duplicate object key"));
                    }
                    if !child_ok(*child) {
                        return Err(malformed("object field value is not a back-edge"));
                    }
                }
                self.validate_required(*required, props.len())?;
                self.validate_dependent_props(*dependent, child_ok)?;
                self.validate_dependent_required(*dependent_required)
            }
            Node::OpenObject {
                known,
                known_required,
                patterns,
                additional,
                property_names,
                min_properties,
                max_properties,
                dependent,
                dependent_required,
            } => {
                let known_props = self
                    .props_at(*known)
                    .ok_or_else(|| malformed("open object known props out of range"))?;
                let mut seen: FxHashMap<&str, ()> = FxHashMap::default();
                seen.reserve(known_props.len());
                for (name, child) in known_props {
                    let key = self
                        .str_at(*name)
                        .ok_or_else(|| malformed("open object field name out of range"))?;
                    if seen.insert(key, ()).is_some() {
                        return Err(malformed("duplicate object key"));
                    }
                    if !child_ok(*child) {
                        return Err(malformed("open object field value is not a back-edge"));
                    }
                }
                self.validate_required(*known_required, known_props.len())?;
                let pattern_props = self
                    .props_at(*patterns)
                    .ok_or_else(|| malformed("open object pattern props out of range"))?;
                for (regex, child) in pattern_props {
                    let re = self
                        .str_at(*regex)
                        .ok_or_else(|| malformed("open object pattern regex out of range"))?;
                    validate_search_pattern(re)?;
                    if !child_ok(*child) {
                        return Err(malformed("open object pattern value is not a back-edge"));
                    }
                }
                if let AdditionalPolicy::Schema(id) = additional {
                    if !child_ok(*id) {
                        return Err(malformed(
                            "open object additional schema is not a back-edge",
                        ));
                    }
                }
                if let Some(pn) = property_names {
                    if !child_ok(*pn) {
                        return Err(malformed(
                            "open object propertyNames schema is not a back-edge",
                        ));
                    }
                }
                if let (Some(lo), Some(hi)) = (min_properties, max_properties) {
                    if hi < lo {
                        return Err(malformed(
                            "open object maxProperties is less than minProperties",
                        ));
                    }
                }
                self.validate_dependent_props(*dependent, child_ok)?;
                self.validate_dependent_required(*dependent_required)
            }
            Node::Union { branches } => {
                let ids = self
                    .refs_at(*branches)
                    .ok_or_else(|| malformed("union branch run out of range"))?;
                if ids.is_empty() {
                    return Err(malformed("a type union must have at least one branch"));
                }
                for id in ids {
                    if !child_ok(*id) {
                        return Err(malformed("union branch is not a back-edge"));
                    }
                }
                Ok(())
            }
            Node::Intersection { branches } => {
                let ids = self
                    .refs_at(*branches)
                    .ok_or_else(|| malformed("intersection branch run out of range"))?;
                if ids.is_empty() {
                    return Err(malformed("an intersection must have at least one branch"));
                }
                for id in ids {
                    if !child_ok(*id) {
                        return Err(malformed("intersection branch is not a back-edge"));
                    }
                }
                Ok(())
            }
            Node::ExactlyOne { branches } => {
                let ids = self
                    .refs_at(*branches)
                    .ok_or_else(|| malformed("exactly-one branch run out of range"))?;
                if ids.is_empty() {
                    return Err(malformed("an exactly-one must have at least one branch"));
                }
                for id in ids {
                    if !child_ok(*id) {
                        return Err(malformed("exactly-one branch is not a back-edge"));
                    }
                }
                Ok(())
            }
            Node::Not { inner } => {
                if !child_ok(*inner) {
                    return Err(malformed("not target is not a back-edge"));
                }
                Ok(())
            }
            Node::Ref { def } => {
                if (*def as usize) >= self.def_targets.len() {
                    return Err(malformed("ref names a def slot out of range"));
                }
                Ok(())
            }
            Node::DynamicRef {
                initial_target,
                anchor,
            } => {
                if initial_target.get() as usize >= self.nodes.len() {
                    return Err(malformed("dynamic reference target is out of range"));
                }
                let record = self
                    .anchors
                    .get(anchor.get() as usize)
                    .ok_or_else(|| malformed("dynamic reference anchor is out of range"))?;
                let resource = self
                    .resources
                    .get(record.resource.get() as usize)
                    .ok_or_else(|| {
                        malformed("dynamic reference anchor resource is out of range")
                    })?;
                let dynamic_start = resource.dynamic_anchors.off as usize;
                let dynamic_end = dynamic_start
                    .checked_add(resource.dynamic_anchors.len as usize)
                    .ok_or_else(|| malformed("dynamic anchor run overflows"))?;
                let anchor_index = anchor.get() as usize;
                if !(dynamic_start..dynamic_end).contains(&anchor_index) {
                    return Err(malformed(
                        "dynamic reference names an anchor that is not dynamic",
                    ));
                }
                let consistent = record.target == *initial_target
                    || matches!(
                        self.node(*initial_target),
                        Some(Node::Ref { def }) if self.def_target(*def) == Some(record.target)
                    );
                if !consistent {
                    return Err(malformed(
                        "dynamic reference target disagrees with its initial anchor",
                    ));
                }
                Ok(())
            }
            Node::Unevaluated {
                scope, unevaluated, ..
            } => {
                if !child_ok(*scope) || !child_ok(*unevaluated) {
                    return Err(malformed("unevaluated child is not a back-edge"));
                }
                Ok(())
            }
            Node::Unsupported { keyword, .. } => {
                self.str_at(*keyword)
                    .ok_or_else(|| malformed("unsupported keyword reference out of range"))?;
                Ok(())
            }
        }
    }

    fn validate_resources(&self) -> Result<(), CompileError> {
        if self.resources.is_empty() || self.resources.len() > MAX_RESOURCES {
            return Err(malformed("resource table is empty or exceeds its cap"));
        }
        if self.anchors.len() > MAX_ANCHORS {
            return Err(malformed("anchor table exceeds its cap"));
        }
        if self.node_resources.len() != self.nodes.len() {
            return Err(malformed("node-to-resource table length mismatch"));
        }
        if let Some(uri) = self.retrieval_uri {
            let uri = self
                .str_at(uri)
                .ok_or_else(|| malformed("retrieval URI string run is invalid"))?;
            validate_canonical_uri(uri)?;
        }
        for resource in &self.node_resources {
            if resource.get() as usize >= self.resources.len() {
                return Err(malformed("node is assigned to an invalid resource"));
            }
        }
        let mut previous_uri: Option<&str> = None;
        let mut anonymous_seen = false;
        let mut anchor_cursor = 0usize;
        for (index, resource) in self.resources.iter().enumerate() {
            if resource.root.get() as usize >= self.nodes.len() {
                return Err(malformed("resource root is out of range"));
            }
            let resource_id =
                ResourceId(u32::try_from(index).map_err(|_| limit("resource index"))?);
            if self.node_resource(resource.root) != Some(resource_id) {
                return Err(malformed("resource root has an inconsistent owner"));
            }
            match resource.canonical_uri {
                None => {
                    if anonymous_seen || previous_uri.is_some() {
                        return Err(malformed("anonymous resource ordering is not canonical"));
                    }
                    anonymous_seen = true;
                }
                Some(uri) => {
                    let uri = self
                        .str_at(uri)
                        .ok_or_else(|| malformed("resource URI string run is invalid"))?;
                    validate_canonical_uri(uri)?;
                    if previous_uri.is_some_and(|previous| previous >= uri) {
                        return Err(malformed("resource URIs are duplicate or not canonical"));
                    }
                    previous_uri = Some(uri);
                }
            }
            let mut names = rustc_hash::FxHashSet::default();
            for run in [resource.static_anchors, resource.dynamic_anchors] {
                if usize::try_from(run.off).map_err(|_| malformed("anchor run offset"))?
                    != anchor_cursor
                {
                    return Err(malformed("anchor runs are not in canonical order"));
                }
                let anchors = self.validate_anchor_run(run, resource_id)?;
                anchor_cursor = anchor_cursor
                    .checked_add(anchors.len())
                    .ok_or_else(|| malformed("anchor run overflows"))?;
                names
                    .try_reserve(anchors.len())
                    .map_err(|_| limit("anchor validation set"))?;
                for anchor in anchors {
                    let name = self
                        .str_at(anchor.name)
                        .ok_or_else(|| malformed("anchor name string run is invalid"))?;
                    if !names.insert(name) {
                        return Err(malformed(
                            "static and dynamic anchors collide inside one resource",
                        ));
                    }
                }
            }
        }
        if anchor_cursor != self.anchors.len() {
            return Err(malformed("anchor table has unclaimed records"));
        }
        Ok(())
    }

    fn validate_anchor_run(
        &self,
        run: AnchorSlice,
        resource: ResourceId,
    ) -> Result<&[AnchorRecord], CompileError> {
        let start = usize::try_from(run.off).map_err(|_| malformed("anchor run offset"))?;
        let end = start
            .checked_add(usize::try_from(run.len).map_err(|_| malformed("anchor run length"))?)
            .ok_or_else(|| malformed("anchor run overflows"))?;
        let anchors = self
            .anchors
            .get(start..end)
            .ok_or_else(|| malformed("anchor run is out of range"))?;
        let mut previous_name: Option<&str> = None;
        for anchor in anchors {
            if anchor.resource != resource {
                return Err(malformed("anchor run contains another resource"));
            }
            if anchor.target.get() as usize >= self.nodes.len()
                || self.node_resource(anchor.target) != Some(resource)
            {
                return Err(malformed("anchor target or resource is invalid"));
            }
            let name = self
                .str_at(anchor.name)
                .ok_or_else(|| malformed("anchor name string run is invalid"))?;
            if previous_name.is_some_and(|previous| previous >= name) {
                return Err(malformed("anchor names are duplicate or not canonical"));
            }
            previous_name = Some(name);
        }
        Ok(anchors)
    }

    fn validate_required(
        &self,
        required: BitSlice,
        field_count: usize,
    ) -> Result<(), CompileError> {
        if required.len as usize != field_count {
            return Err(malformed(
                "required bitset width does not match field count",
            ));
        }
        let words = field_count.div_ceil(64);
        let end = (required.off as usize)
            .checked_add(words)
            .ok_or_else(|| malformed("required bitset overflows"))?;
        let slice = self
            .required_bits
            .get(required.off as usize..end)
            .ok_or_else(|| malformed("required bitset out of range"))?;
        // The tail bits past the field count must be zero so the words hash canonically.
        if field_count % 64 != 0 {
            if let Some(last) = slice.last() {
                let used = field_count % 64;
                if last >> used != 0 {
                    return Err(malformed("required bitset has non-zero padding bits"));
                }
            }
        }
        Ok(())
    }

    /// Validates a `dependentSchemas` run: distinct keys, every value a strict back-edge.
    fn validate_dependent_props(
        &self,
        dependent: PropSlice,
        child_ok: impl Fn(NodeId) -> bool,
    ) -> Result<(), CompileError> {
        let props = self
            .props_at(dependent)
            .ok_or_else(|| malformed("dependentSchemas prop run out of range"))?;
        let mut seen: FxHashMap<&str, ()> = FxHashMap::default();
        seen.reserve(props.len());
        for (name, child) in props {
            let key = self
                .str_at(*name)
                .ok_or_else(|| malformed("dependentSchemas key out of range"))?;
            if seen.insert(key, ()).is_some() {
                return Err(malformed("duplicate dependentSchemas key"));
            }
            if !child_ok(*child) {
                return Err(malformed("dependentSchemas value is not a back-edge"));
            }
        }
        Ok(())
    }

    fn validate_dependent_required(
        &self,
        dependent: DependentRequiredSlice,
    ) -> Result<(), CompileError> {
        let pairs = self
            .dependent_required_at(dependent)
            .ok_or_else(|| malformed("dependentRequired pair run out of range"))?;
        if pairs.len() > MAX_DEPENDENT_REQUIRED_PAIRS {
            return Err(malformed("dependentRequired pair count exceeds cap"));
        }
        let mut seen = rustc_hash::FxHashSet::default();
        seen.try_reserve(pairs.len())
            .map_err(|_| limit("dependentRequired validation set"))?;
        for pair in pairs {
            let trigger = self
                .str_at(pair.trigger)
                .ok_or_else(|| malformed("dependentRequired trigger out of range"))?;
            let required = self
                .str_at(pair.required)
                .ok_or_else(|| malformed("dependentRequired required name out of range"))?;
            if !seen.insert((trigger, required)) {
                return Err(malformed("duplicate dependentRequired pair"));
            }
        }
        Ok(())
    }

    fn compute_hash(&self) -> [u8; 32] {
        let mut digests: Vec<[u8; 32]> = Vec::with_capacity(self.nodes.len());
        for node in &self.nodes {
            digests.push(self.node_digest(node, &digests));
        }
        let mut top = blake3::Hasher::new();
        top.update(b"MFIR-ir-v");
        top.update(&self.ir_version.to_le_bytes());
        top.update(&digests[self.root.get() as usize]);
        // A def body is reachable only through the def table, so its content is folded in by slot;
        // without this two recursive schemas sharing ref structure but differing bodies would collide.
        top.update(&(self.def_targets.len() as u64).to_le_bytes());
        for target in &self.def_targets {
            top.update(&digests[target.get() as usize]);
        }
        top.update(&[self.options.object_closure as u8]);
        top.update(&[u8::from(self.options.format_assertion)]);
        top.update(&[self.options.unsupported_policy as u8]);
        top.update(&self.options.max_diagnostics.to_le_bytes());
        match self.retrieval_uri() {
            None => {
                top.update(&[0u8]);
            }
            Some(uri) => {
                top.update(&[1u8]);
                feed_bytes(&mut top, uri.as_bytes())
            }
        };
        top.update(&(self.resources.len() as u64).to_le_bytes());
        for (index, resource) in self.resources.iter().enumerate() {
            match resource.canonical_uri.and_then(|uri| self.str_at(uri)) {
                None => {
                    top.update(&[0u8]);
                }
                Some(uri) => {
                    top.update(&[1u8]);
                    feed_bytes(&mut top, uri.as_bytes())
                }
            };
            top.update(&resource.root.get().to_le_bytes());
            let resource_id = ResourceId(u32::try_from(index).unwrap_or(u32::MAX));
            for (dynamic, run) in [
                (false, resource.static_anchors),
                (true, resource.dynamic_anchors),
            ] {
                top.update(&[u8::from(dynamic)]);
                let start = run.off as usize;
                let end = start.saturating_add(run.len as usize);
                let anchors = self.anchors.get(start..end).unwrap_or(&[]);
                top.update(&(anchors.len() as u64).to_le_bytes());
                for anchor in anchors {
                    top.update(&resource_id.get().to_le_bytes());
                    feed_bytes(&mut top, self.str_at(anchor.name).unwrap_or("").as_bytes());
                    top.update(&anchor.target.get().to_le_bytes());
                }
            }
        }
        top.update(&(self.node_resources.len() as u64).to_le_bytes());
        for resource in &self.node_resources {
            top.update(&resource.get().to_le_bytes());
        }
        *top.finalize().as_bytes()
    }

    fn node_digest(&self, node: &Node, digests: &[[u8; 32]]) -> [u8; 32] {
        let mut h = blake3::Hasher::new();
        match node {
            Node::Null => h.update(&[0u8]),
            Node::Boolean => h.update(&[1u8]),
            Node::Never => h.update(&[16u8]),
            Node::StringConst { value } => {
                h.update(&[2u8]);
                feed_bytes(&mut h, self.str_at(*value).unwrap_or("").as_bytes());
                &mut h
            }
            Node::StringPattern {
                regex,
                min_len,
                max_len,
                charset,
            } => {
                h.update(&[3u8]);
                feed_bytes(&mut h, self.str_at(*regex).unwrap_or("").as_bytes());
                feed_opt_u32(&mut h, *min_len);
                feed_opt_u32(&mut h, *max_len);
                h.update(&[charset_tag(*charset)]);
                &mut h
            }
            Node::Integer {
                minimum,
                maximum,
                multiple_of,
            } => {
                h.update(&[4u8]);
                feed_opt_i64(&mut h, *minimum);
                feed_opt_i64(&mut h, *maximum);
                feed_opt_u64(&mut h, *multiple_of);
                &mut h
            }
            Node::Number {
                integer_only,
                minimum,
                maximum,
                multiple_of,
            } => {
                h.update(&[12u8]);
                h.update(&[u8::from(*integer_only)]);
                feed_opt_decimal_bound(&mut h, *minimum);
                feed_opt_decimal_bound(&mut h, *maximum);
                match multiple_of {
                    None => h.update(&[0u8]),
                    Some((coef, exp)) => h
                        .update(&[1u8])
                        .update(&coef.to_le_bytes())
                        .update(&exp.to_le_bytes()),
                };
                &mut h
            }
            Node::LexicalNumber { regex } => {
                h.update(&[17u8]);
                feed_bytes(&mut h, self.str_at(*regex).unwrap_or("").as_bytes());
                &mut h
            }
            Node::Enum { values } => {
                h.update(&[5u8]);
                let lits = self.lits_at(*values).unwrap_or(&[]);
                h.update(&(lits.len() as u64).to_le_bytes());
                for lit in lits {
                    feed_bytes(&mut h, &lit_bytes(lit));
                }
                &mut h
            }
            Node::Array {
                items,
                min_items,
                max_items,
                unique_items,
                contains,
                items_annotates,
            } => {
                h.update(&[6u8]);
                match items {
                    ItemsPolicy::Schema(id) => {
                        h.update(&[0u8]);
                        h.update(&digests[id.get() as usize]);
                    }
                    ItemsPolicy::AllowAny => {
                        h.update(&[1u8]);
                    }
                }
                h.update(&min_items.to_le_bytes());
                feed_opt_u32(&mut h, *max_items);
                h.update(&[u8::from(*unique_items)]);
                feed_contains(&mut h, contains, digests);
                h.update(&[u8::from(*items_annotates)]);
                &mut h
            }
            Node::Tuple {
                prefix,
                tail,
                min_items,
                max_items,
                unique_items,
                tail_annotates,
                contains,
            } => {
                h.update(&[13u8]);
                let ids = self.refs_at(*prefix).unwrap_or(&[]);
                h.update(&(ids.len() as u64).to_le_bytes());
                for id in ids {
                    h.update(&digests[id.get() as usize]);
                }
                match tail {
                    None => h.update(&[0u8]),
                    Some(t) => h.update(&[1u8]).update(&digests[t.get() as usize]),
                };
                h.update(&min_items.to_le_bytes());
                feed_opt_u32(&mut h, *max_items);
                h.update(&[u8::from(*unique_items)]);
                feed_contains(&mut h, contains, digests);
                h.update(&[u8::from(*tail_annotates)]);
                &mut h
            }
            Node::Object {
                fields,
                required,
                closure,
                dependent,
                dependent_required,
            } => {
                h.update(&[7u8]);
                let props = self.props_at(*fields).unwrap_or(&[]);
                h.update(&(props.len() as u64).to_le_bytes());
                // Field count is a u32 by construction, so the u32 index never overflows here.
                for ((name, child), idx) in props.iter().zip(0u32..) {
                    feed_bytes(&mut h, self.str_at(*name).unwrap_or("").as_bytes());
                    h.update(&digests[child.get() as usize]);
                    h.update(&[u8::from(self.is_required(*required, idx))]);
                }
                h.update(&[closure_tag(*closure)]);
                self.feed_dependent(&mut h, *dependent, digests);
                self.feed_dependent_required(&mut h, *dependent_required);
                &mut h
            }
            Node::OpenObject {
                known,
                known_required,
                patterns,
                additional,
                property_names,
                min_properties,
                max_properties,
                dependent,
                dependent_required,
            } => {
                h.update(&[14u8]);
                let kp = self.props_at(*known).unwrap_or(&[]);
                h.update(&(kp.len() as u64).to_le_bytes());
                for ((name, child), idx) in kp.iter().zip(0u32..) {
                    feed_bytes(&mut h, self.str_at(*name).unwrap_or("").as_bytes());
                    h.update(&digests[child.get() as usize]);
                    h.update(&[u8::from(self.is_required(*known_required, idx))]);
                }
                let pp = self.props_at(*patterns).unwrap_or(&[]);
                h.update(&(pp.len() as u64).to_le_bytes());
                for (regex, child) in pp {
                    feed_bytes(&mut h, self.str_at(*regex).unwrap_or("").as_bytes());
                    h.update(&digests[child.get() as usize]);
                }
                match additional {
                    AdditionalPolicy::Forbid => h.update(&[0u8]),
                    AdditionalPolicy::AllowAny => h.update(&[1u8]),
                    AdditionalPolicy::Schema(id) => {
                        h.update(&[2u8]).update(&digests[id.get() as usize])
                    }
                    AdditionalPolicy::Open => h.update(&[3u8]),
                };
                match property_names {
                    None => h.update(&[0u8]),
                    Some(id) => h.update(&[1u8]).update(&digests[id.get() as usize]),
                };
                feed_opt_u32(&mut h, *min_properties);
                feed_opt_u32(&mut h, *max_properties);
                self.feed_dependent(&mut h, *dependent, digests);
                self.feed_dependent_required(&mut h, *dependent_required);
                &mut h
            }
            Node::Union { branches } => {
                h.update(&[9u8]);
                let ids = self.refs_at(*branches).unwrap_or(&[]);
                h.update(&(ids.len() as u64).to_le_bytes());
                for id in ids {
                    h.update(&digests[id.get() as usize]);
                }
                &mut h
            }
            Node::Intersection { branches } => {
                h.update(&[10u8]);
                let ids = self.refs_at(*branches).unwrap_or(&[]);
                h.update(&(ids.len() as u64).to_le_bytes());
                for id in ids {
                    h.update(&digests[id.get() as usize]);
                }
                &mut h
            }
            Node::ExactlyOne { branches } => {
                h.update(&[11u8]);
                let ids = self.refs_at(*branches).unwrap_or(&[]);
                h.update(&(ids.len() as u64).to_le_bytes());
                for id in ids {
                    h.update(&digests[id.get() as usize]);
                }
                &mut h
            }
            Node::Not { inner } => {
                h.update(&[15u8]);
                h.update(&digests[inner.get() as usize]);
                &mut h
            }
            Node::Ref { def } => {
                h.update(&[17u8]);
                h.update(&def.to_le_bytes());
                &mut h
            }
            Node::DynamicRef {
                initial_target,
                anchor,
            } => {
                h.update(&[19u8]);
                h.update(&initial_target.get().to_le_bytes());
                h.update(&anchor.get().to_le_bytes());
                &mut h
            }
            Node::Unevaluated {
                kind,
                scope,
                unevaluated,
            } => {
                h.update(&[18u8]);
                h.update(&[*kind as u8]);
                h.update(&digests[scope.get() as usize]);
                h.update(&digests[unevaluated.get() as usize]);
                &mut h
            }
            Node::Unsupported { keyword, reason } => {
                h.update(&[8u8]);
                feed_bytes(&mut h, self.str_at(*keyword).unwrap_or("").as_bytes());
                h.update(&(*reason as u32).to_le_bytes());
                &mut h
            }
        };
        *h.finalize().as_bytes()
    }

    /// Feeds a `dependentSchemas` run into a node digest, keyed by name so equal sets hash equal
    /// regardless of arena insertion order.
    fn feed_dependent(&self, h: &mut blake3::Hasher, dependent: PropSlice, digests: &[[u8; 32]]) {
        let props = self.props_at(dependent).unwrap_or(&[]);
        h.update(&(props.len() as u64).to_le_bytes());
        for (name, child) in props {
            feed_bytes(h, self.str_at(*name).unwrap_or("").as_bytes());
            h.update(&digests[child.get() as usize]);
        }
    }

    fn feed_dependent_required(&self, h: &mut blake3::Hasher, dependent: DependentRequiredSlice) {
        let mut pairs: Vec<(&[u8], &[u8])> = self
            .dependent_required_at(dependent)
            .unwrap_or(&[])
            .iter()
            .map(|pair| {
                (
                    self.str_at(pair.trigger).unwrap_or("").as_bytes(),
                    self.str_at(pair.required).unwrap_or("").as_bytes(),
                )
            })
            .collect();
        pairs.sort_unstable();
        h.update(&(pairs.len() as u64).to_le_bytes());
        for (trigger, required) in pairs {
            feed_bytes(h, trigger);
            feed_bytes(h, required);
        }
    }
}

fn feed_bytes(h: &mut blake3::Hasher, bytes: &[u8]) {
    h.update(&(bytes.len() as u64).to_le_bytes());
    h.update(bytes);
}

fn feed_opt_u32(h: &mut blake3::Hasher, v: Option<u32>) {
    match v {
        None => h.update(&[0u8]),
        Some(x) => h.update(&[1u8]).update(&x.to_le_bytes()),
    };
}

fn feed_opt_i64(h: &mut blake3::Hasher, v: Option<i64>) {
    match v {
        None => h.update(&[0u8]),
        Some(x) => h.update(&[1u8]).update(&x.to_le_bytes()),
    };
}

fn feed_opt_decimal_bound(h: &mut blake3::Hasher, v: Option<(i128, u32, bool)>) {
    match v {
        None => h.update(&[0u8]),
        Some((x, scale, excl)) => h
            .update(&[1u8])
            .update(&x.to_le_bytes())
            .update(&scale.to_le_bytes())
            .update(&[u8::from(excl)]),
    };
}

/// Compares `(coefficient, scale)` decimals without scale-sized work or overflow.
pub(crate) fn decimal_cmp(a: (i128, u32), b: (i128, u32)) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    if a.0 == 0 || b.0 == 0 || a.0.is_negative() != b.0.is_negative() {
        return a.0.signum().cmp(&b.0.signum());
    }
    let (a_digits, a_len) = decimal_digits(a.0.unsigned_abs());
    let (b_digits, b_len) = decimal_digits(b.0.unsigned_abs());
    let a_exponent = i64::try_from(a_len).unwrap_or(i64::MAX) - i64::from(a.1);
    let b_exponent = i64::try_from(b_len).unwrap_or(i64::MAX) - i64::from(b.1);
    let mut magnitude = a_exponent.cmp(&b_exponent);
    if magnitude == Ordering::Equal {
        for index in 0..a_len.max(b_len) {
            magnitude = a_digits[index].cmp(&b_digits[index]);
            if magnitude != Ordering::Equal {
                break;
            }
        }
    }
    if a.0.is_negative() {
        magnitude.reverse()
    } else {
        magnitude
    }
}

fn decimal_digits(mut value: u128) -> ([u8; 39], usize) {
    let mut reverse = [0u8; 39];
    let mut length = 0;
    while value > 0 {
        reverse[length] = u8::try_from(value % 10).unwrap_or(0);
        value /= 10;
        length += 1;
    }
    let mut digits = [0u8; 39];
    for index in 0..length {
        digits[index] = reverse[length - index - 1];
    }
    (digits, length)
}

fn feed_contains(
    h: &mut blake3::Hasher,
    contains: &Option<ContainsConstraint>,
    digests: &[[u8; 32]],
) {
    match contains {
        None => {
            h.update(&[0u8]);
        }
        Some(c) => {
            h.update(&[1u8]);
            match c.policy {
                ContainsPolicy::Never => h.update(&[0u8]),
                ContainsPolicy::Always => h.update(&[1u8]),
                ContainsPolicy::Schema(id) => h.update(&[2u8]).update(&digests[id.get() as usize]),
            };
            h.update(&c.min.to_le_bytes());
            feed_opt_u32(h, c.max);
        }
    }
}

fn feed_opt_u64(h: &mut blake3::Hasher, v: Option<u64>) {
    match v {
        None => h.update(&[0u8]),
        Some(x) => h.update(&[1u8]).update(&x.to_le_bytes()),
    };
}

fn charset_tag(c: Charset) -> u8 {
    match c {
        Charset::Utf8Any => 0,
        Charset::AsciiPrintableNoQuoteBackslash => 1,
        Charset::Utf8CountedCodepoints => 2,
    }
}

fn closure_tag(c: ObjectClosure) -> u8 {
    match c {
        ObjectClosure::RejectOpenObjects => 0,
        ObjectClosure::AssumeClosedProfile => 1,
        ObjectClosure::Forbidden => 2,
        ObjectClosure::AllowOpenProfile => 3,
    }
}

fn lit_bytes(lit: &ScalarLit) -> Vec<u8> {
    match lit {
        ScalarLit::Null => vec![0u8],
        ScalarLit::Bool(b) => vec![1u8, u8::from(*b)],
        ScalarLit::Int(i) => {
            let mut v = vec![2u8];
            v.extend_from_slice(&i.to_le_bytes());
            v
        }
        ScalarLit::Str(s) => {
            let mut v = vec![3u8];
            v.extend_from_slice(s.as_bytes());
            v
        }
        ScalarLit::Json(s) => {
            let mut v = vec![4u8];
            v.extend_from_slice(s.as_bytes());
            v
        }
    }
}

/// Rejects patterns the byte-level engine cannot compile.
fn validate_pattern(regex: &str) -> Result<(), CompileError> {
    if has_anchor_outside_brackets(regex.as_bytes()) {
        return Err(unsupported("explicit anchors are not allowed"));
    }
    validate_pattern_body(regex, false)
}

/// Like `validate_pattern`, but permits `^` and `$` for structured search.
/// Used by `patternProperties` and `propertyNames`.
pub(crate) fn validate_search_pattern(regex: &str) -> Result<(), CompileError> {
    validate_pattern_body(regex, true)
}

fn validate_pattern_body(regex: &str, allow_leading_assertions: bool) -> Result<(), CompileError> {
    use crate::frontend::regex::{analyze_compiled_pattern, PatternAnalysis};

    match analyze_compiled_pattern(regex) {
        PatternAnalysis::Ordinary => Ok(()),
        PatternAnalysis::Leading(_) if allow_leading_assertions => Ok(()),
        PatternAnalysis::Leading(_) => {
            Err(unsupported("unsupported regex construct").with_observed("look-ahead"))
        }
        PatternAnalysis::Unsupported(what) => {
            Err(unsupported("unsupported regex construct").with_observed(what))
        }
        PatternAnalysis::Malformed(what) => {
            Err(malformed("malformed regex syntax").with_observed(what))
        }
    }
}

/// True if `^` or `$` appears as an anchor (outside a bracket expression, unescaped). Inside
/// `[...]` those bytes are a negation or a literal, which the byte engine accepts.
pub(crate) fn has_anchor_outside_brackets(bytes: &[u8]) -> bool {
    let mut in_bracket = false;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 1,
            b'[' if !in_bracket => in_bracket = true,
            b']' if in_bracket => in_bracket = false,
            b'^' | b'$' if !in_bracket => return true,
            _ => {}
        }
        i += 1;
    }
    false
}

fn err(code: ErrorCode, message: &'static str) -> CompileError {
    CompileError::new(code, Stage::L2, message)
}

fn malformed(message: &'static str) -> CompileError {
    CompileError::new(ErrorCode::Malformed, Stage::L2, message)
}

fn validate_canonical_uri(value: &str) -> Result<(), CompileError> {
    let uri = Uri::parse(value).map_err(|_| malformed("canonical resource URI is invalid"))?;
    if uri.fragment().is_some() || uri.normalize().as_str() != value {
        return Err(malformed(
            "resource URI is not fragmentless canonical RFC 3986 form",
        ));
    }
    Ok(())
}

fn unsupported(message: &'static str) -> CompileError {
    CompileError::new(ErrorCode::Unsupported, Stage::L2, message)
}

/// Hash-consing arena builder. Structurally equal subtrees collapse to one `NodeId` because every
/// side blob is content-interned, so equal children yield equal `Node` values.
pub struct Builder {
    nodes: Vec<Node>,
    strings: Vec<u8>,
    literals: Vec<ScalarLit>,
    props: Vec<(StrRef, NodeId)>,
    dependent_required_pairs: Vec<DependentRequiredPair>,
    required_bits: Vec<u64>,
    node_refs: Vec<NodeId>,
    def_targets: Vec<Option<NodeId>>,
    diagnostics: Vec<Diagnostic>,
    literal_str_bytes: usize,
    node_intern: FxHashMap<(ResourceId, Node), NodeId>,
    node_resources: Vec<ResourceId>,
    current_resource: ResourceId,
    str_intern: FxHashMap<String, StrRef>,
    lit_intern: FxHashMap<Vec<ScalarLit>, LitSlice>,
    prop_intern: FxHashMap<Vec<(StrRef, NodeId)>, PropSlice>,
    dependent_required_intern: FxHashMap<Vec<DependentRequiredPair>, DependentRequiredSlice>,
    bit_intern: FxHashMap<Vec<u64>, BitSlice>,
    ref_intern: FxHashMap<Vec<NodeId>, RefSlice>,
    options: CompileOptions,
}

impl Builder {
    /// A new builder with the given options.
    #[must_use]
    pub fn new(options: CompileOptions) -> Self {
        Self {
            nodes: Vec::new(),
            strings: Vec::new(),
            literals: Vec::new(),
            props: Vec::new(),
            dependent_required_pairs: Vec::new(),
            required_bits: Vec::new(),
            node_refs: Vec::new(),
            def_targets: Vec::new(),
            diagnostics: Vec::new(),
            literal_str_bytes: 0,
            node_intern: FxHashMap::default(),
            node_resources: Vec::new(),
            current_resource: ResourceId(0),
            str_intern: FxHashMap::default(),
            lit_intern: FxHashMap::default(),
            prop_intern: FxHashMap::default(),
            dependent_required_intern: FxHashMap::default(),
            bit_intern: FxHashMap::default(),
            ref_intern: FxHashMap::default(),
            options,
        }
    }

    /// Interns a UTF-8 string, returning a content-addressed reference.
    fn intern_str(&mut self, s: &str) -> Result<StrRef, CompileError> {
        if let Some(r) = self.str_intern.get(s) {
            return Ok(*r);
        }
        if self
            .strings
            .len()
            .checked_add(s.len())
            .is_none_or(|n| n > MAX_STRINGS_BYTES)
        {
            return Err(limit("strings blob cap"));
        }
        let off = u32::try_from(self.strings.len()).map_err(|_| limit("strings blob"))?;
        let len = u32::try_from(s.len()).map_err(|_| limit("string length"))?;
        self.strings.extend_from_slice(s.as_bytes());
        let r = StrRef { off, len };
        self.str_intern.insert(s.to_owned(), r);
        Ok(r)
    }

    fn intern_lits(&mut self, lits: Vec<ScalarLit>) -> Result<LitSlice, CompileError> {
        if let Some(r) = self.lit_intern.get(&lits) {
            return Ok(*r);
        }
        if self
            .literals
            .len()
            .checked_add(lits.len())
            .is_none_or(|n| n > MAX_LITERALS)
        {
            return Err(limit("literals cap"));
        }
        if self
            .literal_str_bytes
            .checked_add(literal_str_bytes(&lits))
            .is_none_or(|n| n > MAX_LITERAL_STR_BYTES)
        {
            return Err(limit("literal string bytes cap"));
        }
        self.literal_str_bytes += literal_str_bytes(&lits);
        let off = u32::try_from(self.literals.len()).map_err(|_| limit("literals blob"))?;
        let len = u32::try_from(lits.len()).map_err(|_| limit("literal run"))?;
        self.literals.extend_from_slice(&lits);
        let r = LitSlice { off, len };
        self.lit_intern.insert(lits, r);
        Ok(r)
    }

    fn intern_props(&mut self, pairs: Vec<(StrRef, NodeId)>) -> Result<PropSlice, CompileError> {
        if let Some(r) = self.prop_intern.get(&pairs) {
            return Ok(*r);
        }
        if self
            .props
            .len()
            .checked_add(pairs.len())
            .is_none_or(|n| n > MAX_PROPS)
        {
            return Err(limit("props cap"));
        }
        let off = u32::try_from(self.props.len()).map_err(|_| limit("props blob"))?;
        let len = u32::try_from(pairs.len()).map_err(|_| limit("prop run"))?;
        self.props.extend_from_slice(&pairs);
        let r = PropSlice { off, len };
        self.prop_intern.insert(pairs, r);
        Ok(r)
    }

    /// `groups` is `(trigger, required names)`: each trigger and each required name is owned
    /// exactly once by the caller. Interns the trigger once per group (never once per edge),
    /// reserves the flattened pair vector fallibly against the checked total edge count, and
    /// keeps the existing sorted/deduplicated/shared-slice arena representation.
    fn intern_dependent_required(
        &mut self,
        mut groups: Vec<(String, Vec<String>)>,
    ) -> Result<DependentRequiredSlice, CompileError> {
        let total_edges = groups
            .iter()
            .try_fold(0usize, |total, (_, required)| {
                total.checked_add(required.len())
            })
            .ok_or_else(|| limit("dependentRequired pair count"))?;
        if total_edges > MAX_DEPENDENT_REQUIRED_PAIRS {
            return Err(limit("dependentRequired pair count"));
        }
        groups.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
        if groups.windows(2).any(|pair| pair[0].0 == pair[1].0) {
            return Err(malformed("duplicate dependentRequired trigger"));
        }
        for (_, required) in &mut groups {
            required.sort_unstable();
            if required.windows(2).any(|pair| pair[0] == pair[1]) {
                return Err(malformed("duplicate dependentRequired pair"));
            }
        }
        let mut refs = Vec::new();
        refs.try_reserve_exact(total_edges)
            .map_err(|_| limit("dependentRequired pair arena"))?;
        for (trigger, required) in &groups {
            let trigger_ref = self.intern_str(trigger)?;
            for name in required {
                refs.push(DependentRequiredPair {
                    trigger: trigger_ref,
                    required: self.intern_str(name)?,
                });
            }
        }
        if let Some(r) = self.dependent_required_intern.get(&refs) {
            return Ok(*r);
        }
        if self
            .dependent_required_pairs
            .len()
            .checked_add(refs.len())
            .is_none_or(|n| n > MAX_DEPENDENT_REQUIRED_PAIRS)
        {
            return Err(limit("dependentRequired pair arena"));
        }
        let off = u32::try_from(self.dependent_required_pairs.len())
            .map_err(|_| limit("dependentRequired pair arena"))?;
        let len = u32::try_from(refs.len()).map_err(|_| limit("dependentRequired pair run"))?;
        self.dependent_required_pairs
            .try_reserve_exact(refs.len())
            .map_err(|_| limit("dependentRequired pair arena"))?;
        self.dependent_required_pairs.extend_from_slice(&refs);
        let slice = DependentRequiredSlice { off, len };
        self.dependent_required_intern.insert(refs, slice);
        Ok(slice)
    }

    fn intern_bits(&mut self, words: Vec<u64>, field_count: u32) -> Result<BitSlice, CompileError> {
        if let Some(r) = self.bit_intern.get(&words) {
            return Ok(BitSlice {
                off: r.off,
                len: field_count,
            });
        }
        if self
            .required_bits
            .len()
            .checked_add(words.len())
            .is_none_or(|n| n > MAX_REQUIRED_WORDS)
        {
            return Err(limit("required words cap"));
        }
        let off = u32::try_from(self.required_bits.len()).map_err(|_| limit("required blob"))?;
        self.required_bits.extend_from_slice(&words);
        let r = BitSlice {
            off,
            len: field_count,
        };
        self.bit_intern.insert(words, r);
        Ok(r)
    }

    fn intern_refs(&mut self, refs: Vec<NodeId>) -> Result<RefSlice, CompileError> {
        if let Some(r) = self.ref_intern.get(&refs) {
            return Ok(*r);
        }
        if self
            .node_refs
            .len()
            .checked_add(refs.len())
            .is_none_or(|n| n > MAX_NODE_REFS)
        {
            return Err(limit("node refs cap"));
        }
        let off = u32::try_from(self.node_refs.len()).map_err(|_| limit("node refs blob"))?;
        let len = u32::try_from(refs.len()).map_err(|_| limit("node ref run"))?;
        self.node_refs.extend_from_slice(&refs);
        let r = RefSlice { off, len };
        self.ref_intern.insert(refs, r);
        Ok(r)
    }

    fn intern_node(&mut self, node: Node) -> Result<NodeId, CompileError> {
        if let Some(id) = self.node_intern.get(&(self.current_resource, node.clone())) {
            return Ok(*id);
        }
        if self.nodes.len() >= MAX_NODES {
            return Err(limit("node cap"));
        }
        let id = NodeId::try_from(self.nodes.len()).map_err(|_| limit("node count"))?;
        self.nodes.push(node.clone());
        self.node_resources.push(self.current_resource);
        self.node_intern.insert((self.current_resource, node), id);
        Ok(id)
    }

    pub(crate) fn set_current_resource(&mut self, resource: ResourceId) -> ResourceId {
        std::mem::replace(&mut self.current_resource, resource)
    }

    /// Interns a `null` node.
    pub fn null(&mut self) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Null)
    }

    /// Interns a `boolean` node.
    pub fn boolean(&mut self) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Boolean)
    }

    /// Interns a node matching no value at all (the bare `false` schema).
    pub fn never(&mut self) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Never)
    }

    /// Interns a string-const node.
    pub fn string_const(&mut self, value: &str) -> Result<NodeId, CompileError> {
        let value = self.intern_str(value)?;
        self.intern_node(Node::StringConst { value })
    }

    /// Interns a string-pattern node.
    pub fn string_pattern(
        &mut self,
        regex: &str,
        min_len: Option<u32>,
        max_len: Option<u32>,
        charset: Charset,
    ) -> Result<NodeId, CompileError> {
        let regex = self.intern_str(regex)?;
        self.intern_node(Node::StringPattern {
            regex,
            min_len,
            max_len,
            charset,
        })
    }

    /// Interns an integer node.
    pub fn integer(
        &mut self,
        minimum: Option<i64>,
        maximum: Option<i64>,
    ) -> Result<NodeId, CompileError> {
        self.integer_multiple_of(minimum, maximum, None)
    }

    /// Interns an integer node with an exact `multipleOf` divisor.
    pub fn integer_multiple_of(
        &mut self,
        minimum: Option<i64>,
        maximum: Option<i64>,
        multiple_of: Option<u64>,
    ) -> Result<NodeId, CompileError> {
        if multiple_of == Some(0) {
            return Err(malformed("multipleOf must be a positive integer"));
        }
        self.intern_node(Node::Integer {
            minimum,
            maximum,
            multiple_of,
        })
    }

    /// Interns an unbounded `number` node (the full JSON numeric grammar).
    pub fn number(&mut self) -> Result<NodeId, CompileError> {
        self.number_range(None, None, None)
    }

    /// Interns a `number` node with an integer-valued inclusive/exclusive bound and/or a decimal
    /// `multipleOf` (`coef * 10^-exp`).
    pub fn number_range(
        &mut self,
        minimum: Option<(i128, u32, bool)>,
        maximum: Option<(i128, u32, bool)>,
        multiple_of: Option<(u64, u32)>,
    ) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Number {
            integer_only: false,
            minimum,
            maximum,
            multiple_of,
        })
    }

    /// Interns exact decimal constraints whose accepted values must be mathematically integral.
    pub fn integer_number_range(
        &mut self,
        minimum: Option<(i128, u32, bool)>,
        maximum: Option<(i128, u32, bool)>,
        multiple_of: Option<(u64, u32)>,
    ) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Number {
            integer_only: true,
            minimum,
            maximum,
            multiple_of,
        })
    }

    /// Interns a lexical JSON-number constraint.
    pub fn lexical_number(&mut self, regex: &str) -> Result<NodeId, CompileError> {
        validate_pattern(regex)?;
        let regex = self.intern_str(regex)?;
        self.intern_node(Node::LexicalNumber { regex })
    }

    /// Interns an enum node. Values are canonically sorted; a duplicate value is rejected.
    pub fn enum_values(&mut self, mut values: Vec<ScalarLit>) -> Result<NodeId, CompileError> {
        if values.is_empty() {
            return Err(malformed("an enum must have at least one value"));
        }
        values.sort();
        if values.windows(2).any(|w| w[0] == w[1]) {
            return Err(malformed("duplicate enum value"));
        }
        let values = self.intern_lits(values)?;
        self.intern_node(Node::Enum { values })
    }

    /// Interns an array node.
    pub fn array(
        &mut self,
        items: NodeId,
        min_items: u32,
        max_items: Option<u32>,
    ) -> Result<NodeId, CompileError> {
        self.array_unique(items, min_items, max_items, false)
    }

    /// Interns an array node with an explicit `uniqueItems` flag.
    pub fn array_unique(
        &mut self,
        items: NodeId,
        min_items: u32,
        max_items: Option<u32>,
        unique_items: bool,
    ) -> Result<NodeId, CompileError> {
        self.array_full(
            ItemsPolicy::Schema(items),
            min_items,
            max_items,
            unique_items,
            None,
            true,
        )
    }

    /// Interns an array node with unconstrained (`items: true` or absent) elements.
    pub fn array_open(
        &mut self,
        min_items: u32,
        max_items: Option<u32>,
        unique_items: bool,
    ) -> Result<NodeId, CompileError> {
        self.array_full(
            ItemsPolicy::AllowAny,
            min_items,
            max_items,
            unique_items,
            None,
            true,
        )
    }

    /// Interns an array node with every keyword explicit, including `contains` and whether `items`
    /// was textually present (`items_annotates`, for `unevaluatedItems`).
    #[allow(clippy::too_many_arguments)]
    pub fn array_full(
        &mut self,
        items: ItemsPolicy,
        min_items: u32,
        max_items: Option<u32>,
        unique_items: bool,
        contains: Option<ContainsConstraint>,
        items_annotates: bool,
    ) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Array {
            items,
            min_items,
            max_items,
            unique_items,
            contains,
            items_annotates,
        })
    }

    /// Interns a tuple array with positional `prefix` schemas and an optional `tail` schema.
    /// Closed tuples whose minimum exceeds the prefix length are rejected.
    pub fn tuple(
        &mut self,
        prefix: Vec<NodeId>,
        tail: Option<NodeId>,
        min_items: u32,
        max_items: Option<u32>,
    ) -> Result<NodeId, CompileError> {
        self.tuple_unique(prefix, tail, min_items, max_items, false)
    }

    /// Interns a positional (tuple) array node with an explicit `uniqueItems` flag.
    pub fn tuple_unique(
        &mut self,
        prefix: Vec<NodeId>,
        tail: Option<NodeId>,
        min_items: u32,
        max_items: Option<u32>,
        unique_items: bool,
    ) -> Result<NodeId, CompileError> {
        self.tuple_full(prefix, tail, min_items, max_items, unique_items, None, true)
    }

    /// Interns a positional (tuple) array node with every keyword explicit, including `contains` and
    /// whether the tail was textually present (`tail_annotates`, for `unevaluatedItems`).
    #[allow(clippy::too_many_arguments)]
    pub fn tuple_full(
        &mut self,
        prefix: Vec<NodeId>,
        tail: Option<NodeId>,
        min_items: u32,
        max_items: Option<u32>,
        unique_items: bool,
        contains: Option<ContainsConstraint>,
        tail_annotates: bool,
    ) -> Result<NodeId, CompileError> {
        if prefix.is_empty() {
            return Err(malformed("a tuple must have at least one prefix position"));
        }
        let prefix = self.intern_refs(prefix)?;
        self.intern_node(Node::Tuple {
            prefix,
            tail,
            min_items,
            max_items,
            unique_items,
            tail_annotates,
            contains,
        })
    }

    /// Interns a type-union node. `branches` are child nodes in declaration order; a single branch
    /// collapses to that branch directly rather than a one-element union.
    pub fn union_of(&mut self, branches: Vec<NodeId>) -> Result<NodeId, CompileError> {
        if branches.is_empty() {
            return Err(malformed("a type union must have at least one branch"));
        }
        if branches.len() == 1 {
            return Ok(branches[0]);
        }
        let branches = self.intern_refs(branches)?;
        self.intern_node(Node::Union { branches })
    }

    /// Reserves a def slot for a recursive definition and returns its index. The slot is filled by
    /// [`Builder::set_def_target`] once the body is lowered; a `Node::Ref` may point at it meanwhile.
    pub fn alloc_def_slot(&mut self) -> Result<u32, CompileError> {
        let slot = u32::try_from(self.def_targets.len()).map_err(|_| limit("def slot count"))?;
        if self.def_targets.len() >= MAX_NODES {
            return Err(limit("def slot cap"));
        }
        self.def_targets.push(None);
        Ok(slot)
    }

    /// Points a reserved def slot at its lowered body root. Fails on an out-of-range slot or one
    /// already assigned, rather than silently overwriting or indexing out of bounds.
    pub fn set_def_target(&mut self, slot: u32, body: NodeId) -> Result<(), CompileError> {
        let entry = self
            .def_targets
            .get_mut(slot as usize)
            .ok_or_else(|| malformed("def slot index out of range"))?;
        if entry.replace(body).is_some() {
            return Err(malformed("def slot already assigned"));
        }
        Ok(())
    }

    /// Interns a `Node::Ref` naming a reserved def slot (a recursion cut point).
    pub fn ref_node(&mut self, def: u32) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Ref { def })
    }

    /// Interns an already-statically-resolved dynamic reference.
    pub fn dynamic_ref(
        &mut self,
        initial_target: NodeId,
        anchor: AnchorId,
    ) -> Result<NodeId, CompileError> {
        self.intern_node(Node::DynamicRef {
            initial_target,
            anchor,
        })
    }

    /// Interns an `unevaluatedProperties`/`unevaluatedItems` obligation over `scope`, with
    /// `unevaluated` applied to each member `scope` did not annotate.
    pub fn unevaluated(
        &mut self,
        kind: UnevaluatedKind,
        scope: NodeId,
        unevaluated: NodeId,
    ) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Unevaluated {
            kind,
            scope,
            unevaluated,
        })
    }

    /// Interns an `allOf` intersection in declaration order.
    /// A single branch collapses to itself.
    pub fn intersection_of(&mut self, branches: Vec<NodeId>) -> Result<NodeId, CompileError> {
        if branches.is_empty() {
            return Err(malformed("an intersection must have at least one branch"));
        }
        if branches.len() == 1 {
            return Ok(branches[0]);
        }
        let branches = self.intern_refs(branches)?;
        self.intern_node(Node::Intersection { branches })
    }

    /// Interns a `oneOf` exactly-one node in declaration order.
    /// A single branch collapses to itself because exactly-one preserves its language.
    pub fn exactly_one_of(&mut self, branches: Vec<NodeId>) -> Result<NodeId, CompileError> {
        if branches.is_empty() {
            return Err(malformed("an exactly-one must have at least one branch"));
        }
        if branches.len() == 1 {
            return Ok(branches[0]);
        }
        let branches = self.intern_refs(branches)?;
        self.intern_node(Node::ExactlyOne { branches })
    }

    /// Interns a `not`: matches any complete JSON value `inner` does not.
    pub fn not(&mut self, inner: NodeId) -> Result<NodeId, CompileError> {
        self.intern_node(Node::Not { inner })
    }

    /// Interns `(name, child)` pairs plus their aligned required bitset; shared by `object` and
    /// `open_object`. A duplicate field name is rejected.
    fn intern_named_fields(
        &mut self,
        fields: Vec<(String, NodeId)>,
        required: &[bool],
    ) -> Result<(PropSlice, BitSlice), CompileError> {
        if required.len() != fields.len() {
            return Err(malformed("required flags do not align with fields"));
        }
        let mut names: FxHashMap<&str, ()> = FxHashMap::default();
        names.reserve(fields.len());
        for (name, _) in &fields {
            if names.insert(name.as_str(), ()).is_some() {
                return Err(malformed("duplicate object key"));
            }
        }
        let mut pairs = Vec::with_capacity(fields.len());
        for (name, child) in &fields {
            let name = self.intern_str(name)?;
            pairs.push((name, *child));
        }
        let field_count = u32::try_from(fields.len()).map_err(|_| limit("object field count"))?;
        let words = fields.len().div_ceil(64);
        let mut bits = vec![0u64; words];
        for (i, &req) in required.iter().enumerate() {
            if req {
                bits[i / 64] |= 1u64 << (i % 64);
            }
        }
        let fields = self.intern_props(pairs)?;
        let required = self.intern_bits(bits, field_count)?;
        Ok((fields, required))
    }

    /// Interns an object node. `fields` are `(name, child)` in source order; `required` is aligned
    /// to `fields` by position. A duplicate field name is rejected.
    pub fn object(
        &mut self,
        fields: Vec<(String, NodeId)>,
        required: &[bool],
        closure: ObjectClosure,
    ) -> Result<NodeId, CompileError> {
        self.object_full(fields, required, closure, Vec::new(), Vec::new())
    }

    /// Interns an object with `dependentSchemas`: `(key, schema)` pairs where `key`'s presence in
    /// the instance additionally requires the whole instance to satisfy `schema`.
    pub fn object_full(
        &mut self,
        fields: Vec<(String, NodeId)>,
        required: &[bool],
        closure: ObjectClosure,
        dependent: Vec<(String, NodeId)>,
        dependent_required: Vec<(String, Vec<String>)>,
    ) -> Result<NodeId, CompileError> {
        let (fields, required) = self.intern_named_fields(fields, required)?;
        let dependent = self.intern_dependent(dependent)?;
        let dependent_required = self.intern_dependent_required(dependent_required)?;
        self.intern_node(Node::Object {
            fields,
            required,
            closure,
            dependent,
            dependent_required,
        })
    }

    fn intern_dependent(
        &mut self,
        dependent: Vec<(String, NodeId)>,
    ) -> Result<PropSlice, CompileError> {
        let mut pairs = Vec::with_capacity(dependent.len());
        for (name, child) in dependent {
            let name_ref = self.intern_str(&name)?;
            pairs.push((name_ref, child));
        }
        self.intern_props(pairs)
    }

    /// Interns an order-independent open object. `known`/`known_required` behave like `object`'s
    /// `fields`/`required`; `patterns` are `(regex, child)` `patternProperties` entries.
    #[allow(clippy::too_many_arguments)]
    pub fn open_object(
        &mut self,
        known: Vec<(String, NodeId)>,
        known_required: &[bool],
        patterns: Vec<(String, NodeId)>,
        additional: AdditionalPolicy,
        property_names: Option<NodeId>,
        min_properties: Option<u32>,
        max_properties: Option<u32>,
    ) -> Result<NodeId, CompileError> {
        self.open_object_full(
            known,
            known_required,
            patterns,
            additional,
            property_names,
            min_properties,
            max_properties,
            Vec::new(),
            Vec::new(),
        )
    }

    /// Interns an order-independent open object with `dependentSchemas`, same semantics as
    /// `object_full`'s.
    #[allow(clippy::too_many_arguments)]
    pub fn open_object_full(
        &mut self,
        known: Vec<(String, NodeId)>,
        known_required: &[bool],
        patterns: Vec<(String, NodeId)>,
        additional: AdditionalPolicy,
        property_names: Option<NodeId>,
        min_properties: Option<u32>,
        max_properties: Option<u32>,
        dependent: Vec<(String, NodeId)>,
        dependent_required: Vec<(String, Vec<String>)>,
    ) -> Result<NodeId, CompileError> {
        if let (Some(lo), Some(hi)) = (min_properties, max_properties) {
            if hi < lo {
                return Err(malformed("maxProperties is less than minProperties"));
            }
        }
        let (known, known_required) = self.intern_named_fields(known, known_required)?;
        let mut pattern_pairs = Vec::with_capacity(patterns.len());
        for (regex, child) in &patterns {
            let regex_ref = self.intern_str(regex)?;
            pattern_pairs.push((regex_ref, *child));
        }
        let patterns = self.intern_props(pattern_pairs)?;
        let dependent = self.intern_dependent(dependent)?;
        let dependent_required = self.intern_dependent_required(dependent_required)?;
        self.intern_node(Node::OpenObject {
            known,
            known_required,
            patterns,
            additional,
            property_names,
            min_properties,
            max_properties,
            dependent,
            dependent_required,
        })
    }

    /// Interns an `Unsupported` node and records a diagnostic for this occurrence. Returns the
    /// node id, or `TooManyDiagnostics` once the bounded buffer is full.
    pub fn unsupported(
        &mut self,
        keyword: &str,
        reason: UnsupportedReason,
        json_pointer: &str,
    ) -> Result<NodeId, CompileError> {
        if self.diagnostics.len() >= MAX_DIAGNOSTICS
            || self.diagnostics.len() as u64 >= u64::from(self.options.max_diagnostics)
        {
            return Err(CompileError::new(
                ErrorCode::TooManyDiagnostics,
                Stage::L2,
                "diagnostics buffer is full",
            ));
        }
        let keyword_ref = self.intern_str(keyword)?;
        let pointer_ref = self.intern_str(json_pointer)?;
        let node = self.intern_node(Node::Unsupported {
            keyword: keyword_ref,
            reason,
        })?;
        self.diagnostics.push(Diagnostic {
            node,
            keyword: keyword_ref,
            json_pointer: pointer_ref,
            source_span: None,
            reason,
        });
        Ok(node)
    }

    /// Freezes the arena into an immutable IR rooted at `root`, running full validation.
    pub fn finish(self, root: NodeId) -> Result<SchemaIR, CompileError> {
        self.finish_with_resources(
            root,
            None,
            vec![ResourceInput {
                canonical_uri: None,
                root,
                static_anchors: Vec::new(),
                dynamic_anchors: Vec::new(),
            }],
        )
    }

    pub(crate) fn finish_with_resources(
        mut self,
        root: NodeId,
        retrieval_uri: Option<String>,
        resource_inputs: Vec<ResourceInput>,
    ) -> Result<SchemaIR, CompileError> {
        let retrieval_uri = retrieval_uri
            .as_deref()
            .map(|uri| self.intern_str(uri))
            .transpose()?;
        let mut resources = Vec::new();
        resources
            .try_reserve_exact(resource_inputs.len())
            .map_err(|_| limit("resource allocation"))?;
        let mut anchors = Vec::new();
        for (index, input) in resource_inputs.into_iter().enumerate() {
            let resource = ResourceId(u32::try_from(index).map_err(|_| limit("resource index"))?);
            let canonical_uri = input
                .canonical_uri
                .as_deref()
                .map(|uri| self.intern_str(uri))
                .transpose()?;
            let static_off = u32::try_from(anchors.len()).map_err(|_| limit("anchor offset"))?;
            for (name, target) in input.static_anchors {
                let name = self.intern_str(&name)?;
                anchors.push(AnchorRecord {
                    resource,
                    name,
                    target,
                });
            }
            let static_len = u32::try_from(anchors.len())
                .map_err(|_| limit("anchor count"))?
                .checked_sub(static_off)
                .ok_or_else(|| limit("anchor run"))?;
            let dynamic_off = u32::try_from(anchors.len()).map_err(|_| limit("anchor offset"))?;
            for (name, target) in input.dynamic_anchors {
                let name = self.intern_str(&name)?;
                anchors.push(AnchorRecord {
                    resource,
                    name,
                    target,
                });
            }
            let dynamic_len = u32::try_from(anchors.len())
                .map_err(|_| limit("anchor count"))?
                .checked_sub(dynamic_off)
                .ok_or_else(|| limit("anchor run"))?;
            resources.push(ResourceRecord {
                canonical_uri,
                root: input.root,
                static_anchors: AnchorSlice {
                    off: static_off,
                    len: static_len,
                },
                dynamic_anchors: AnchorSlice {
                    off: dynamic_off,
                    len: dynamic_len,
                },
            });
        }
        let def_targets = self
            .def_targets
            .into_iter()
            .map(|t| t.ok_or_else(|| malformed("def slot never assigned a target")))
            .collect::<Result<Vec<NodeId>, CompileError>>()?;
        SchemaIR::assemble(SchemaIRWire {
            ir_version: IR_VERSION,
            root,
            nodes: self.nodes,
            strings: self.strings,
            literals: self.literals,
            props: self.props,
            dependent_required_pairs: self.dependent_required_pairs,
            required_bits: self.required_bits,
            node_refs: self.node_refs,
            def_targets,
            retrieval_uri,
            resources,
            anchors,
            node_resources: self.node_resources,
            options: self.options,
            diagnostics: self.diagnostics,
        })
    }
}

fn limit(what: &'static str) -> CompileError {
    CompileError::new(ErrorCode::InternalLimitExceeded, Stage::L2, what)
}

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

    fn opts() -> CompileOptions {
        CompileOptions::default()
    }

    #[test]
    fn identical_subschemas_share_one_node_id() {
        let mut b = Builder::new(opts());
        let a = b.boolean().unwrap();
        let c = b.boolean().unwrap();
        assert_eq!(a, c, "boolean is interned once");
        let obj = b
            .object(
                vec![("x".into(), a), ("y".into(), c)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir = b.finish(obj).unwrap();
        // two occurrences of boolean, one distinct boolean node (plus the object).
        assert_eq!(ir.node_count(), 2);
    }

    #[test]
    fn finish_rejects_an_unfilled_def_slot() {
        let mut b = Builder::new(opts());
        let slot = b.alloc_def_slot().unwrap();
        let root = b.ref_node(slot).unwrap();
        assert!(b.finish(root).is_err());
    }

    #[test]
    fn set_def_target_rejects_a_second_assignment_to_the_same_slot() {
        let mut b = Builder::new(opts());
        let slot = b.alloc_def_slot().unwrap();
        let a = b.boolean().unwrap();
        let c = b.boolean().unwrap();
        b.set_def_target(slot, a).unwrap();
        assert!(b.set_def_target(slot, c).is_err());
    }

    #[test]
    fn set_def_target_rejects_an_out_of_range_slot() {
        let mut b = Builder::new(opts());
        let a = b.boolean().unwrap();
        assert!(b.set_def_target(0, a).is_err());
    }

    #[test]
    fn object_with_few_fields_but_heavy_bounded_strings_needs_structured_backend() {
        let mut b = Builder::new(opts());
        let a = b
            .string_pattern("(?:.)", None, Some(100), Charset::Utf8CountedCodepoints)
            .unwrap();
        let c = b
            .string_pattern("(?:.)", None, Some(2048), Charset::Utf8CountedCodepoints)
            .unwrap();
        let obj = b
            .object(
                vec![("a".into(), a), ("c".into(), c)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir = b.finish(obj).unwrap();
        assert!(
            ir.requires_structured_backend(),
            "2 fields, well under MAX_SAFE_SHUFFLE_FIELDS, but weight 100+2048 exceeds the cap"
        );
    }

    #[test]
    fn three_fields_with_a_255_scalar_string_exceed_the_shuffle_edge_bound() {
        let mut b = Builder::new(opts());
        let label = b
            .string_pattern("(?:.)", Some(2), Some(255), Charset::Utf8CountedCodepoints)
            .unwrap();
        let boolean = b.boolean().unwrap();
        let obj = b
            .object(
                vec![
                    ("category".into(), label),
                    ("generate_entities".into(), boolean),
                    ("label".into(), label),
                ],
                &[false, false, true],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir = b.finish(obj).unwrap();
        assert!(ir.requires_structured_backend());
    }

    #[test]
    fn large_minimum_array_needs_structured_backend_even_without_a_maximum() {
        let mut b = Builder::new(opts());
        let item = b.null().unwrap();
        let array = b.array(item, MAX_UNROLLED_ARRAY_ITEMS + 1, None).unwrap();
        let ir = b.finish(array).unwrap();
        assert!(ir.requires_structured_backend());
    }

    #[test]
    fn object_with_small_bounded_strings_stays_on_the_fast_dfa_path() {
        let mut b = Builder::new(opts());
        let a = b
            .string_pattern("(?:.)", None, Some(50), Charset::Utf8CountedCodepoints)
            .unwrap();
        let c = b
            .string_pattern("(?:.)", None, Some(50), Charset::Utf8CountedCodepoints)
            .unwrap();
        let obj = b
            .object(
                vec![("a".into(), a), ("c".into(), c)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir = b.finish(obj).unwrap();
        assert!(!ir.requires_structured_backend());
    }

    #[test]
    fn single_optional_heavy_bounded_string_routes_before_shuffle_construction() {
        let mut b = Builder::new(opts());
        let a = b
            .string_pattern("(?:.)", None, Some(4096), Charset::Utf8CountedCodepoints)
            .unwrap();
        let obj = b
            .object(vec![("a".into(), a)], &[false], ObjectClosure::Forbidden)
            .unwrap();
        let ir = b.finish(obj).unwrap();
        assert!(ir.requires_structured_backend());
    }

    #[test]
    fn heavy_bounded_string_wrapped_in_a_nullable_union_still_counts_its_weight() {
        let mut b = Builder::new(opts());
        let null = b.null().unwrap();
        let big = b
            .string_pattern("(?:.)", None, Some(2048), Charset::Utf8CountedCodepoints)
            .unwrap();
        let nullable_big = b.union_of(vec![null, big]).unwrap();
        let small = b
            .string_pattern("(?:.)", None, Some(100), Charset::Utf8CountedCodepoints)
            .unwrap();
        let obj = b
            .object(
                vec![("a".into(), nullable_big), ("b".into(), small)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir = b.finish(obj).unwrap();
        assert!(
            ir.requires_structured_backend(),
            "type:[X,null] must not hide a field's real weight from the shuffle pre-check"
        );
    }

    #[test]
    fn distinct_node_count_never_exceeds_occurrence_count() {
        let mut b = Builder::new(opts());
        let inner = b.boolean().unwrap();
        let arr = b.array(inner, 0, None).unwrap();
        let ir = b.finish(arr).unwrap();
        assert!(ir.node_count() <= 2);
    }

    #[test]
    fn two_builders_different_insertion_order_hash_equal() {
        let mut b1 = Builder::new(opts());
        let x = b1.boolean().unwrap();
        let y = b1.null().unwrap();
        let o1 = b1
            .object(
                vec![("a".into(), x), ("b".into(), y)],
                &[true, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir1 = b1.finish(o1).unwrap();

        let mut b2 = Builder::new(opts());
        let y = b2.null().unwrap();
        let x = b2.boolean().unwrap();
        let o2 = b2
            .object(
                vec![("a".into(), x), ("b".into(), y)],
                &[true, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir2 = b2.finish(o2).unwrap();

        assert_eq!(ir1.canonical_hash(), ir2.canonical_hash());
    }

    #[test]
    fn different_property_order_changes_the_hash() {
        let mut b1 = Builder::new(opts());
        let (x, y) = (b1.boolean().unwrap(), b1.null().unwrap());
        let o1 = b1
            .object(
                vec![("a".into(), x), ("b".into(), y)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir1 = b1.finish(o1).unwrap();

        let mut b2 = Builder::new(opts());
        let (x, y) = (b2.boolean().unwrap(), b2.null().unwrap());
        let o2 = b2
            .object(
                vec![("b".into(), y), ("a".into(), x)],
                &[false, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir2 = b2.finish(o2).unwrap();

        assert_ne!(ir1.canonical_hash(), ir2.canonical_hash());
    }

    #[test]
    fn enum_order_does_not_change_the_hash() {
        let mut b1 = Builder::new(opts());
        let e1 = b1
            .enum_values(vec![ScalarLit::Int(1), ScalarLit::Int(2)])
            .unwrap();
        let ir1 = b1.finish(e1).unwrap();
        let mut b2 = Builder::new(opts());
        let e2 = b2
            .enum_values(vec![ScalarLit::Int(2), ScalarLit::Int(1)])
            .unwrap();
        let ir2 = b2.finish(e2).unwrap();
        assert_eq!(ir1.canonical_hash(), ir2.canonical_hash());
    }

    #[test]
    fn required_flag_change_changes_the_hash() {
        let mk = |req: &[bool]| {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let o = b
                .object(vec![("a".into(), x)], req, ObjectClosure::Forbidden)
                .unwrap();
            b.finish(o).unwrap().canonical_hash()
        };
        assert_ne!(mk(&[true]), mk(&[false]));
    }

    #[test]
    fn length_prefix_prevents_concatenation_collision() {
        let mut b1 = Builder::new(opts());
        let e1 = b1
            .enum_values(vec![
                ScalarLit::Str("ab".into()),
                ScalarLit::Str("c".into()),
            ])
            .unwrap();
        let ir1 = b1.finish(e1).unwrap();
        let mut b2 = Builder::new(opts());
        let e2 = b2
            .enum_values(vec![
                ScalarLit::Str("a".into()),
                ScalarLit::Str("bc".into()),
            ])
            .unwrap();
        let ir2 = b2.finish(e2).unwrap();
        assert_ne!(ir1.canonical_hash(), ir2.canonical_hash());
    }

    #[test]
    fn enum_rejects_duplicate_value() {
        let mut b = Builder::new(opts());
        let e = b.enum_values(vec![ScalarLit::Int(1), ScalarLit::Int(1)]);
        assert_eq!(e.unwrap_err().code, ErrorCode::Malformed);
    }

    #[test]
    fn object_rejects_duplicate_key() {
        let mut b = Builder::new(opts());
        let x = b.boolean().unwrap();
        let y = b.null().unwrap();
        let e = b.object(
            vec![("a".into(), x), ("a".into(), y)],
            &[false, false],
            ObjectClosure::Forbidden,
        );
        assert_eq!(e.unwrap_err().code, ErrorCode::Malformed);
    }

    #[test]
    fn array_max_below_min_is_rejected_at_finish() {
        let mut b = Builder::new(opts());
        let inner = b.boolean().unwrap();
        let arr = b.array(inner, 3, Some(2)).unwrap();
        assert_eq!(b.finish(arr).unwrap_err().code, ErrorCode::Malformed);
    }

    #[test]
    fn unsupported_records_a_diagnostic_per_occurrence() {
        let mut b = Builder::new(opts());
        let u1 = b
            .unsupported("anyOf", UnsupportedReason::UnionType, "/anyOf")
            .unwrap();
        let u2 = b
            .unsupported("anyOf", UnsupportedReason::UnionType, "/properties/x/anyOf")
            .unwrap();
        assert_eq!(u1, u2, "same keyword+reason interns to one node");
        let ir = b.finish(u1).unwrap();
        assert_eq!(
            ir.diagnostics().len(),
            2,
            "each occurrence keeps its own pointer"
        );
        let pointers: Vec<&str> = ir
            .diagnostics()
            .map(|d| ir.str_at(d.json_pointer).unwrap())
            .collect();
        assert_eq!(pointers, ["/anyOf", "/properties/x/anyOf"]);
    }

    #[test]
    fn diagnostics_are_bounded() {
        let mut options = opts();
        options.max_diagnostics = 2;
        let mut b = Builder::new(options);
        b.unsupported("not", UnsupportedReason::Complement, "/a")
            .unwrap();
        b.unsupported("not", UnsupportedReason::Complement, "/b")
            .unwrap();
        let e = b.unsupported("not", UnsupportedReason::Complement, "/c");
        assert_eq!(e.unwrap_err().code, ErrorCode::TooManyDiagnostics);
    }

    #[test]
    fn default_max_diagnostics_absorbs_a_real_world_scale_schema_without_hard_failing() {
        // The measured jsonschemabench worst case was ~4500 occurrences; the default must clear it.
        let mut b = Builder::new(CompileOptions::default());
        for i in 0..5000u32 {
            b.unsupported("not", UnsupportedReason::Complement, &format!("/{i}"))
                .unwrap();
        }
        let last = b
            .unsupported("not", UnsupportedReason::Complement, "/last")
            .unwrap();
        let ir = b.finish(last).unwrap();
        assert_eq!(ir.diagnostics().len(), 5001);
    }

    #[test]
    fn canonical_hash_ignores_diagnostic_pointer() {
        let mk = |ptr: &str| {
            let mut b = Builder::new(opts());
            let u = b
                .unsupported("not", UnsupportedReason::Complement, ptr)
                .unwrap();
            b.finish(u).unwrap().canonical_hash()
        };
        assert_eq!(mk("/a"), mk("/properties/deeply/nested/b"));
    }

    #[test]
    fn integer_bounds_reject_empty_range_at_finish() {
        let mut b = Builder::new(opts());
        let n = b.integer(Some(5), Some(1)).unwrap();
        assert_eq!(b.finish(n).unwrap_err().code, ErrorCode::Malformed);
    }

    #[test]
    fn object_closure_change_changes_the_hash() {
        let mk = |closure| {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let o = b.object(vec![("a".into(), x)], &[false], closure).unwrap();
            b.finish(o).unwrap().canonical_hash()
        };
        assert_ne!(
            mk(ObjectClosure::Forbidden),
            mk(ObjectClosure::AssumeClosedProfile)
        );
    }

    #[test]
    fn compile_options_are_part_of_the_program4_hash() {
        let mk = |cap| {
            let mut o = opts();
            o.max_diagnostics = cap;
            let mut b = Builder::new(o);
            let n = b.boolean().unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        assert_ne!(mk(8), mk(64));
    }

    #[test]
    fn all_compile_options_change_the_program4_hash() {
        let mk = |f: &dyn Fn(&mut CompileOptions)| {
            let mut o = opts();
            f(&mut o);
            let mut b = Builder::new(o);
            let n = b.boolean().unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        let base = mk(&|_| {});
        assert_ne!(base, mk(&|o| o.max_diagnostics = 8));
        assert_ne!(base, mk(&|o| o.format_assertion = true));
    }

    #[test]
    fn same_content_address_holds_across_build_order() {
        let mut b1 = Builder::new(opts());
        let x = b1.boolean().unwrap();
        let y = b1.null().unwrap();
        let o1 = b1
            .object(
                vec![("a".into(), x), ("b".into(), y)],
                &[true, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir1 = b1.finish(o1).unwrap();

        let mut b2 = Builder::new(opts());
        let y = b2.null().unwrap();
        let x = b2.boolean().unwrap();
        let o2 = b2
            .object(
                vec![("a".into(), x), ("b".into(), y)],
                &[true, false],
                ObjectClosure::Forbidden,
            )
            .unwrap();
        let ir2 = b2.finish(o2).unwrap();

        assert!(ir1.same_content_address(&ir2));
    }

    #[test]
    fn object_field_counts_around_word_boundaries_build_and_read_back() {
        for n in [0usize, 1, 63, 64, 65, 130] {
            let mut b = Builder::new(opts());
            let mut fields = Vec::with_capacity(n);
            let mut required = Vec::with_capacity(n);
            for i in 0..n {
                let child = b.boolean().unwrap();
                fields.push((format!("f{i}"), child));
                required.push(i % 2 == 0);
            }
            let o = b
                .object(fields, &required, ObjectClosure::Forbidden)
                .unwrap();
            let ir = b.finish(o).unwrap();
            let Node::Object { required: bits, .. } = ir.node(o).unwrap() else {
                panic!("object");
            };
            for i in 0..n {
                let idx = u32::try_from(i).unwrap();
                assert_eq!(ir.is_required(*bits, idx), i % 2 == 0, "field {i} of {n}");
            }
        }
    }

    #[test]
    fn integer_and_enum_carry_i64_extremes() {
        let mut b = Builder::new(opts());
        let n = b.integer(Some(i64::MIN), Some(i64::MAX)).unwrap();
        let ir = b.finish(n).unwrap();
        assert_eq!(SchemaIR::from_wire(&ir.to_wire()).unwrap(), ir);

        let mut b = Builder::new(opts());
        let e = b
            .enum_values(vec![ScalarLit::Int(i64::MIN), ScalarLit::Int(i64::MAX)])
            .unwrap();
        let ir = b.finish(e).unwrap();
        assert_eq!(SchemaIR::from_wire(&ir.to_wire()).unwrap(), ir);
    }

    #[test]
    fn literal_string_bytes_at_the_cap_build_and_round_trip() {
        let mut b = Builder::new(opts());
        let big = "a".repeat(MAX_LITERAL_STR_BYTES);
        let e = b.enum_values(vec![ScalarLit::Str(big)]).unwrap();
        let ir = b.finish(e).unwrap();
        assert_eq!(SchemaIR::from_wire(&ir.to_wire()).unwrap(), ir);
    }

    #[test]
    fn a_single_over_cap_literal_string_is_rejected_at_build() {
        let mut b = Builder::new(opts());
        let too_big = "a".repeat(MAX_LITERAL_STR_BYTES + 1);
        let e = b.enum_values(vec![ScalarLit::Str(too_big)]);
        assert_eq!(e.unwrap_err().code, ErrorCode::InternalLimitExceeded);
    }

    #[test]
    fn repeated_large_literals_cannot_bypass_the_aggregate_cap() {
        let half = MAX_LITERAL_STR_BYTES / 2;
        let mut b = Builder::new(opts());
        // Two distinct enums, each just under the cap, together exceed it.
        b.enum_values(vec![ScalarLit::Str("a".repeat(half))])
            .unwrap();
        let second = b.enum_values(vec![ScalarLit::Str("b".repeat(half + 1))]);
        assert_eq!(second.unwrap_err().code, ErrorCode::InternalLimitExceeded);
    }

    #[test]
    fn tuple_node_round_trips_and_rejects_a_closed_min_past_the_prefix() {
        let mut b = Builder::new(opts());
        let x = b.boolean().unwrap();
        let y = b.null().unwrap();
        let node = b.tuple(vec![x, y], Some(x), 1, Some(4)).unwrap();
        let ir = b.finish(node).unwrap();
        assert_eq!(SchemaIR::from_wire(&ir.to_wire()).unwrap(), ir);

        // A closed tuple (no tail) cannot hold more items than its prefix, so minItems past the
        // prefix length is an empty language, rejected at finish.
        let mut b = Builder::new(opts());
        let x = b.boolean().unwrap();
        let node = b.tuple(vec![x], None, 3, None).unwrap();
        assert_eq!(b.finish(node).unwrap_err().code, ErrorCode::Malformed);
    }

    #[test]
    fn empty_tuple_prefix_is_rejected_at_build() {
        let mut b = Builder::new(opts());
        assert_eq!(
            b.tuple(vec![], None, 0, None).unwrap_err().code,
            ErrorCode::Malformed
        );
    }

    #[test]
    fn tuple_and_array_hash_differently_even_with_one_prefix_element() {
        let mk_tuple = || {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let n = b.tuple(vec![x], Some(x), 0, None).unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        let mk_array = || {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let n = b.array(x, 0, None).unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        assert_ne!(mk_tuple(), mk_array());
    }

    #[test]
    fn deeply_nested_and_repeated_subtrees_build_via_arena_iteration() {
        let mut b = Builder::new(opts());
        let mut node = b.boolean().unwrap();
        for _ in 0..5_000 {
            node = b.array(node, 0, None).unwrap();
        }
        let ir = b.finish(node).unwrap();
        assert_eq!(ir.node_count(), 5_001);
        let _ = ir.canonical_hash();
    }

    #[test]
    fn open_object_rejects_duplicate_known_keys() {
        let mut b = Builder::new(opts());
        let x = b.boolean().unwrap();
        let err = b
            .open_object(
                vec![("a".into(), x), ("a".into(), x)],
                &[false, false],
                Vec::new(),
                AdditionalPolicy::Forbid,
                None,
                None,
                None,
            )
            .unwrap_err();
        assert_eq!(err.code, ErrorCode::Malformed);
    }

    #[test]
    fn open_object_rejects_max_properties_below_min_properties() {
        let mut b = Builder::new(opts());
        let err = b
            .open_object(
                Vec::new(),
                &[],
                Vec::new(),
                AdditionalPolicy::AllowAny,
                None,
                Some(5),
                Some(2),
            )
            .unwrap_err();
        assert_eq!(err.code, ErrorCode::Malformed);
    }

    #[test]
    fn open_object_additional_policy_changes_the_hash() {
        let mk = |policy: AdditionalPolicy| {
            let mut b = Builder::new(opts());
            let n = b
                .open_object(Vec::new(), &[], Vec::new(), policy, None, None, None)
                .unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        let forbid = mk(AdditionalPolicy::Forbid);
        let allow_any = mk(AdditionalPolicy::AllowAny);
        assert_ne!(forbid, allow_any);

        let mut b = Builder::new(opts());
        let s = b.boolean().unwrap();
        let schema_hash = {
            let n = b
                .open_object(
                    Vec::new(),
                    &[],
                    Vec::new(),
                    AdditionalPolicy::Schema(s),
                    None,
                    None,
                    None,
                )
                .unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        assert_ne!(schema_hash, forbid);
        assert_ne!(schema_hash, allow_any);
    }

    #[test]
    fn open_object_and_closed_object_hash_differently_for_the_same_fields() {
        let mk_open = || {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let n = b
                .open_object(
                    vec![("a".into(), x)],
                    &[true],
                    Vec::new(),
                    AdditionalPolicy::Forbid,
                    None,
                    None,
                    None,
                )
                .unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        let mk_closed = || {
            let mut b = Builder::new(opts());
            let x = b.boolean().unwrap();
            let n = b
                .object(vec![("a".into(), x)], &[true], ObjectClosure::Forbidden)
                .unwrap();
            b.finish(n).unwrap().canonical_hash()
        };
        assert_ne!(mk_open(), mk_closed());
    }

    #[test]
    fn open_object_pattern_and_property_names_round_trip_through_wire() {
        let mut b = Builder::new(opts());
        let known_val = b.boolean().unwrap();
        let pattern_val = b.integer(None, None).unwrap();
        let names_schema = b
            .string_pattern("[a-z]+", None, None, Charset::Utf8Any)
            .unwrap();
        let n = b
            .open_object(
                vec![("a".into(), known_val)],
                &[true],
                vec![("^x_".into(), pattern_val)],
                AdditionalPolicy::AllowAny,
                Some(names_schema),
                Some(1),
                Some(10),
            )
            .unwrap();
        let ir = b.finish(n).unwrap();
        let bytes = ir.to_wire();
        let decoded = SchemaIR::from_wire(&bytes).unwrap();
        assert_eq!(ir.canonical_hash(), decoded.canonical_hash());
        let Node::OpenObject {
            min_properties,
            max_properties,
            property_names,
            ..
        } = decoded.node(decoded.root()).unwrap()
        else {
            panic!("expected OpenObject");
        };
        assert_eq!(*min_properties, Some(1));
        assert_eq!(*max_properties, Some(10));
        assert!(property_names.is_some());
    }

    #[test]
    fn dependent_required_canonical_hash_is_unordered_and_wire_stable() {
        let options = CompileOptions::default();
        let first = crate::frontend::schema_to_ir(
            r#"{"dependentRequired":{"a":["b","c"],"x":["y"]}}"#,
            options.clone(),
        )
        .unwrap();
        let second = crate::frontend::schema_to_ir(
            r#"{"dependentRequired":{"x":["y"],"a":["c","b"]}}"#,
            options,
        )
        .unwrap();
        assert_eq!(IR_VERSION, 6);
        assert_eq!(first.canonical_hash(), second.canonical_hash());
        let encoded = first.to_wire();
        let decoded = SchemaIR::from_wire(&encoded).unwrap();
        assert_eq!(decoded, first);
        assert_eq!(decoded.canonical_hash(), first.canonical_hash());
        let mut v2 = encoded;
        v2[6..8].copy_from_slice(&2u16.to_le_bytes());
        assert_eq!(
            SchemaIR::from_wire(&v2).unwrap_err().code,
            ErrorCode::Malformed
        );
    }

    #[test]
    fn decimal_comparison_is_exact_at_coefficient_and_scale_limits() {
        use std::cmp::Ordering;

        assert_eq!(decimal_cmp((1, u32::MAX), (2, u32::MAX)), Ordering::Less);
        assert_eq!(
            decimal_cmp((-1, u32::MAX), (-2, u32::MAX)),
            Ordering::Greater
        );
        assert_eq!(decimal_cmp((10, 2), (1, 1)), Ordering::Equal);
        assert_eq!(decimal_cmp((i128::MAX, 38), (1, 0)), Ordering::Greater);
        assert_eq!(decimal_cmp((i128::MIN, 38), (-1, 0)), Ordering::Less);
    }

    #[test]
    fn forged_dependent_required_arena_is_rejected_without_panicking() {
        let valid = crate::frontend::schema_to_ir(
            r#"{"type":"object","additionalProperties":true,"dependentRequired":{"a":["b"]}}"#,
            CompileOptions::default(),
        )
        .unwrap();
        let root = valid.root().get() as usize;
        let mut bad_slice = valid.to_wire_struct();
        match &mut bad_slice.nodes[root] {
            Node::OpenObject {
                dependent_required, ..
            }
            | Node::Object {
                dependent_required, ..
            } => dependent_required.off = u32::MAX,
            _ => panic!("expected object branch"),
        }
        assert_eq!(
            SchemaIR::assemble(bad_slice).unwrap_err().code,
            ErrorCode::Malformed
        );

        for (off, len) in [(0, u32::MAX), (u32::MAX, u32::MAX)] {
            let mut bad_range = valid.to_wire_struct();
            match &mut bad_range.nodes[root] {
                Node::OpenObject {
                    dependent_required, ..
                }
                | Node::Object {
                    dependent_required, ..
                } => {
                    dependent_required.off = off;
                    dependent_required.len = len;
                }
                _ => unreachable!(),
            }
            assert_eq!(
                SchemaIR::assemble(bad_range).unwrap_err().code,
                ErrorCode::Malformed
            );
        }

        for trigger in [true, false] {
            let mut bad_name = valid.to_wire_struct();
            let bad = StrRef {
                off: u32::MAX,
                len: 1,
            };
            if trigger {
                bad_name.dependent_required_pairs[0].trigger = bad;
            } else {
                bad_name.dependent_required_pairs[0].required = bad;
            }
            assert_eq!(
                SchemaIR::assemble(bad_name).unwrap_err().code,
                ErrorCode::Malformed
            );
        }

        let mut duplicate = valid.to_wire_struct();
        duplicate
            .dependent_required_pairs
            .push(duplicate.dependent_required_pairs[0]);
        match &mut duplicate.nodes[root] {
            Node::OpenObject {
                dependent_required, ..
            }
            | Node::Object {
                dependent_required, ..
            } => dependent_required.len = 2,
            _ => unreachable!(),
        }
        assert_eq!(
            SchemaIR::assemble(duplicate).unwrap_err().code,
            ErrorCode::Malformed
        );

        let mut over_cap = valid.to_wire_struct();
        over_cap.dependent_required_pairs =
            vec![over_cap.dependent_required_pairs[0]; MAX_DEPENDENT_REQUIRED_PAIRS + 1];
        assert_eq!(
            SchemaIR::assemble(over_cap).unwrap_err().code,
            ErrorCode::Malformed
        );
    }
}