decl-lang 0.4.7

Decl — a declarative language for describing, generating, and validating structured data: the `decl` CLI (check / evaluate / validate / fmt) and the `decl-lsp` language server, implemented natively in Rust
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
//! Value model, environment, and type resolution — a port of the
//! reference implementation's semantics.ts.
use crate::ast::*;
use indexmap::IndexMap;
use num_bigint::{BigInt, Sign};
use num_traits::{FromPrimitive, Signed, ToPrimitive};
use regex::Regex;
use rustc_hash::{FxBuildHasher, FxHashMap};
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::rc::Rc;
use std::sync::LazyLock;

pub(crate) mod lifetime;
pub use lifetime::collect_cycles;

mod shared_text;
pub use shared_text::SharedText;

mod map_entries;
pub(crate) use map_entries::{KeysSeen, MapShapePool};
pub use map_entries::{
    MapEntries, MapEntriesIntoIter, MapEntriesIter, MapEntriesIterMut, MapEntriesKeys,
    MapEntriesValues, MapEntriesValuesMut,
};

mod prefix_path;
#[cfg(feature = "runtime-diagnostics")]
pub use lifetime::{take_gc_diagnostics, GcDiagnostics, GcTrigger};
pub use prefix_path::{
    prefix_path_diagnostics, prefix_path_layouts, PrefixPath, PrefixPathDiagnostics,
    PrefixPathIter, PrefixPathLayouts, PrefixPathPool, PrefixPathPoolStats,
};

/// an integer value (§4.5): a machine word when it fits, arbitrary precision
/// otherwise. The reference and Python hold every integer as a big integer;
/// here the common small values avoid a heap allocation and a deep copy on
/// clone, which dominate at scale (F21). Always normalized — a `Big` never
/// holds a value that fits in `i64` — so equality and ordering are the
/// machine-word comparison whenever both operands are small, and a `Small`
/// never equals a `Big`.
#[derive(Clone, Debug)]
pub enum Num {
    /// fits a machine word
    Small(i64),
    /// out of `i64` range
    Big(Rc<BigInt>),
}
impl Num {
    /// zero.
    pub fn zero() -> Num {
        Num::Small(0)
    }
    /// a big integer, demoted to `Small` when it fits a word.
    pub fn from_big(b: BigInt) -> Num {
        match b.to_i64() {
            Some(n) => Num::Small(n),
            None => Num::Big(Rc::new(b)),
        }
    }
    /// its value as a big integer.
    pub fn to_big(&self) -> BigInt {
        match self {
            Num::Small(n) => BigInt::from(*n),
            Num::Big(b) => (**b).clone(),
        }
    }
    /// its value as `f64` (§4.5), `None` only for a non-finite big integer.
    pub fn to_f64(&self) -> Option<f64> {
        match self {
            Num::Small(n) => Some(*n as f64),
            Num::Big(b) => b.to_f64(),
        }
    }
    /// its value as `i64` when it fits.
    pub fn to_i64(&self) -> Option<i64> {
        match self {
            Num::Small(n) => Some(*n),
            Num::Big(b) => b.to_i64(),
        }
    }
    /// its value as `usize` when it fits and is non-negative.
    pub fn to_usize(&self) -> Option<usize> {
        match self {
            Num::Small(n) => usize::try_from(*n).ok(),
            Num::Big(b) => b.to_usize(),
        }
    }
    /// whether it is zero.
    pub fn is_zero(&self) -> bool {
        matches!(self, Num::Small(0))
    }
    /// whether it is negative.
    pub fn is_negative(&self) -> bool {
        match self {
            Num::Small(n) => *n < 0,
            Num::Big(b) => b.sign() == Sign::Minus,
        }
    }
    /// its absolute value.
    pub fn abs(&self) -> Num {
        match self {
            Num::Small(n) => n
                .checked_abs()
                .map(Num::Small)
                .unwrap_or_else(|| Num::from_big(BigInt::from(*n).abs())),
            Num::Big(b) => Num::from_big(b.abs()),
        }
    }
    /// the number of bits in its absolute value (as `BigInt::bits`).
    pub fn bits(&self) -> u64 {
        match self {
            Num::Small(n) => BigInt::from(*n).bits(),
            Num::Big(b) => b.bits(),
        }
    }
    /// a float rounded toward zero to an integer, `None` if non-finite.
    pub fn from_f64(x: f64) -> Option<Num> {
        BigInt::from_f64(x).map(Num::from_big)
    }
    /// parse a decimal (or signed) integer literal.
    pub fn parse_str(s: &str) -> Option<Num> {
        s.parse::<BigInt>().ok().map(Num::from_big)
    }
}
impl From<i64> for Num {
    fn from(n: i64) -> Num {
        Num::Small(n)
    }
}
impl From<i32> for Num {
    fn from(n: i32) -> Num {
        Num::Small(n as i64)
    }
}
impl From<u32> for Num {
    fn from(n: u32) -> Num {
        Num::Small(n as i64)
    }
}
impl From<usize> for Num {
    fn from(n: usize) -> Num {
        i64::try_from(n)
            .map(Num::Small)
            .unwrap_or_else(|_| Num::from_big(BigInt::from(n)))
    }
}
impl From<u64> for Num {
    fn from(n: u64) -> Num {
        i64::try_from(n)
            .map(Num::Small)
            .unwrap_or_else(|_| Num::from_big(BigInt::from(n)))
    }
}
impl From<BigInt> for Num {
    fn from(b: BigInt) -> Num {
        Num::from_big(b)
    }
}
impl fmt::Display for Num {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Num::Small(n) => write!(f, "{n}"),
            Num::Big(b) => write!(f, "{b}"),
        }
    }
}
impl PartialEq for Num {
    fn eq(&self, o: &Num) -> bool {
        match (self, o) {
            (Num::Small(a), Num::Small(b)) => a == b,
            (Num::Big(a), Num::Big(b)) => a == b,
            _ => false, // normalized: a Small and a Big are never equal
        }
    }
}
impl Eq for Num {}
impl Ord for Num {
    fn cmp(&self, o: &Num) -> std::cmp::Ordering {
        match (self, o) {
            (Num::Small(a), Num::Small(b)) => a.cmp(b),
            _ => self.to_big().cmp(&o.to_big()),
        }
    }
}
impl PartialOrd for Num {
    fn partial_cmp(&self, o: &Num) -> Option<std::cmp::Ordering> {
        Some(self.cmp(o))
    }
}
impl std::ops::Neg for &Num {
    type Output = Num;
    fn neg(self) -> Num {
        match self {
            Num::Small(n) => n
                .checked_neg()
                .map(Num::Small)
                .unwrap_or_else(|| Num::from_big(-BigInt::from(*n))),
            Num::Big(b) => Num::from_big(-&**b),
        }
    }
}
macro_rules! num_binop {
    ($tr:ident, $m:ident, $checked:ident, $op:tt) => {
        impl std::ops::$tr for &Num {
            type Output = Num;
            fn $m(self, rhs: &Num) -> Num {
                if let (Num::Small(a), Num::Small(b)) = (self, rhs) {
                    if let Some(r) = a.$checked(*b) {
                        return Num::Small(r);
                    }
                }
                Num::from_big(self.to_big() $op rhs.to_big())
            }
        }
    };
}
num_binop!(Add, add, checked_add, +);
num_binop!(Sub, sub, checked_sub, -);
num_binop!(Mul, mul, checked_mul, *);
num_binop!(Div, div, checked_div, /);
num_binop!(Rem, rem, checked_rem, %);
macro_rules! num_bitop {
    ($tr:ident, $m:ident, $op:tt) => {
        impl std::ops::$tr for &Num {
            type Output = Num;
            fn $m(self, rhs: &Num) -> Num {
                if let (Num::Small(a), Num::Small(b)) = (self, rhs) {
                    return Num::Small(a $op b);
                }
                Num::from_big(self.to_big() $op rhs.to_big())
            }
        }
    };
}
num_bitop!(BitAnd, bitand, &);
num_bitop!(BitOr, bitor, |);
num_bitop!(BitXor, bitxor, ^);
impl std::ops::Shl<usize> for &Num {
    type Output = Num;
    fn shl(self, n: usize) -> Num {
        Num::from_big(self.to_big() << n)
    }
}
impl std::ops::Shr<usize> for &Num {
    type Output = Num;
    fn shr(self, n: usize) -> Num {
        Num::from_big(self.to_big() >> n)
    }
}
impl std::ops::Neg for Num {
    type Output = Num;
    fn neg(self) -> Num {
        -&self
    }
}
// small-literal arithmetic on the counters and bounds a range walk uses
impl std::ops::Add<i64> for &Num {
    type Output = Num;
    fn add(self, n: i64) -> Num {
        self + &Num::Small(n)
    }
}
impl std::ops::Sub<i64> for &Num {
    type Output = Num;
    fn sub(self, n: i64) -> Num {
        self - &Num::Small(n)
    }
}
impl std::ops::AddAssign<i64> for Num {
    fn add_assign(&mut self, n: i64) {
        *self = &*self + n;
    }
}

// the pattern-interpolation grammar (§3.6): compiled once
static PATTERN_HOLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$\{([^}]*)\}").unwrap());
static PATTERN_STR_LIT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"^"((?:[^"\\]|\\.)*)"$"#).unwrap());
static PATTERN_INT_RANGE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(-?[0-9]+)\.\.(<?)(-?[0-9]+)$").unwrap());
static PATTERN_INT_LIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^-?[0-9]+$").unwrap());
static PATTERN_IDENT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_.]*$").unwrap());

// ---------------- paths ----------------
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
/// a segment of a canonical path (§7.2)
pub enum Seg {
    /// a record member by name: dotted when the dot can spell it (§7.2)
    Name(Rc<str>),
    /// an array index
    Idx(usize),
    /// a map key: always bracketed (§7.2)
    Key(Rc<str>),
}
/// a canonical path
pub type SegPath = Vec<Seg>;
/// A segment's text as the path spells it.
pub fn seg_text(s: &Seg) -> String {
    match s {
        Seg::Name(n) | Seg::Key(n) => n.to_string(),
        Seg::Idx(i) => i.to_string(),
    }
}
/// dot-spellable (§3.11, §4.3): identifier-shaped and not a literal keyword
pub fn dot_spellable(name: &str) -> bool {
    let mut cs = name.chars();
    let head = matches!(cs.next(), Some(c) if c == '_' || c.is_ascii_alphabetic());
    head && cs.all(|c| c == '_' || c.is_ascii_alphanumeric())
        && !matches!(name, "true" | "false" | "null")
}

// ---------------- values ----------------
#[derive(Clone)]
/// a runtime value (§9): the scalars, quantities, references, and instances,
/// and the engine's intermediate forms
pub enum Value {
    /// an integer
    Int(Num),
    /// a float
    Float(f64),
    /// a string
    Str(SharedText),
    /// a boolean
    Bool(bool),
    /// null
    Null,
    /// an absent optional member (§4.6)
    Absent,
    /// not yet computed
    Undef,
    /// a quantity
    Q(Box<QuantityValue>),
    /// a reference, by canonical path
    Ref(Rc<SegPath>),
    /// a record instance
    Rec(Rc<RefCell<RecInst>>),
    /// an array
    Arr(Rc<RefCell<ArrV>>),
    /// a map
    Map(Rc<RefCell<MapV>>),
    /// a range value
    Range(Box<RangeValue>),
    /// a closure
    Clo(Rc<Closure>),
    /// a native function
    Nat(NatFn),
    /// a standard-library path, partially spelled
    Std(Rc<Vec<String>>),
    /// a namespace
    NsRef(Rc<NsRefV>),
    /// a pattern
    Pat(SharedText),
    /// a record literal not yet bound
    PreObj(Rc<Vec<(String, Value)>>),
    /// an array literal not yet bound: (spread, item)
    PreArr(Rc<Vec<(bool, Value)>>),
    /// an expression not yet evaluated, with its scope
    PreVal(Rc<PreValV>),
    /// a JSON object, as read
    JObj(Rc<Vec<(String, Value)>>),
    /// a JSON array, as read
    JArr(Rc<Vec<Value>>),
    /// a path value
    Segs(Rc<SegPath>),
}

/// A uniquely owned quantity magnitude and its shared dimension key.
/// Cloning preserves independent magnitude mutation and dimension copy-on-write.
#[derive(Clone)]
pub struct QuantityValue {
    /// The shared dimension key; use quantity_dimension_mut for copy-on-write.
    pub dim: Rc<String>,
    /// The magnitude in the base unit.
    pub value: f64,
}

/// Uniquely owned range endpoints. Cloning a range clones its endpoint Values;
/// sharing the payload would change native mutation and collector edge counts.
#[derive(Clone)]
pub struct RangeValue {
    /// The lower bound.
    pub lo: Value,
    /// The upper bound.
    pub hi: Value,
    /// Whether the upper bound is excluded.
    pub excl: bool,
}

impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Int(i) => write!(f, "{i}"),
            Value::Float(x) => write!(f, "{x}"),
            Value::Str(s) => write!(f, "{s:?}"),
            Value::Bool(b) => write!(f, "{b}"),
            Value::Null => write!(f, "null"),
            Value::Absent => write!(f, "ABSENT"),
            Value::Undef => write!(f, "UNDEF"),
            Value::Q(q) => write!(f, "{}<{}>", q.value, q.dim),
            other => write!(f, "<{}>", other.tag()),
        }
    }
}

impl Value {
    /// Construct a quantity with a base-unit magnitude and a dimension key.
    /// Display units remain properties of the environment, not this value.
    pub fn quantity(dim: impl Into<String>, value: f64) -> Self {
        Self::Q(Box::new(QuantityValue {
            dim: Rc::new(dim.into()),
            value,
        }))
    }
    /// Borrow the dimension and read the independently stored magnitude.
    pub fn as_quantity(&self) -> Option<(&str, f64)> {
        match self {
            Self::Q(q) => Some((q.dim.as_str(), q.value)),
            _ => None,
        }
    }
    /// Mutate a dimension without changing a retained clone's dimension.
    pub fn quantity_dimension_mut(&mut self) -> Option<&mut String> {
        match self {
            Self::Q(q) => Some(Rc::make_mut(&mut q.dim)),
            _ => None,
        }
    }
    /// Mutate this quantity's independently owned magnitude or dimension owner.
    pub fn as_quantity_mut(&mut self) -> Option<&mut QuantityValue> {
        match self {
            Self::Q(q) => Some(q),
            _ => None,
        }
    }
    /// Construct a range without evaluating or restricting its endpoints.
    /// Iteration and membership retain their existing validation boundaries.
    pub fn range(lo: Value, hi: Value, excl: bool) -> Self {
        Self::Range(Box::new(RangeValue { lo, hi, excl }))
    }
    /// Borrow a range's uniquely owned endpoints and exclusion flag.
    pub fn as_range(&self) -> Option<&RangeValue> {
        match self {
            Self::Range(range) => Some(range),
            _ => None,
        }
    }
    /// Mutate this range's endpoints; ordinary Value clone rules still apply
    /// to containers or native captures stored inside those endpoints.
    pub fn as_range_mut(&mut self) -> Option<&mut RangeValue> {
        match self {
            Self::Range(range) => Some(range),
            _ => None,
        }
    }
    /// Construct pattern text. Pattern equality remains non-reflexive.
    pub fn pattern(src: impl Into<Rc<str>>) -> Self {
        Self::Pat(SharedText::from_rc(src.into()))
    }
    /// Borrow pattern text without exposing its shared storage.
    pub fn as_pattern(&self) -> Option<&str> {
        match self {
            Self::Pat(src) => Some(src),
            _ => None,
        }
    }
    /// Share one native callable and its captures across Value clones.
    pub fn native<F>(f: F) -> Self
    where
        F: Fn(&[Value]) -> R<Value> + 'static,
    {
        Self::Nat(Rc::new(Box::new(f)))
    }
    /// The value's kind, as a word.
    pub fn tag(&self) -> &'static str {
        match self {
            Value::Int(_) => "int",
            Value::Float(_) => "float",
            Value::Str(_) => "string",
            Value::Bool(_) => "bool",
            Value::Null => "null",
            Value::Absent => "absent",
            Value::Undef => "undef",
            Value::Q(_) => "quantity",
            Value::Ref(_) => "ref",
            Value::Rec(_) => "record",
            Value::Arr(_) => "array",
            Value::Map(_) => "map",
            Value::Range(_) => "range",
            Value::Clo(_) => "closure",
            Value::Nat(_) => "native",
            Value::Std(_) => "std",
            Value::NsRef(_) => "namespace",
            Value::Pat(_) => "pattern",
            Value::PreObj(_) => "pre-obj",
            Value::PreArr(_) => "pre-arr",
            Value::PreVal(_) => "pre-val",
            Value::JObj(_) => "json-obj",
            Value::JArr(_) => "json-arr",
            Value::Segs(_) => "segs",
        }
    }
    /// Whether the value is not yet computed.
    pub fn is_undef(&self) -> bool {
        matches!(self, Value::Undef)
    }
    /// Whether the value is absent.
    pub fn is_absent(&self) -> bool {
        matches!(self, Value::Absent)
    }
    /// The canonical path the value sits at or refers to, when it has one.
    pub fn place(&self) -> Option<SegPath> {
        match self {
            Value::Ref(p) => Some((**p).clone()),
            Value::Rec(r) => Some(r.borrow().path.to_vec()),
            Value::Arr(a) => Some(a.borrow().path.to_vec()),
            Value::Map(m) => Some(m.borrow().path.to_vec()),
            _ => None,
        }
    }
}

/// a native function
pub type NatFn = Rc<Box<dyn Fn(&[Value]) -> R<Value>>>;

/// a function value: its parameters, its body, the scope it closed over
pub struct Closure {
    /// the parameters
    pub params: Vec<String>,
    /// the body
    pub body: Rc<Expr>,
    /// the scope
    pub scope: Scope,
}
/// a namespace's exports
pub struct NsRefV {
    /// the exports, by name
    pub exports: Rc<RefCell<HashMap<String, Export>>>,
}
/// an expression waiting to be evaluated in its scope
pub struct PreValV {
    /// the expression
    pub expr: Rc<Expr>,
    /// the scope
    pub scope: Scope,
}
/// an array value
pub struct ArrV {
    /// the items
    pub items: Vec<Value>,
    /// its canonical path
    pub path: PrefixPath,
}
/// An insertion-ordered table with indexed lookup. Iteration retains language
/// order while reference navigation and member access avoid linear scans.
pub type OrderedMap<T> = IndexMap<String, T, FxBuildHasher>;

/// a map value
pub struct MapV {
    /// the entries, in order
    pub entries: MapEntries,
    /// its canonical path
    pub path: PrefixPath,
}
impl MapV {
    /// The value at a key.
    pub fn get(&self, k: &str) -> Option<&Value> {
        self.entries.get(k)
    }
    /// Whether the key is present.
    pub fn has(&self, k: &str) -> bool {
        self.entries.contains_key(k)
    }
    /// Set a key's value.
    pub fn set(&mut self, k: String, v: Value) {
        self.entries.insert(k, v);
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
/// a member's kind (§5)
pub enum MKind {
    /// required
    Req,
    /// optional
    Opt,
    /// defaulted
    Dflt,
    /// derived
    Der,
}
#[derive(Clone, Copy, PartialEq, Debug)]
/// the state of a slot
pub enum SlotState {
    /// not forced yet
    Unforced,
    /// the computation reached `$referrers` before the universe was complete: not attempted again
    /// until phase 2 (a demand meanwhile defers at once)
    Deferred,
    /// being forced
    Forcing,
    /// forced, with a value
    Ok,
    /// an error invalidated it
    Invalid,
    /// absent
    Absent,
}

#[derive(Clone)]
/// how a slot computes its value
pub enum Compute {
    /// a supplied value checked against the types
    Check {
        /// the value supplied
        raw: Value,
        /// the types to check against
        types: Rc<Vec<RT>>,
        /// the member
        name: Rc<str>,
        /// the root
        root_name: Rc<str>,
        /// the module environment
        menv: Option<Rc<Env>>,
    },
    /// a default expression
    Default {
        /// the expression
        expr: Rc<Expr>,
        /// the shared executable program, when queries are enabled
        op: Option<crate::qengine::programs::Op>,
        /// the types to check against
        types: Rc<Vec<RT>>,
        /// the member
        name: Rc<str>,
        /// the root
        root_name: Rc<str>,
        /// the module environment
        menv: Option<Rc<Env>>,
    },
    /// a derived expression
    Derived {
        /// the expression
        expr: Rc<Expr>,
        /// the shared executable program, when queries are enabled
        op: Option<crate::qengine::programs::Op>,
        /// the declared type
        ty: Option<RT>,
        /// the value the document supplied, to compare (§10.5)
        supplied: Option<Value>,
        /// the member
        name: Rc<str>,
        /// the root
        root_name: Rc<str>,
        /// the module environment
        menv: Option<Rc<Env>>,
    },
    /// a query-engine slot: forcing it runs the given thunk, which reads the
    /// value through the incremental database (qengine). Lets the value layer
    /// force a query-graph slot uniformly (§7.5 navigation, §6 asserts).
    Bridge(Rc<dyn Fn() -> R<Value>>),
}

/// a member's slot in an instance
pub struct Slot {
    /// the member's kind
    pub kind: MKind,
    /// `x$ = e`: computed, never part of the value (D34)
    pub hidden: bool,
    /// its state
    pub state: SlotState,
    /// its value, once forced
    pub value: Value,
    /// Binding-time computation metadata. Shared snapshots are immutable;
    /// use `computation_mut` for an isolated copy-on-write mutation.
    pub compute: Option<Rc<Compute>>,
}

impl Slot {
    /// Inspect the descriptor captured when this slot was bound.
    pub fn computation(&self) -> Option<&Compute> {
        self.compute.as_deref()
    }

    /// Retain an immutable descriptor snapshot, including its captured owners.
    pub fn computation_snapshot(&self) -> Option<Rc<Compute>> {
        self.compute.clone()
    }

    /// Mutate this slot's descriptor without changing an outstanding snapshot.
    /// As with direct field replacement, this does not reset the slot state or
    /// invalidate retained queries; the caller still owns that policy.
    pub fn computation_mut(&mut self) -> Option<&mut Compute> {
        self.compute.as_mut().map(Rc::make_mut)
    }

    /// Replace or remove captured metadata. This does not change state/value.
    pub fn set_computation(&mut self, compute: Option<Compute>) {
        self.compute = compute.map(Rc::new);
    }
}

/// a record instance: its type, its path, its slots
pub struct RecInst {
    /// the type's name, when named
    pub type_name: Option<String>,
    /// the type
    pub rt: RT,
    /// its canonical path
    pub path: Rc<SegPath>,
    /// cached path_str(path) for the slot key (F21); path is immutable
    pub ps: RefCell<Option<String>>,
    /// the enclosing instance
    pub parent: Option<Rc<RefCell<RecInst>>>,
    // declaration order matters (forcing order drives diagnostic order)
    /// the slots, in declaration order
    pub slots: Vec<(Rc<str>, Slot)>,
    /// the order the document supplied the members
    pub entry_order: Rc<Vec<String>>,
    /// members of an open record beyond its type
    pub extras: Vec<(String, Value)>,
    /// the module environment
    pub menv: Option<Rc<Env>>,
}

/// Allocate an instance and track its lifetime without retaining it.
pub(crate) fn record_instance(record: RecInst) -> Rc<RefCell<RecInst>> {
    let record = Rc::new(RefCell::new(record));
    lifetime::track_record(&record);
    record
}
impl RecInst {
    /// Borrow the member order captured from the input document.
    pub fn entry_order(&self) -> &[String] {
        &self.entry_order
    }
    /// Retain the current order independently of later record mutation.
    pub fn entry_order_snapshot(&self) -> Rc<Vec<String>> {
        self.entry_order.clone()
    }
    /// Edit this record's order without changing other records or snapshots.
    pub fn entry_order_mut(&mut self) -> &mut Vec<String> {
        Rc::make_mut(&mut self.entry_order)
    }
    /// An extra member's value.
    pub fn extra(&self, n: &str) -> Option<&Value> {
        self.extras.iter().find(|(k, _)| k == n).map(|(_, v)| v)
    }
    /// Set an extra member.
    pub fn set_extra(&mut self, n: &str, v: Value) {
        if let Some(e) = self.extras.iter_mut().find(|(k, _)| k == n) {
            e.1 = v;
        } else {
            self.extras.push((n.to_string(), v));
        }
    }
    /// A slot by name.
    pub fn slot(&self, n: &str) -> Option<&Slot> {
        self.slots
            .iter()
            .find(|(k, _)| k.as_ref() == n)
            .map(|(_, s)| s)
    }
    /// A slot by name, mutably.
    pub fn slot_mut(&mut self, n: &str) -> Option<&mut Slot> {
        self.slots
            .iter_mut()
            .find(|(k, _)| k.as_ref() == n)
            .map(|(_, s)| s)
    }
    /// Whether the slot exists.
    pub fn has_slot(&self, n: &str) -> bool {
        self.slots.iter().any(|(k, _)| k.as_ref() == n)
    }
}

/// the local variables of a scope: a persistent chain of (name, value)
/// frames (F21 perf: extending a scope with one binding — the hot path in a
/// comprehension iterated over thousands of items — allocates one small frame
/// instead of cloning a whole map; the depth is a handful of loop/parameter
/// names, so a linear lookup is cheap). This is a Rust-only representation; the
/// reference keeps a map (see AGENTS.md, the performance layer).
#[derive(Clone, Default)]
pub struct Locals(Option<Rc<LocalFrame>>);
/// one binding in a `Locals` chain
pub struct LocalFrame {
    name: Rc<str>,
    value: Value,
    next: Option<Rc<LocalFrame>>,
}
impl Locals {
    /// Visible bindings, for comparing captured scopes between Session edits.
    pub(crate) fn entries(&self) -> FxHashMap<Rc<str>, Value> {
        let mut out = FxHashMap::default();
        let mut current = &self.0;
        while let Some(frame) = current {
            out.entry(frame.name.clone())
                .or_insert_with(|| frame.value.clone());
            current = &frame.next;
        }
        out
    }
    /// The empty scope.
    pub fn new() -> Locals {
        Locals(None)
    }
    /// The scope with one more binding, shadowing any earlier one of the name.
    pub fn with(&self, name: Rc<str>, value: Value) -> Locals {
        #[cfg(feature = "runtime-diagnostics")]
        crate::retention_diagnostics::local_frame();
        Locals(Some(Rc::new(LocalFrame {
            name,
            value,
            next: self.0.clone(),
        })))
    }
    /// The value bound to a name, innermost first.
    pub fn get(&self, name: &str) -> Option<&Value> {
        let mut cur = &self.0;
        while let Some(f) = cur {
            if &*f.name == name {
                return Some(&f.value);
            }
            cur = &f.next;
        }
        None
    }
    /// Build a scope from a map's entries (used off the hot path, e.g. rendering).
    pub fn from_map(m: &FxHashMap<String, Value>) -> Locals {
        let mut l = Locals::new();
        for (k, v) in m {
            l = l.with(Rc::from(k.as_str()), v.clone());
        }
        l
    }
}

#[derive(Clone)]
/// an evaluation scope: the enclosing instance, the local variables, the root, the module environment
pub struct Scope {
    /// the enclosing instance
    pub inst: Option<Rc<RefCell<RecInst>>>,
    /// the local variables
    pub locals: Locals,
    /// the root
    pub root_name: Rc<str>,
    /// the module environment
    pub menv: Option<Rc<Env>>,
}
impl Scope {
    /// A scope at a root.
    pub fn new(root_name: &str, menv: Option<Rc<Env>>) -> Scope {
        Scope {
            inst: None,
            locals: Locals::new(),
            root_name: Rc::from(root_name),
            menv,
        }
    }
    /// The scope with local variables.
    pub fn with_locals(&self, locals: Locals) -> Scope {
        Scope {
            inst: self.inst.clone(),
            locals,
            root_name: self.root_name.clone(),
            menv: self.menv.clone(),
        }
    }
    /// The scope inside an instance.
    pub fn with_inst(&self, inst: Option<Rc<RefCell<RecInst>>>) -> Scope {
        Scope {
            inst,
            locals: self.locals.clone(),
            root_name: self.root_name.clone(),
            menv: self.menv.clone(),
        }
    }
    /// The scope in a module environment.
    pub fn with_menv(&self, menv: Option<Rc<Env>>) -> Scope {
        Scope {
            inst: self.inst.clone(),
            locals: self.locals.clone(),
            root_name: self.root_name.clone(),
            menv,
        }
    }
}

// ---------------- failures & diagnostics ----------------
/// an evaluation error, with its code when it has one
pub struct EvalErr {
    /// the message
    pub msg: String,
    /// the code
    pub code: Option<String>,
}
/// why an evaluation stopped
pub enum Fail {
    /// it read an invalid value
    Taint,
    /// it must wait for phase 2
    Defer,
    /// an error
    Eval(EvalErr),
}
/// an evaluation's outcome
pub type R<T> = Result<T, Fail>;
/// An evaluation error without a code.
pub fn err<T>(msg: impl Into<String>) -> R<T> {
    Err(Fail::Eval(EvalErr {
        msg: msg.into(),
        code: None,
    }))
}
/// An evaluation error with a code.
pub fn err_code<T>(msg: impl Into<String>, code: &str) -> R<T> {
    Err(Fail::Eval(EvalErr {
        msg: msg.into(),
        code: Some(code.to_string()),
    }))
}

#[derive(Clone, Debug)]
/// a diagnostic (§6, §12)
pub struct Diag {
    /// `error`, `warn`, or `info`
    pub severity: String,
    /// the constraint's stable id, for an assertion
    pub id: Option<String>,
    /// the message, rendered
    pub message: String,
    /// the canonical path
    pub path: String,
    /// the code (§12)
    pub code: Option<String>,
    /// the source range the checker reported at (the declaration, or the expression under inference)
    pub loc: Option<Loc>,
    /// the evaluation step that produced it (a slot, a root, an assert): dependency tracking's tag
    pub by: Option<String>,
}
impl Diag {
    /// An error diagnostic at a path.
    pub fn error(message: impl Into<String>, path: String, code: Option<&str>) -> Diag {
        Diag {
            severity: "error".into(),
            id: None,
            message: message.into(),
            path,
            code: code.map(|c| c.to_string()),
            loc: None,
            by: None,
        }
    }
    /// The diagnostic as a JSON object in the report's field order (§12.2), with the file when given.
    pub fn to_json(&self, file: Option<&str>) -> String {
        let mut parts = Vec::new();
        // the report's field order (§12.2): file, code, id, severity,
        // message, path — absent fields omitted (byte-identical across
        // implementations)
        if let Some(f) = file {
            parts.push(format!("\"file\":{}", json_str(f)));
        }
        if let Some(c) = &self.code {
            parts.push(format!("\"code\":{}", json_str(c)));
        }
        if let Some(id) = &self.id {
            parts.push(format!("\"id\":{}", json_str(id)));
        }
        parts.push(format!("\"severity\":{}", json_str(&self.severity)));
        parts.push(format!("\"message\":{}", json_str(&self.message)));
        parts.push(format!("\"path\":{}", json_str(&self.path)));
        // §12.2: a source span, 1-based, for compile-time diagnostics
        if let (Some(f), Some(l)) = (file, &self.loc) {
            parts.push(format!(
                "\"location\":{{\"file\":{},\"line\":{},\"col\":{}}}",
                json_str(f),
                l.sl + 1,
                l.sc + 1
            ));
        }
        format!("{{{}}}", parts.join(","))
    }
}

// ---------------- resolved types ----------------
/// a resolved type, shared
pub type RT = Rc<Ty>;

/// a resolved type: its kind, its name when named, its `else` tail
pub struct Ty {
    /// the kind
    pub k: RTk,
    /// the name, for a named type
    pub name: RefCell<Option<String>>,
    /// the `else` tail
    pub tail: RefCell<Option<Tail>>,
}
/// A resolved type of a kind.
pub fn ty(k: RTk) -> RT {
    let rt = Rc::new(Ty {
        k,
        name: RefCell::new(None),
        tail: RefCell::new(None),
    });
    lifetime::track_type(&rt);
    rt
}

/// the kinds of resolved types (§3)
pub enum RTk {
    /// a primitive
    Prim(String),
    /// a literal
    Lit(Value),
    /// a numeric range
    Range {
        /// the lower bound
        lo: Value,
        /// the upper bound
        hi: Value,
        /// whether the upper bound is excluded
        excl: bool,
        /// int or float
        base: String,
    },
    /// a string pattern
    Pattern {
        /// its text
        src: String,
        /// compiled
        re: Regex,
    },
    /// an array
    Arr {
        /// the element type
        elem: RT,
        /// the lower size bound
        lo: Option<i64>,
        /// the upper size bound
        hi: Option<i64>,
    },
    /// a map
    Map {
        /// the key type
        key: RT,
        /// the value type
        val: RT,
    },
    /// a union; its arms are filled after the node exists when an alias names
    /// itself through one of them (§3.1)
    Union(RefCell<Vec<RT>>),
    /// an intersection not yet merged
    IsectN(Vec<RT>),
    /// a record
    Rec(RecType),
    /// a predicate refinement
    Pred {
        /// the base type
        base: RT,
        /// the predicates
        preds: Vec<Rc<Expr>>,
    },
    /// a reference type
    Ref(RT),
    /// a quantity of a dimension
    Quantity(String),
    /// a function type
    Func {
        /// the parameter types
        params: Vec<RT>,
        /// the return type
        ret: RT,
    },
    /// any value
    Any,
}

/// a record type's shape
pub struct RecType {
    /// whether it is open
    pub open: Cell<bool>,
    /// Its members, shared after resolution. Recursive type construction uses
    /// copy-on-write so an earlier snapshot never changes underneath a reader.
    pub members: RefCell<Rc<Vec<Member>>>,
    /// its assertions and guarded groups
    pub asserts: RefCell<Vec<AssertItem>>,
    /// `context $parent: ref<T>` declarations (D30), checked at embedding sites
    pub ctx_decls: RefCell<Vec<(String, RT)>>,
    /// still being filled; extensions of it wait in `pending` (§3.14)
    pub filling: Cell<bool>,
    /// extensions not yet merged (recursive types)
    pub pending: RefCell<Vec<(RT, RT)>>,
}
/// An empty record type.
pub fn rec_type(open: bool) -> RecType {
    RecType {
        open: Cell::new(open),
        members: RefCell::new(Rc::new(vec![])),
        asserts: RefCell::new(vec![]),
        ctx_decls: RefCell::new(vec![]),
        filling: Cell::new(false),
        pending: RefCell::new(vec![]),
    }
}

#[derive(Clone)]
/// a member of a resolved record type
pub struct Member {
    /// the kind
    pub kind: MKind,
    /// the name
    pub name: String,
    /// a hidden member (D34): computed, never part of the value
    pub hidden: bool,
    /// the type
    pub ty: Option<RT>,
    /// the types a conjunction contributed
    pub conj: Option<Vec<RT>>,
    /// the default
    pub dflt: Option<Rc<Expr>>,
    /// the derived expression
    pub expr: Option<Rc<Expr>>,
    /// the module environment
    pub menv: Option<Rc<Env>>,
}

#[derive(Clone)]
/// an assertion or a guarded group of a record type
pub struct AssertItem {
    /// whether it is a `when` group
    pub when: bool,
    /// the name
    pub name: String,
    /// the condition
    pub cond: Rc<Expr>,
    /// the `else` tail
    pub tail: Option<Tail>,
    /// the members, for a group
    pub body: Vec<MemberAst>,
    /// the type declaring it, for the id
    pub origin: Option<String>,
    /// the module environment
    pub menv: Option<Rc<Env>>,
}

/// The members of a record type; empty for any other type.
pub fn rec_members(t: &RT) -> Rc<Vec<Member>> {
    match &t.k {
        RTk::Rec(r) => r.members.borrow().clone(),
        _ => Rc::new(vec![]),
    }
}
/// Whether the type is a record.
pub fn is_rec(t: &RT) -> bool {
    matches!(t.k, RTk::Rec(_))
}
/// The leaf record types of a (possibly nested) union — unions are associative
/// (§3.12), so `A | (B | C)` yields the same leaves as `A | B | C`.
pub fn leaf_recs(t: &RT) -> Vec<RT> {
    match &t.k {
        RTk::Rec(_) => vec![t.clone()],
        RTk::Union(arms) => arms.borrow().iter().flat_map(leaf_recs).collect(),
        _ => vec![],
    }
}

// ---------------- dimension vectors ----------------
/// a dimension as base dimensions with exponents
pub type DimVec = BTreeMap<String, i32>;
/// The dimension's key (`Length*Time^-1`).
pub fn key_of_vec(v: &DimVec) -> String {
    v.iter()
        .filter(|(_, e)| **e != 0)
        .map(|(n, e)| {
            if *e == 1 {
                n.clone()
            } else {
                format!("{n}^{e}")
            }
        })
        .collect::<Vec<_>>()
        .join("*")
}
/// A dimension from its key.
pub fn vec_of_key(key: &str) -> DimVec {
    let mut v = DimVec::new();
    if key.is_empty() {
        return v;
    }
    for p in key.split('*') {
        let (n, e) = match p.split_once('^') {
            Some((n, e)) => (n.to_string(), e.parse::<i32>().unwrap_or(1)),
            None => (p.to_string(), 1),
        };
        *v.entry(n).or_insert(0) += e;
    }
    v
}
/// Two dimensions multiplied (`sign` 1) or divided (`sign` -1).
pub fn vec_combine(a: &DimVec, b: &DimVec, sign: i32) -> DimVec {
    let mut out = a.clone();
    for (n, e) in b {
        *out.entry(n.clone()).or_insert(0) += sign * e;
    }
    out
}

// ---------------- environment ----------------
/// an exported name: the environment declaring it
pub struct Export {
    /// the environment
    pub env: Rc<Env>,
    /// the name there
    pub name: String,
}
impl Clone for Export {
    fn clone(&self) -> Self {
        Export {
            env: self.env.clone(),
            name: self.name.clone(),
        }
    }
}
/// a constant's declaration and memoized value
pub struct ConstEntry {
    /// the expression
    pub expr: Rc<Expr>,
    /// the annotation
    pub ty: Option<TypeAst>,
    /// whether the value is computed
    pub state: Cell<bool>,
    /// the value
    pub value: RefCell<Value>,
}
/// a function's declaration
pub struct FuncEntry {
    /// the parameters
    pub params: Vec<Param>,
    /// the return type
    pub ret: Option<TypeAst>,
    /// the body
    pub body: Rc<Expr>,
}
/// a type's declaration
pub struct TypeEntry {
    /// the type
    pub ast: TypeAst,
    /// its `else` tail
    pub tail: Option<Tail>,
    /// the type parameters
    pub params: Vec<Param>,
}
/// a diagnostic template's declaration
pub struct DiagDecl {
    /// the parameters
    pub params: Vec<Param>,
    /// the severity
    pub severity: String,
    /// the template
    pub template: Vec<TPart>,
}
/// a unit's declaration
pub struct UnitDecl {
    /// its dimension
    pub dim: Option<String>,
    /// its factor
    pub factor: Option<Rc<Expr>>,
    /// its base unit
    pub base: Option<String>,
}
/// evaluates a constant by name (the engine's)
pub type ConstEval = Rc<dyn Fn(&str) -> R<Value>>;
/// evaluates an expression (the engine's)
pub type ExprEval = Rc<dyn Fn(&Rc<Expr>) -> R<Value>>;

/// the environment of a module: its declarations, its imports, its roots and
/// diagnostics, the unit space
pub struct Env {
    /// the type declarations
    pub type_asts: RefCell<HashMap<String, Rc<TypeEntry>>>,
    /// resolved types, memoized
    pub type_memo: RefCell<HashMap<String, RT>>,
    /// the non-record aliases being resolved, to catch a reference back to one
    pub resolving: RefCell<HashSet<String>>,
    /// the placeholder an alias's inner reference took (§3.1)
    pub cyclic: RefCell<HashMap<String, RT>>,
    // names being spliced into a pattern right now, across nested
    // resolutions — a mutually recursive pair is a cycle, not a stack overflow
    /// the named types being resolved (recursion)
    pub pattern_visiting: RefCell<Vec<String>>,
    /// the constants
    pub consts: RefCell<HashMap<String, Rc<ConstEntry>>>,
    /// the functions
    pub funcs: RefCell<HashMap<String, Rc<FuncEntry>>>,
    /// names declared twice
    pub duplicates: RefCell<Vec<String>>,
    /// the outputs: name, type, expression
    pub outputs: RefCell<Vec<(String, TypeAst, Rc<Expr>)>>,
    /// the inputs: type, fallback
    pub inputs: RefCell<HashMap<String, (TypeAst, Option<Rc<Expr>>)>>,
    /// the diagnostic templates
    pub diags: RefCell<HashMap<String, Rc<DiagDecl>>>,
    /// every instance bound
    pub registry: RefCell<Rc<RefCell<Vec<Rc<RefCell<RecInst>>>>>>,
    /// the roots' values, by name
    pub roots: RefCell<Rc<RefCell<Vec<(String, Value)>>>>,
    /// the diagnostics raised
    pub diagnostics: RefCell<Rc<RefCell<Vec<Diag>>>>,
    /// >0: a frozen round is being read (`Engine::muted`) — its reports are not this evaluation's
    pub muted: Cell<u32>,
    /// the constant evaluator, once an engine is wired in
    pub const_eval: RefCell<Option<ConstEval>>,
    /// the expression evaluator, once an engine is wired in
    pub expr_eval: RefCell<Option<ExprEval>>,
    /// the imported names
    pub imports: RefCell<HashMap<String, Export>>,
    /// the namespace imports
    pub namespaces: RefCell<HashMap<String, (Rc<Env>, Rc<RefCell<HashMap<String, Export>>>)>>,
    const_diag_seen: RefCell<HashSet<String>>,
    /// the dimension declarations
    pub dim_decls: RefCell<HashMap<String, Option<Vec<(String, i32)>>>>,
    /// dimensions resolved, memoized
    pub dim_memo: RefCell<HashMap<String, DimVec>>,
    /// the unit declarations
    pub unit_decls: RefCell<HashMap<String, UnitDecl>>,
    /// units resolved to (dimension, factor), memoized
    pub unit_memo: RefCell<HashMap<String, (String, f64)>>,
    /// the base unit of each dimension
    pub base_unit_of: RefCell<HashMap<String, String>>,
    /// the unit space's diagnostics (E4073 and friends)
    pub space_diags: RefCell<Vec<Diag>>,
    /// declaration order (HashMaps do not keep it; diagnostics follow it)
    pub type_order: RefCell<Vec<String>>,
    /// the units in declaration order
    pub unit_order: RefCell<Vec<String>>,
    /// installed by the checker: constant-evaluation errors go here instead of the report
    pub const_diag_sink: RefCell<Option<Rc<RefCell<Vec<Diag>>>>>,
    /// installed by the engine: the evaluation step a report is attributed to
    pub tagger: RefCell<Option<Rc<dyn Fn() -> Option<String>>>>,
}

/// §6.7: evaluation- and validation-time diagnostics sort by (path, id), path in canonical order; stable
pub fn sort_diags(diags: Vec<Diag>) -> Vec<Diag> {
    let segs_of = |p: &str| -> SegPath {
        if p.is_empty() {
            return vec![];
        }
        parse_path(p, "").unwrap_or_else(|_| vec![Seg::Name(Rc::from(p.to_string()))])
    };
    let mut keyed: Vec<(usize, SegPath, Diag)> = diags
        .into_iter()
        .enumerate()
        .map(|(i, d)| (i, segs_of(&d.path), d))
        .collect();
    keyed.sort_by(|a, b| {
        cmp_path(&a.1, &b.1)
            .then_with(|| {
                a.2.id
                    .as_deref()
                    .unwrap_or("")
                    .cmp(b.2.id.as_deref().unwrap_or(""))
            })
            .then_with(|| a.0.cmp(&b.0))
    });
    keyed.into_iter().map(|(_, _, d)| d).collect()
}

const SI_PREFIXES: [(&str, f64); 20] = [
    ("y", 1e-24),
    ("z", 1e-21),
    ("a", 1e-18),
    ("f", 1e-15),
    ("p", 1e-12),
    ("n", 1e-9),
    ("u", 1e-6),
    ("m", 1e-3),
    ("c", 1e-2),
    ("d", 1e-1),
    ("da", 1e1),
    ("h", 1e2),
    ("k", 1e3),
    ("M", 1e6),
    ("G", 1e9),
    ("T", 1e12),
    ("P", 1e15),
    ("E", 1e18),
    ("Z", 1e21),
    ("Y", 1e24),
];

impl Env {
    /// An empty environment.
    pub fn new() -> Rc<Env> {
        let env = Env {
            type_asts: RefCell::new(HashMap::new()),
            type_memo: RefCell::new(HashMap::new()),
            resolving: RefCell::new(HashSet::new()),
            cyclic: RefCell::new(HashMap::new()),
            pattern_visiting: RefCell::new(vec![]),
            consts: RefCell::new(HashMap::new()),
            funcs: RefCell::new(HashMap::new()),
            duplicates: RefCell::new(vec![]),
            outputs: RefCell::new(vec![]),
            inputs: RefCell::new(HashMap::new()),
            diags: RefCell::new(HashMap::new()),
            registry: RefCell::new(Rc::new(RefCell::new(vec![]))),
            roots: RefCell::new(Rc::new(RefCell::new(vec![]))),
            diagnostics: RefCell::new(Rc::new(RefCell::new(vec![]))),
            muted: Cell::new(0),
            const_eval: RefCell::new(None),
            expr_eval: RefCell::new(None),
            imports: RefCell::new(HashMap::new()),
            namespaces: RefCell::new(HashMap::new()),
            const_diag_seen: RefCell::new(HashSet::new()),
            dim_decls: RefCell::new(HashMap::new()),
            dim_memo: RefCell::new(HashMap::new()),
            unit_decls: RefCell::new(HashMap::new()),
            unit_memo: RefCell::new(HashMap::new()),
            base_unit_of: RefCell::new(HashMap::new()),
            space_diags: RefCell::new(vec![]),
            type_order: RefCell::new(vec![]),
            unit_order: RefCell::new(vec![]),
            const_diag_sink: RefCell::new(None),
            tagger: RefCell::new(None),
        };
        env.seed_units();
        let env = Rc::new(env);
        lifetime::track_env(&env);
        env
    }

    // std.units — the SI catalog generated from the §13.10 prefix rule (D15)
    fn seed_units(&self) {
        let unit = |sym: &str, dim: Option<&str>, factor: f64, base: &str| {
            let mut m = self.unit_decls.borrow_mut();
            if m.contains_key(sym) {
                return;
            }
            self.unit_order.borrow_mut().push(sym.to_string());
            m.insert(
                sym.to_string(),
                match dim {
                    Some(d) => UnitDecl {
                        dim: Some(d.to_string()),
                        factor: None,
                        base: None,
                    },
                    None => UnitDecl {
                        dim: None,
                        factor: Some(Rc::new(Expr::Lit(Value::Float(factor)))),
                        base: Some(base.to_string()),
                    },
                },
            );
        };
        let bases = [
            ("Time", "s"),
            ("Length", "m"),
            ("Mass", "kg"),
            ("Current", "A"),
            ("Temperature", "K"),
            ("Amount", "mol"),
            ("LuminousIntensity", "cd"),
        ];
        for (d, _) in bases {
            self.dim_decls.borrow_mut().insert(d.to_string(), None);
        }
        let t = |n: &str, e: i32| (n.to_string(), e);
        let derived: Vec<(&str, Option<Vec<(String, i32)>>, &str)> = vec![
            ("Frequency", Some(vec![t("Time", -1)]), "Hz"),
            (
                "Force",
                Some(vec![t("Mass", 1), t("Length", 1), t("Time", -2)]),
                "N",
            ),
            (
                "Pressure",
                Some(vec![t("Mass", 1), t("Length", -1), t("Time", -2)]),
                "Pa",
            ),
            (
                "Energy",
                Some(vec![t("Mass", 1), t("Length", 2), t("Time", -2)]),
                "J",
            ),
            (
                "Power",
                Some(vec![t("Mass", 1), t("Length", 2), t("Time", -3)]),
                "W",
            ),
            ("Charge", Some(vec![t("Current", 1), t("Time", 1)]), "C"),
            (
                "Voltage",
                Some(vec![
                    t("Mass", 1),
                    t("Length", 2),
                    t("Time", -3),
                    t("Current", -1),
                ]),
                "V",
            ),
            (
                "Resistance",
                Some(vec![
                    t("Mass", 1),
                    t("Length", 2),
                    t("Time", -3),
                    t("Current", -2),
                ]),
                "Ohm",
            ),
            (
                "Capacitance",
                Some(vec![
                    t("Mass", -1),
                    t("Length", -2),
                    t("Time", 4),
                    t("Current", 2),
                ]),
                "F",
            ),
            ("DataSize", None, "bit"),
        ];
        for (d, terms, _) in &derived {
            self.dim_decls
                .borrow_mut()
                .insert(d.to_string(), terms.clone());
        }
        for (d, s) in bases {
            unit(s, Some(d), 1.0, "");
        }
        for (d, _, s) in &derived {
            unit(s, Some(d), 1.0, "");
        }
        unit("B", None, 8.0, "bit");
        unit("g", None, 1e-3, "kg");
        let mut prefixable: Vec<&str> = bases
            .iter()
            .map(|(_, s)| *s)
            .filter(|s| *s != "kg")
            .collect();
        prefixable.extend(derived.iter().map(|(_, _, s)| *s).filter(|s| *s != "bit"));
        prefixable.push("g");
        for u0 in prefixable {
            for (p, f) in SI_PREFIXES {
                unit(&format!("{p}{u0}"), None, f, u0);
            }
        }
        for u0 in ["bit", "B"] {
            for (p, f) in [
                ("Ki", 1024f64),
                ("Mi", 1024f64.powi(2)),
                ("Gi", 1024f64.powi(3)),
                ("Ti", 1024f64.powi(4)),
                ("Pi", 1024f64.powi(5)),
                ("Ei", 1024f64.powi(6)),
            ] {
                unit(&format!("{p}{u0}"), None, f, u0);
            }
            for (p, f) in SI_PREFIXES {
                if ["k", "M", "G", "T", "P", "E"].contains(&p) {
                    unit(&format!("{p}{u0}"), None, f, u0);
                }
            }
        }
    }

    /// Load declarations into the environment (§5, §8).
    pub fn load(&self, decls: &[Decl]) {
        let mut seen: HashSet<String> = HashSet::new();
        for d in decls {
            if let Some(n) = d.name() {
                if !matches!(d.body, DeclBody::Unit { .. } | DeclBody::Dimension { .. })
                    && !seen.insert(n.to_string())
                {
                    self.duplicates.borrow_mut().push(n.to_string());
                }
            }
            match &d.body {
                DeclBody::Dimension { name, terms } => {
                    if self.dim_decls.borrow().contains_key(name) {
                        self.space_diags.borrow_mut().push(Diag::error(
                            format!("dimension {name} redeclared"),
                            String::new(),
                            Some("E3001"),
                        ));
                    } else {
                        self.dim_decls
                            .borrow_mut()
                            .insert(name.clone(), terms.clone());
                    }
                }
                DeclBody::Unit {
                    name,
                    dim,
                    factor,
                    base,
                } => {
                    if self.unit_decls.borrow().contains_key(name) {
                        self.space_diags.borrow_mut().push(Diag::error(
                            format!("unit {name} redeclared"),
                            String::new(),
                            Some("E4073"),
                        ));
                    } else {
                        self.unit_order.borrow_mut().push(name.clone());
                        self.unit_decls.borrow_mut().insert(
                            name.clone(),
                            UnitDecl {
                                dim: dim.clone(),
                                factor: factor.clone(),
                                base: base.clone(),
                            },
                        );
                    }
                }
                DeclBody::Type {
                    name,
                    params,
                    ty,
                    tail,
                } => {
                    if !self.type_asts.borrow().contains_key(name) {
                        self.type_order.borrow_mut().push(name.clone());
                    }
                    self.type_asts.borrow_mut().insert(
                        name.clone(),
                        Rc::new(TypeEntry {
                            ast: ty.clone(),
                            tail: tail.clone(),
                            params: params.clone(),
                        }),
                    );
                }
                DeclBody::Const { name, ty, expr } => {
                    self.consts.borrow_mut().insert(
                        name.clone(),
                        Rc::new(ConstEntry {
                            expr: expr.clone(),
                            ty: ty.clone(),
                            state: Cell::new(false),
                            value: RefCell::new(Value::Null),
                        }),
                    );
                }
                DeclBody::Func {
                    name,
                    params,
                    ret,
                    body,
                } => {
                    self.funcs.borrow_mut().insert(
                        name.clone(),
                        Rc::new(FuncEntry {
                            params: params.clone(),
                            ret: ret.clone(),
                            body: body.clone(),
                        }),
                    );
                }
                DeclBody::Output { name, ty, expr } => {
                    self.outputs
                        .borrow_mut()
                        .push((name.clone(), ty.clone(), expr.clone()))
                }
                DeclBody::Input { name, ty, fallback } => {
                    self.inputs
                        .borrow_mut()
                        .insert(name.clone(), (ty.clone(), fallback.clone()));
                }
                DeclBody::Diagnostic {
                    name,
                    params,
                    severity,
                    template,
                } => {
                    self.diags.borrow_mut().insert(
                        name.clone(),
                        Rc::new(DiagDecl {
                            params: params.clone(),
                            severity: severity.clone(),
                            template: template.clone(),
                        }),
                    );
                }
                _ => {}
            }
        }
    }

    /// Raise a diagnostic.
    pub fn report(&self, d: Diag) {
        if self.muted.get() > 0 {
            return;
        }
        let by = self.tagger.borrow().as_ref().and_then(|t| t());
        let mut d = d;
        if by.is_some() {
            d.by = by;
        }
        self.diagnostics.borrow().borrow_mut().push(d);
    }
    /// replace every diagnostic (the run entry points sort them, §6.7)
    pub fn diag_set(&self, diags: Vec<Diag>) {
        let rc = self.diagnostics.borrow().clone();
        *rc.borrow_mut() = diags;
    }
    /// Forget a root.
    pub fn remove_root(&self, name: &str) {
        let rc = self.roots.borrow().clone();
        rc.borrow_mut().retain(|(n, _)| n != name);
    }
    /// The roots' names, in order.
    pub fn root_names(&self) -> Vec<String> {
        self.roots
            .borrow()
            .borrow()
            .iter()
            .map(|(n, _)| n.clone())
            .collect()
    }
    /// Keep the instances a predicate accepts.
    pub fn registry_retain(&self, mut pred: impl FnMut(&Rc<RefCell<RecInst>>) -> bool) {
        let rc = self.registry.borrow().clone();
        rc.borrow_mut().retain(|i| pred(i));
    }
    /// Count registered instances without copying their shared handles.
    pub(crate) fn registry_len(&self) -> usize {
        self.registry.borrow().borrow().len()
    }
    /// Preserve the existing prefix and retain only the tail a predicate accepts.
    pub(crate) fn registry_retain_from(
        &self,
        start: usize,
        mut pred: impl FnMut(&Rc<RefCell<RecInst>>) -> bool,
    ) {
        let rc = self.registry.borrow().clone();
        let mut registry = rc.borrow_mut();
        let start = start.min(registry.len());
        for _ in registry.extract_if(start.., |inst| !pred(inst)) {}
    }
    /// The diagnostics raised so far.
    pub fn diagnostics_vec(&self) -> Vec<Diag> {
        self.diagnostics.borrow().borrow().clone()
    }
    /// How many diagnostics were raised.
    pub fn diag_len(&self) -> usize {
        self.diagnostics.borrow().borrow().len()
    }
    /// Forget the diagnostics after the first `n`.
    pub fn diag_truncate(&self, n: usize) {
        self.diagnostics.borrow().borrow_mut().truncate(n);
    }
    /// A root's value.
    pub fn root(&self, name: &str) -> Option<Value> {
        self.roots
            .borrow()
            .borrow()
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.clone())
    }
    /// Set a root's value.
    pub fn set_root(&self, name: &str, v: Value) {
        let rc = self.roots.borrow().clone();
        let mut roots = rc.borrow_mut();
        if let Some(e) = roots.iter_mut().find(|(n, _)| n == name) {
            e.1 = v;
        } else {
            roots.push((name.to_string(), v));
        }
    }
    /// The roots' values, in order.
    pub fn root_values(&self) -> Vec<Value> {
        self.roots
            .borrow()
            .borrow()
            .iter()
            .map(|(_, v)| v.clone())
            .collect()
    }
    /// Register an instance.
    pub fn registry_push(&self, inst: Rc<RefCell<RecInst>>) {
        self.registry.borrow().borrow_mut().push(inst);
    }
    /// Forget every instance (a round starts over).
    pub fn registry_clear(&self) {
        self.registry.borrow().borrow_mut().clear();
    }
    /// Forget every root (a round starts over).
    pub fn roots_clear(&self) {
        self.roots.borrow().borrow_mut().clear();
    }
    /// The roots with their names, in order.
    pub fn roots_vec(&self) -> Vec<(String, Value)> {
        self.roots.borrow().borrow().clone()
    }
    /// The instances registered so far.
    pub fn registry_snapshot(&self) -> Vec<Rc<RefCell<RecInst>>> {
        self.registry.borrow().borrow().clone()
    }

    // §4.13: a named endpoint in a constant position evaluates at elaboration time
    /// A numeric constant's value where a type expects a number (a size, a bound).
    pub fn const_num(&self, v: &Value) -> Value {
        let name = match v {
            Value::Str(s) => s.to_string(),
            other => return other.clone(),
        };
        let ce = self.const_eval.borrow().clone();
        let Some(ce) = ce else { return v.clone() };
        if !self.consts.borrow().contains_key(&name) {
            return v.clone();
        }
        let diag = |code: &str, message: String| {
            let key = format!("{name}{code}");
            if self.const_diag_seen.borrow().contains(&key) {
                return;
            }
            self.const_diag_seen.borrow_mut().insert(key);
            let d = Diag::error(message, String::new(), Some(code));
            match &*self.const_diag_sink.borrow() {
                Some(sink) => sink.borrow_mut().push(d),
                None => self.report(d),
            }
        };
        match ce(&name) {
            Ok(Value::Int(i)) => Value::Int(i),
            Ok(Value::Float(f)) => Value::Float(f),
            Ok(Value::Undef) | Ok(Value::Null) => v.clone(),
            Ok(_) => {
                diag(
                    "E4021",
                    format!("constant {name} is not numeric in a constant position"),
                );
                v.clone()
            }
            Err(Fail::Eval(e)) => {
                let code = if e.msg.contains("zero") {
                    "E5001"
                } else if e.msg.contains("NaN") || e.msg.contains("Infinity") {
                    "E5002"
                } else {
                    "E5001"
                };
                diag(code, format!("evaluating constant {name}: {}", e.msg));
                v.clone()
            }
            Err(_) => v.clone(),
        }
    }

    // ---- unit / dimension name spaces ----
    /// Resolve a dimension by name to its base dimensions.
    pub fn resolve_dim(&self, name: &str, visiting: &mut Vec<String>) -> Result<DimVec, String> {
        if let Some(v) = self.dim_memo.borrow().get(name) {
            return Ok(v.clone());
        }
        if visiting.iter().any(|v| v == name) {
            return Err(format!("circular dimension {name}"));
        }
        let decl = self
            .dim_decls
            .borrow()
            .get(name)
            .cloned()
            .ok_or_else(|| format!("unknown dimension {name}"))?;
        let mut vec = DimVec::new();
        match decl {
            None => {
                vec.insert(name.to_string(), 1);
            }
            Some(terms) => {
                visiting.push(name.to_string());
                for (tn, te) in terms {
                    let sub = self.resolve_dim(&tn, visiting)?;
                    for (n, e) in sub {
                        *vec.entry(n).or_insert(0) += e * te;
                    }
                }
                visiting.pop();
            }
        }
        self.dim_memo
            .borrow_mut()
            .insert(name.to_string(), vec.clone());
        Ok(vec)
    }
    /// A unit's dimension key and factor against the base unit.
    pub fn unit_info(&self, sym: &str) -> Result<(String, f64), String> {
        self.unit_info_v(sym, &mut vec![])
    }
    /// §3.16 unit/dimension-space findings for the checker: the load-time
    /// redeclarations plus unresolvable units and duplicate base units
    pub fn finalize_unit_space(&self) -> Vec<Diag> {
        let mut out = self.space_diags.borrow().clone();
        let mut base_seen: HashMap<String, String> = HashMap::new();
        let syms = self.unit_order.borrow().clone();
        for sym in syms {
            let has_dim = self
                .unit_decls
                .borrow()
                .get(&sym)
                .map(|u| u.dim.is_some())
                .unwrap_or(false);
            match self.unit_info(&sym) {
                Ok((key, _)) => {
                    if has_dim {
                        if let Some(prev) = base_seen.get(&key) {
                            out.push(Diag::error(
                                format!(
                                    "second base unit {sym} for dimension {key} (base is {prev})"
                                ),
                                String::new(),
                                Some("E4073"),
                            ));
                        } else {
                            base_seen.insert(key, sym.clone());
                        }
                    }
                }
                Err(msg) => {
                    let code = if msg.contains("unknown dimension")
                        || msg.contains("circular dimension")
                    {
                        "E3003"
                    } else {
                        "E4073"
                    };
                    out.push(Diag::error(msg, String::new(), Some(code)));
                }
            }
        }
        out
    }
    fn unit_info_v(&self, sym: &str, visiting: &mut Vec<String>) -> Result<(String, f64), String> {
        if let Some(v) = self.unit_memo.borrow().get(sym) {
            return Ok(v.clone());
        }
        if visiting.iter().any(|v| v == sym) {
            return Err(format!("circular unit {sym}"));
        }
        let (dim, factor, base) = {
            let m = self.unit_decls.borrow();
            let u = m.get(sym).ok_or_else(|| format!("unknown unit {sym}"))?;
            (u.dim.clone(), u.factor.clone(), u.base.clone())
        };
        let info = if let Some(d) = dim {
            let key = key_of_vec(&self.resolve_dim(&d, &mut vec![])?);
            self.base_unit_of
                .borrow_mut()
                .entry(key.clone())
                .or_insert_with(|| sym.to_string());
            (key, 1.0)
        } else {
            visiting.push(sym.to_string());
            let b = self.unit_info_v(base.as_deref().unwrap_or(""), visiting)?;
            visiting.pop();
            let mut f: Option<f64> = match factor.as_deref() {
                Some(Expr::Lit(Value::Float(x))) => Some(*x),
                Some(Expr::Lit(Value::Int(i))) => i.to_f64(),
                _ => None,
            };
            if f.is_none() {
                if let (Some(fx), Some(ee)) = (factor.clone(), self.expr_eval.borrow().clone()) {
                    f = match ee(&fx) {
                        Ok(Value::Float(x)) => Some(x),
                        Ok(Value::Int(i)) => i.to_f64(),
                        _ => None,
                    };
                }
            }
            let f = f.ok_or_else(|| format!("unit {sym}: factor is not a numeric constant"))?;
            (b.0, f * b.1)
        };
        self.unit_memo
            .borrow_mut()
            .insert(sym.to_string(), info.clone());
        Ok(info)
    }

    // ---- type resolution ----
    /// Resolve a type annotation to a resolved type (§3), memoized under `name` for a named type.
    pub fn resolve(self: &Rc<Env>, ast: &TypeAst, name: Option<&str>) -> Result<RT, String> {
        Ok(match ast {
            TypeAst::Prim { name: n, .. } => ty(RTk::Prim(n.clone())),
            TypeAst::Lit { v, .. } => ty(RTk::Lit(v.clone())),
            TypeAst::Range { lo, hi, excl, .. } => {
                let lo = self.const_num(lo);
                let hi = self.const_num(hi);
                let is_f = matches!(lo, Value::Float(_)) || matches!(hi, Value::Float(_));
                ty(RTk::Range {
                    lo,
                    hi,
                    excl: *excl,
                    base: if is_f { "float".into() } else { "int".into() },
                })
            }
            TypeAst::Pattern { re: src, .. } => {
                let expanded = self.expand_pattern(src)?;
                if let Some(bad) = pattern_error(&expanded) {
                    return Err(format!("malformed pattern /{src}/: {bad}"));
                }
                let re = compile_pattern(&expanded)
                    .map_err(|e| format!("malformed pattern /{src}/: {e}"))?;
                ty(RTk::Pattern { src: expanded, re })
            }
            TypeAst::Map { key, val, .. } => ty(RTk::Map {
                key: self.resolve(key, None)?,
                val: self.resolve(val, None)?,
            }),
            TypeAst::Array {
                elem, lo, hi, excl, ..
            } => {
                let lo = lo.as_ref().map(|v| self.const_num(v));
                let hi0 = hi.as_ref().map(|v| self.const_num(v));
                let to_i = |v: &Value| match v {
                    Value::Int(i) => i.to_i64(),
                    Value::Float(f) => Some(*f as i64),
                    _ => None,
                };
                let lo_i = lo.as_ref().and_then(&to_i);
                let hi_i = hi0
                    .as_ref()
                    .and_then(to_i)
                    .map(|h| if *excl { h - 1 } else { h });
                ty(RTk::Arr {
                    elem: self.resolve(elem, None)?,
                    lo: lo_i,
                    hi: hi_i,
                })
            }
            TypeAst::Union { arms, .. } => ty(RTk::Union(RefCell::new(
                arms.iter()
                    .map(|a| self.resolve(a, None))
                    .collect::<Result<_, _>>()?,
            ))),
            TypeAst::Isect { arms, .. } => {
                let arms: Vec<RT> = arms
                    .iter()
                    .map(|a| self.resolve(a, None))
                    .collect::<Result<_, _>>()?;
                if arms.iter().all(is_rec) {
                    self.merge_isect(&arms, name)
                } else {
                    ty(RTk::IsectN(arms))
                }
            }
            TypeAst::Record { members, open, .. } => {
                let rt = ty(RTk::Rec(rec_type(*open)));
                *rt.name.borrow_mut() = name.map(|s| s.to_string());
                self.fill_record(&rt, members)?;
                rt
            }
            TypeAst::Func { params, ret, .. } => ty(RTk::Func {
                params: params
                    .iter()
                    .map(|p| self.resolve(p, None))
                    .collect::<Result<_, _>>()?,
                ret: self.resolve(ret, None)?,
            }),
            TypeAst::Named {
                name: n,
                args,
                preds,
                ext,
                ..
            } => {
                if let Some(preds) = preds {
                    if !preds.is_empty() {
                        let base = self.resolve(
                            &TypeAst::Named {
                                name: n.clone(),
                                args: args.clone(),
                                preds: None,
                                ext: ext.clone(),
                                loc: None,
                            },
                            name,
                        )?;
                        return Ok(ty(RTk::Pred {
                            base,
                            preds: preds.clone(),
                        }));
                    }
                }
                if n == "quantity" {
                    let dn = match args.first() {
                        Some(TypeAst::Named { name, .. }) | Some(TypeAst::Prim { name, .. }) => {
                            name.clone()
                        }
                        _ => return Err("quantity needs a dimension".into()),
                    };
                    return Ok(ty(RTk::Quantity(key_of_vec(
                        &self.resolve_dim(&dn, &mut vec![])?,
                    ))));
                }
                if n == "map" && args.len() == 2 {
                    return Ok(ty(RTk::Map {
                        key: self.resolve(&args[0], None)?,
                        val: self.resolve(&args[1], None)?,
                    }));
                }
                if n == "ref" {
                    return Ok(ty(RTk::Ref(self.resolve(&args[0], None)?)));
                }
                if ["int", "float", "bool", "string"].contains(&n.as_str())
                    && args.is_empty()
                    && ext.is_none()
                {
                    return Ok(ty(RTk::Prim(n.clone())));
                }
                let decl = self.type_asts.borrow().get(n).cloned();
                let Some(decl) = decl else {
                    let im = self.imports.borrow().get(n).cloned();
                    if let Some(im) = im {
                        return im.env.resolve(
                            &TypeAst::Named {
                                name: im.name.clone(),
                                args: args.clone(),
                                preds: None,
                                ext: ext.clone(),
                                loc: None,
                            },
                            name,
                        );
                    }
                    if let Some((ns, rest)) = n.split_once('.') {
                        let ex = self
                            .namespaces
                            .borrow()
                            .get(ns)
                            .and_then(|(_, exports)| exports.borrow().get(rest).cloned());
                        if let Some(ex) = ex {
                            return ex.env.resolve(
                                &TypeAst::Named {
                                    name: ex.name.clone(),
                                    args: args.clone(),
                                    preds: None,
                                    ext: ext.clone(),
                                    loc: None,
                                },
                                name,
                            );
                        }
                    }
                    return Err(format!("unknown type {n}"));
                };
                let memo = self.type_memo.borrow().get(n).cloned();
                let base = if !decl.params.is_empty() {
                    self.instantiate(n, args, &decl)?
                } else if let Some(b) = memo {
                    b
                } else {
                    match &decl.ast {
                        TypeAst::Record { members, open, .. } => {
                            let rt = ty(RTk::Rec(rec_type(*open)));
                            *rt.name.borrow_mut() = Some(n.clone());
                            *rt.tail.borrow_mut() = decl.tail.clone();
                            self.type_memo.borrow_mut().insert(n.clone(), rt.clone());
                            // a member that fails to resolve must not leave a half-filled
                            // record memoized (later lookups would miss its later members)
                            if let Err(e) = self.fill_record(&rt, members) {
                                self.type_memo.borrow_mut().remove(n);
                                return Err(e);
                            }
                            rt
                        }
                        TypeAst::Named {
                            name: pn,
                            args: pa,
                            preds: pp,
                            ext: Some(body),
                            ..
                        } => {
                            // an extension declaration (§3.14) is memoized before its parent
                            // resolves: in a recursive family — `type Base = { kids: { [string]:
                            // Kid } }`, `type Kid = Base { … }` — the parent's body names this
                            // type, and every reference must share the one final record rather
                            // than a snapshot of the parent's members taken mid-fill
                            let rt = ty(RTk::Rec(rec_type(false)));
                            if let RTk::Rec(r) = &rt.k {
                                r.filling.set(true);
                            }
                            *rt.name.borrow_mut() = Some(n.clone());
                            *rt.tail.borrow_mut() = decl.tail.clone();
                            self.type_memo.borrow_mut().insert(n.clone(), rt.clone());
                            let parent_ast = TypeAst::Named {
                                name: pn.clone(),
                                args: pa.clone(),
                                preds: pp.clone(),
                                ext: None,
                                loc: None,
                            };
                            let filled = self.resolve(&parent_ast, None).and_then(|parent| {
                                let extr = self.resolve(body, None)?;
                                self.extend_into(&rt, &parent, &extr);
                                Ok(())
                            });
                            if let Err(e) = filled {
                                self.type_memo.borrow_mut().remove(n);
                                return Err(e);
                            }
                            rt
                        }
                        other => {
                            // an alias that names itself through an array, a map, or a
                            // union (`type Json = … | Json[] | { [string]: Json }`, §3.1)
                            // is entered once: the inner reference gets a placeholder
                            // union that the outer resolution fills — so every reference
                            // shares the one node; a pattern's interpolation cycle is the
                            // pattern code's own diagnostic
                            let guard = !matches!(other, TypeAst::Pattern { .. });
                            if guard && self.resolving.borrow().contains(n) {
                                let ph = self.cyclic.borrow().get(n).cloned();
                                return Ok(match ph {
                                    Some(ph) => ph,
                                    None => {
                                        let ph = ty(RTk::Union(RefCell::new(vec![])));
                                        *ph.name.borrow_mut() = Some(n.clone());
                                        *ph.tail.borrow_mut() = decl.tail.clone();
                                        self.cyclic.borrow_mut().insert(n.clone(), ph.clone());
                                        ph
                                    }
                                });
                            }
                            if guard {
                                self.resolving.borrow_mut().insert(n.clone());
                            }
                            let resolved = self.resolve(other, Some(n));
                            if guard {
                                self.resolving.borrow_mut().remove(n);
                            }
                            let mut rt = resolved?;
                            let ph = self.cyclic.borrow_mut().remove(n);
                            if let Some(ph) = ph {
                                let arms: Vec<RT> = match &rt.k {
                                    RTk::Union(a) => a.borrow().clone(),
                                    _ => vec![rt.clone()],
                                };
                                if arms.iter().any(|a| Rc::ptr_eq(a, &ph)) {
                                    return Err(format!(
                                        "recursive type alias {n} names itself as an arm"
                                    ));
                                }
                                if let RTk::Union(pa) = &ph.k {
                                    *pa.borrow_mut() = arms;
                                }
                                rt = ph;
                            }
                            if matches!(rt.k, RTk::Rec(_) | RTk::Union(_)) {
                                *rt.name.borrow_mut() = Some(n.clone());
                            }
                            if rt.tail.borrow().is_none() {
                                *rt.tail.borrow_mut() = decl.tail.clone();
                            }
                            self.type_memo.borrow_mut().insert(n.clone(), rt.clone());
                            rt
                        }
                    }
                };
                if let Some(ext) = ext {
                    // an inline extension in a type position: anonymous, never memoized
                    let extr = self.resolve(ext, None)?;
                    if !is_rec(&base) {
                        return Ok(base);
                    }
                    let merged = ty(RTk::Rec(rec_type(false)));
                    if let RTk::Rec(r) = &merged.k {
                        r.filling.set(true);
                    }
                    *merged.name.borrow_mut() = base.name.borrow().clone();
                    self.extend_into(&merged, &base, &extr);
                    return Ok(merged);
                }
                base
            }
        })
    }

    // §3.14: fill `target` as `base` extended by the override body `ext` —
    // base members copied, overrides replacing or adding, asserts appended,
    // and a context declaration narrowed by the extension replacing the
    // inherited one (§7.3). A base still being filled (the recursive-family
    // case above) defers the merge until it completes; `target` stays marked
    // filling meanwhile, so an extension of an extension waits in turn.
    fn extend_into(&self, target: &RT, base: &RT, extr: &RT) {
        let (RTk::Rec(tr), RTk::Rec(br), RTk::Rec(er)) = (&target.k, &base.k, &extr.k) else {
            if let RTk::Rec(tr) = &target.k {
                tr.filling.set(false);
            }
            return;
        };
        if br.filling.get() {
            br.pending.borrow_mut().push((target.clone(), extr.clone()));
            return;
        }
        tr.open.set(br.open.get());
        if let Some(t) = base.tail.borrow().clone() {
            *target.tail.borrow_mut() = Some(t);
        }
        let mut members: Vec<Member> = (**br.members.borrow()).clone();
        for om in er.members.borrow().iter() {
            if let Some(i) = members.iter().position(|m| m.name == om.name) {
                members[i] = om.clone();
            } else {
                members.push(om.clone());
            }
        }
        let mut asserts = br.asserts.borrow().clone();
        asserts.extend(er.asserts.borrow().iter().cloned());
        let mut ctx_decls: Vec<(String, RT)> = br.ctx_decls.borrow().clone();
        for cd in er.ctx_decls.borrow().iter() {
            if let Some(i) = ctx_decls.iter().position(|(v, _)| *v == cd.0) {
                ctx_decls[i] = cd.clone();
            } else {
                ctx_decls.push(cd.clone());
            }
        }
        *tr.members.borrow_mut() = Rc::new(members);
        *tr.asserts.borrow_mut() = asserts;
        *tr.ctx_decls.borrow_mut() = ctx_decls;
        self.complete_record(target);
    }

    // a record's members are final: extensions that waited on it merge now
    fn complete_record(&self, rt: &RT) {
        let RTk::Rec(r) = &rt.k else { return };
        r.filling.set(false);
        let pending: Vec<(RT, RT)> = std::mem::take(&mut *r.pending.borrow_mut());
        for (target, extr) in pending {
            self.extend_into(&target, rt, &extr);
        }
    }

    // §3.6: `${T}` inside a pattern splices another type — a string-shaped
    // T (pattern, string literal, union of those) as its regular language,
    // an integer-shaped T (int literal, int range, union) as the decimal
    // representations of its members
    fn expand_pattern(self: &Rc<Env>, re: &str) -> Result<String, String> {
        let hole: &Regex = &PATTERN_HOLE;
        let mut out = String::new();
        let mut last = 0;
        for m in hole.captures_iter(re) {
            let whole = m.get(0).unwrap();
            out.push_str(&re[last..whole.start()]);
            last = whole.end();
            let text = m.get(1).unwrap().as_str().trim().to_string();
            // the spliced type: a union of string literals, int literals, int
            // ranges, and named types — the type-expression subset that fits
            // inside a pattern token
            let arms: Vec<String> = text.split('|').map(|a| a.trim().to_string()).collect();
            let mut frags: Vec<String> = vec![];
            let str_lit: &Regex = &PATTERN_STR_LIT;
            let int_range: &Regex = &PATTERN_INT_RANGE;
            let int_lit: &Regex = &PATTERN_INT_LIT;
            let ident: &Regex = &PATTERN_IDENT;
            for arm in &arms {
                if str_lit.is_match(arm) {
                    let v = crate::parse::json_unquote(arm)?;
                    frags.push(self.pattern_fragment(&ty(RTk::Lit(Value::Str(v.into()))), &text)?);
                    continue;
                }
                if let Some(c) = int_range.captures(arm) {
                    let lo = c[1].parse::<BigInt>().map_err(|e| e.to_string())?;
                    let hi = c[3].parse::<BigInt>().map_err(|e| e.to_string())?;
                    let rt = ty(RTk::Range {
                        lo: Value::Int(Num::from(lo)),
                        hi: Value::Int(Num::from(hi)),
                        excl: &c[2] == "<",
                        base: "int".into(),
                    });
                    frags.push(self.pattern_fragment(&rt, &text)?);
                    continue;
                }
                if int_lit.is_match(arm) {
                    let v = arm.parse::<BigInt>().map_err(|e| e.to_string())?;
                    frags.push(
                        self.pattern_fragment(&ty(RTk::Lit(Value::Int(Num::from(v)))), &text)?,
                    );
                    continue;
                }
                if !ident.is_match(arm) {
                    return Err(format!(
                        "pattern interpolation of {text}: not a type (§3.6)"
                    ));
                }
                if self.pattern_visiting.borrow().iter().any(|v| v == arm) {
                    return Err(format!("pattern interpolation of {arm} is circular"));
                }
                self.pattern_visiting.borrow_mut().push(arm.clone());
                let resolved = self.resolve(
                    &TypeAst::Named {
                        name: arm.clone(),
                        args: vec![],
                        preds: None,
                        ext: None,
                        loc: None,
                    },
                    None,
                );
                self.pattern_visiting.borrow_mut().retain(|v| v != arm);
                let rt = match resolved {
                    Ok(rt) => rt,
                    Err(e) => {
                        if e.starts_with("unknown type") {
                            return Err(format!("pattern interpolation of {arm}: unknown type"));
                        }
                        return Err(e);
                    }
                };
                frags.push(self.pattern_fragment(&rt, arm)?);
            }
            if frags.len() == 1 {
                out.push_str(&frags[0]);
            } else {
                out.push_str(&format!("(?:{})", frags.join("|")));
            }
        }
        out.push_str(&re[last..]);
        Ok(out)
    }
    fn pattern_fragment(self: &Rc<Env>, rt: &RT, name: &str) -> Result<String, String> {
        let esc = |s: &str| -> String {
            let mut o = String::with_capacity(s.len());
            for c in s.chars() {
                if ".*+?^${}()|[]\\/".contains(c) {
                    o.push('\\');
                }
                o.push(c);
            }
            o
        };
        let bad = || {
            Err(format!("pattern interpolation of {name}: type is neither string- nor integer-shaped (§3.6)"))
        };
        match &rt.k {
            RTk::Pattern { src, .. } => Ok(format!("(?:{src})")),
            RTk::Lit(Value::Str(s)) => Ok(esc(s)),
            RTk::Lit(Value::Int(i)) => Ok(i.to_string()),
            RTk::Lit(_) => bad(),
            RTk::Range { lo, hi, excl, base } => {
                let (Value::Int(lo), Value::Int(hi)) = (lo, hi) else {
                    return bad();
                };
                if base != "int" {
                    return bad();
                }
                let hi = if *excl { hi - 1 } else { hi.clone() };
                if &hi - lo >= Num::from(65536) {
                    return Err(format!(
                        "pattern interpolation of {name}: range too large (limit 65536 values)"
                    ));
                }
                let mut alts: Vec<String> = vec![];
                let mut v = lo.clone();
                while v <= hi {
                    alts.push(v.to_string());
                    v += 1;
                }
                Ok(format!("(?:{})", alts.join("|")))
            }
            RTk::Union(arms) => {
                let parts = arms
                    .borrow()
                    .iter()
                    .map(|a| self.pattern_fragment(a, name))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(format!("(?:{})", parts.join("|")))
            }
            RTk::Pred { base, .. } => self.pattern_fragment(base, name),
            RTk::Prim(n) if n == "string" => Ok(".*".into()),
            RTk::Prim(n) if n == "int" => Ok("-?[0-9]+".into()),
            _ => bad(),
        }
    }

    // §3.15 generics
    fn instantiate(
        self: &Rc<Env>,
        name: &str,
        args: &[TypeAst],
        decl: &Rc<TypeEntry>,
    ) -> Result<RT, String> {
        let ps = &decl.params;
        if args.len() != ps.len() {
            return Err(format!(
                "generic arity: {name} expects {} argument(s), got {}",
                ps.len(),
                args.len()
            ));
        }
        let mut types: HashMap<String, TypeAst> = HashMap::new();
        let mut values: HashMap<String, Value> = HashMap::new();
        let mut label = Vec::new();
        for (p, a) in ps.iter().zip(args) {
            if let Some(pty) = &p.ty {
                let v = match a {
                    TypeAst::Lit { v, .. } => v.clone(),
                    TypeAst::Named {
                        name: an,
                        args: aa,
                        ext: None,
                        preds: None,
                        ..
                    } if aa.is_empty() => {
                        let v = self.const_num(&Value::Str(an.clone().into()));
                        if matches!(v, Value::Str(_)) {
                            return Err(format!(
                                "non-constant value argument {an} for {} of {name}",
                                p.name
                            ));
                        }
                        v
                    }
                    _ => {
                        return Err(format!(
                            "generic arity: parameter {} of {name} takes a constant value",
                            p.name
                        ))
                    }
                };
                let bound = self.resolve(&subst_type(pty, &types, &values), None)?;
                if !crate::subsume::subsumes(self, &ty(RTk::Lit(v.clone())), &bound) {
                    return Err(format!(
                        "value argument {v:?} outside parameter {}'s type in {name}",
                        p.name
                    ));
                }
                label.push(format!("{v:?}"));
                values.insert(p.name.clone(), v);
            } else {
                label.push(match a {
                    TypeAst::Named { name, .. } | TypeAst::Prim { name, .. } => name.clone(),
                    _ => "type".into(),
                });
                types.insert(p.name.clone(), a.clone());
            }
        }
        let key = format!(
            "{name}<{}>",
            args.iter().map(type_key).collect::<Vec<_>>().join(",")
        );
        if let Some(rt) = self.type_memo.borrow().get(&key).cloned() {
            return Ok(rt);
        }
        let shown = format!("{name}<{}>", label.join(", "));
        let body = subst_type(&decl.ast, &types, &values);
        let rt = match &body {
            TypeAst::Record { members, open, .. } => {
                let rt = ty(RTk::Rec(rec_type(*open)));
                *rt.name.borrow_mut() = Some(shown);
                *rt.tail.borrow_mut() = decl.tail.clone();
                self.type_memo.borrow_mut().insert(key.clone(), rt.clone());
                if let Err(e) = self.fill_record(&rt, members) {
                    self.type_memo.borrow_mut().remove(&key);
                    return Err(e);
                }
                rt
            }
            other => {
                let rt = self.resolve(other, Some(&shown))?;
                if matches!(rt.k, RTk::Rec(_) | RTk::Union(_)) {
                    *rt.name.borrow_mut() = Some(shown);
                }
                if rt.tail.borrow().is_none() {
                    *rt.tail.borrow_mut() = decl.tail.clone();
                }
                self.type_memo.borrow_mut().insert(key, rt.clone());
                rt
            }
        };
        Ok(rt)
    }

    fn fill_record(self: &Rc<Env>, rt: &RT, members: &[MemberAst]) -> Result<(), String> {
        let RTk::Rec(r) = &rt.k else { return Ok(()) };
        let origin = rt.name.borrow().clone();
        r.filling.set(true);
        for m in members {
            match m {
                MemberAst::Value {
                    name,
                    opt,
                    ty: t,
                    dflt,
                    ..
                } => Rc::make_mut(&mut r.members.borrow_mut()).push(Member {
                    kind: if dflt.is_some() {
                        MKind::Dflt
                    } else if *opt {
                        MKind::Opt
                    } else {
                        MKind::Req
                    },
                    name: name.clone(),
                    hidden: false,
                    ty: Some(self.resolve(t, None)?),
                    conj: None,
                    dflt: dflt.clone(),
                    expr: None,
                    menv: Some(self.clone()),
                }),
                MemberAst::Derived {
                    name,
                    ty: t,
                    expr,
                    hidden,
                    ..
                } => Rc::make_mut(&mut r.members.borrow_mut()).push(Member {
                    kind: MKind::Der,
                    name: name.clone(),
                    hidden: *hidden,
                    ty: match t {
                        Some(t) => Some(self.resolve(t, None)?),
                        None => None,
                    },
                    conj: None,
                    dflt: None,
                    expr: Some(expr.clone()),
                    menv: Some(self.clone()),
                }),
                MemberAst::Assert {
                    name, cond, tail, ..
                } => r.asserts.borrow_mut().push(AssertItem {
                    when: false,
                    name: name.clone(),
                    cond: cond.clone(),
                    tail: tail.clone(),
                    body: vec![],
                    origin: origin.clone(),
                    menv: Some(self.clone()),
                }),
                MemberAst::When { cond, body, .. } => r.asserts.borrow_mut().push(AssertItem {
                    when: true,
                    name: String::new(),
                    cond: cond.clone(),
                    tail: None,
                    body: body.clone(),
                    origin: origin.clone(),
                    menv: Some(self.clone()),
                }),
                MemberAst::Context {
                    variable, ty: t, ..
                } => r
                    .ctx_decls
                    .borrow_mut()
                    .push((variable.clone(), self.resolve(t, None)?)),
            }
        }
        self.complete_record(rt);
        Ok(())
    }

    fn merge_isect(&self, arms: &[RT], name: Option<&str>) -> RT {
        let mut members: Vec<Member> = vec![];
        let mut asserts: Vec<AssertItem> = vec![];
        let mut open = true;
        for a in arms {
            let RTk::Rec(r) = &a.k else { continue };
            open = open && r.open.get();
            for m in r.members.borrow().iter() {
                if let Some(i) = members.iter().position(|x| x.name == m.name) {
                    let prev = members[i].clone();
                    let mut conj = prev
                        .conj
                        .clone()
                        .unwrap_or_else(|| prev.ty.iter().cloned().collect());
                    if let Some(t) = &m.ty {
                        conj.push(t.clone());
                    }
                    members[i] = Member {
                        conj: Some(conj),
                        kind: if m.kind == MKind::Req {
                            MKind::Req
                        } else {
                            prev.kind
                        },
                        ..prev
                    };
                } else {
                    members.push(m.clone());
                }
            }
            asserts.extend(r.asserts.borrow().iter().map(|x| AssertItem {
                origin: x.origin.clone().or_else(|| a.name.borrow().clone()),
                ..x.clone()
            }));
        }
        let rec = rec_type(open);
        *rec.members.borrow_mut() = Rc::new(members);
        *rec.asserts.borrow_mut() = asserts;
        let rt = ty(RTk::Rec(rec));
        *rt.name.borrow_mut() = name.map(|s| s.to_string());
        rt
    }
}

fn type_key(t: &TypeAst) -> String {
    match t {
        TypeAst::Prim { name: n, .. } => format!("p:{n}"),
        TypeAst::Lit { v, .. } => format!("l:{v:?}"),
        TypeAst::Named { name, args, .. } => format!(
            "n:{name}<{}>",
            args.iter().map(type_key).collect::<Vec<_>>().join(",")
        ),
        TypeAst::Range { lo, hi, excl, .. } => format!("r:{lo:?}..{excl}{hi:?}"),
        TypeAst::Array { elem, lo, hi, .. } => format!("a:{}[{lo:?},{hi:?}]", type_key(elem)),
        TypeAst::Union { arms: a, .. } => {
            format!("u:{}", a.iter().map(type_key).collect::<Vec<_>>().join("|"))
        }
        TypeAst::Isect { arms: a, .. } => {
            format!("i:{}", a.iter().map(type_key).collect::<Vec<_>>().join("&"))
        }
        TypeAst::Map { key, val, .. } => format!("m:{}:{}", type_key(key), type_key(val)),
        TypeAst::Pattern { re: p, .. } => format!("pat:{p}"),
        TypeAst::Record { members, .. } => format!("rec:{}", members.len()),
        TypeAst::Func { params, ret, .. } => format!("f:{}->{}", params.len(), type_key(ret)),
    }
}

// ---------------- generic substitution ----------------
/// Substitute a generic type's parameters (§3.15).
pub fn subst_type(
    ast: &TypeAst,
    types: &HashMap<String, TypeAst>,
    values: &HashMap<String, Value>,
) -> TypeAst {
    let t = |a: &TypeAst| subst_type(a, types, values);
    match ast {
        TypeAst::Named {
            name,
            args,
            preds,
            ext,
            loc,
        } => {
            let plain = args.is_empty() && ext.is_none() && preds.is_none();
            if plain {
                if let Some(x) = types.get(name) {
                    return x.clone();
                }
                if let Some(v) = values.get(name) {
                    return TypeAst::Lit {
                        v: v.clone(),
                        loc: *loc,
                    };
                }
            }
            TypeAst::Named {
                name: name.clone(),
                args: args.iter().map(t).collect(),
                preds: preds
                    .as_ref()
                    .map(|ps| ps.iter().map(|p| subst_expr(p, values)).collect()),
                ext: ext.as_ref().map(|e| Box::new(t(e))),
                loc: *loc,
            }
        }
        TypeAst::Range { lo, hi, excl, loc } => {
            let sub = |v: &Value| match v {
                Value::Str(s) if values.contains_key(&**s) => values[&**s].clone(),
                other => other.clone(),
            };
            TypeAst::Range {
                lo: sub(lo),
                hi: sub(hi),
                excl: *excl,
                loc: *loc,
            }
        }
        TypeAst::Array {
            elem,
            lo,
            hi,
            excl,
            loc,
        } => {
            let sub = |v: &Value| match v {
                Value::Str(s) if values.contains_key(&**s) => values[&**s].clone(),
                other => other.clone(),
            };
            TypeAst::Array {
                elem: Box::new(t(elem)),
                lo: lo.as_ref().map(sub),
                hi: hi.as_ref().map(sub),
                excl: *excl,
                loc: *loc,
            }
        }
        TypeAst::Record { members, open, loc } => TypeAst::Record {
            members: members
                .iter()
                .map(|m| subst_member(m, types, values))
                .collect(),
            open: *open,
            loc: *loc,
        },
        TypeAst::Map { key, val, loc } => TypeAst::Map {
            key: Box::new(t(key)),
            val: Box::new(t(val)),
            loc: *loc,
        },
        TypeAst::Union { arms: a, loc } => TypeAst::Union {
            arms: a.iter().map(t).collect(),
            loc: *loc,
        },
        TypeAst::Isect { arms: a, loc } => TypeAst::Isect {
            arms: a.iter().map(t).collect(),
            loc: *loc,
        },
        TypeAst::Func { params, ret, loc } => TypeAst::Func {
            params: params.iter().map(t).collect(),
            ret: Box::new(t(ret)),
            loc: *loc,
        },
        other => other.clone(),
    }
}
fn subst_member(
    m: &MemberAst,
    types: &HashMap<String, TypeAst>,
    values: &HashMap<String, Value>,
) -> MemberAst {
    let t = |a: &TypeAst| subst_type(a, types, values);
    match m {
        MemberAst::Value {
            name,
            opt,
            ty,
            dflt,
            annotations,
            loc,
        } => MemberAst::Value {
            name: name.clone(),
            opt: *opt,
            ty: t(ty),
            dflt: dflt.as_ref().map(|d| subst_expr(d, values)),
            annotations: annotations.clone(),
            loc: *loc,
        },
        MemberAst::Derived {
            name,
            ty,
            expr,
            hidden,
            annotations,
            loc,
        } => MemberAst::Derived {
            name: name.clone(),
            ty: ty.as_ref().map(t),
            expr: subst_expr(expr, values),
            hidden: *hidden,
            annotations: annotations.clone(),
            loc: *loc,
        },
        MemberAst::Context {
            variable,
            ty,
            annotations,
            loc,
        } => MemberAst::Context {
            variable: variable.clone(),
            ty: t(ty),
            annotations: annotations.clone(),
            loc: *loc,
        },
        MemberAst::Assert {
            name,
            cond,
            tail,
            annotations,
            loc,
        } => MemberAst::Assert {
            name: name.clone(),
            cond: subst_expr(cond, values),
            tail: tail.clone(),
            annotations: annotations.clone(),
            loc: *loc,
        },
        MemberAst::When {
            cond,
            body,
            annotations,
            loc,
        } => MemberAst::When {
            cond: subst_expr(cond, values),
            body: body
                .iter()
                .map(|b| subst_member(b, types, values))
                .collect(),
            annotations: annotations.clone(),
            loc: *loc,
        },
    }
}
/// Substitute values for names in an expression.
pub fn subst_expr(e: &Rc<Expr>, values: &HashMap<String, Value>) -> Rc<Expr> {
    if values.is_empty() {
        return e.clone();
    }
    let s = |x: &Rc<Expr>| subst_expr(x, values);
    let cls = |c: &ForClause| ForClause {
        v: c.v.clone(),
        iter: s(&c.iter),
        filters: c.filters.iter().map(s).collect(),
    };
    let out = Rc::new(match &**e {
        Expr::Name(n) if values.contains_key(n) => Expr::Lit(values[n].clone()),
        Expr::Template(parts) => Expr::Template(
            parts
                .iter()
                .map(|p| match p {
                    TPart::Expr(x) => TPart::Expr(s(x)),
                    other => other.clone(),
                })
                .collect(),
        ),
        Expr::Obj(es) => Expr::Obj(es.iter().map(|(k, v)| (k.clone(), s(v))).collect()),
        Expr::Arr(items) => Expr::Arr(items.iter().map(|(sp, v)| (*sp, s(v))).collect()),
        Expr::Comp { head, clauses } => Expr::Comp {
            head: s(head),
            clauses: clauses.iter().map(cls).collect(),
        },
        Expr::MapComp { key, val, clauses } => Expr::MapComp {
            key: s(key),
            val: s(val),
            clauses: clauses.iter().map(cls).collect(),
        },
        Expr::Bin { op, l, r } => Expr::Bin {
            op: op.clone(),
            l: s(l),
            r: s(r),
        },
        Expr::Un { op, x } => Expr::Un {
            op: op.clone(),
            x: s(x),
        },
        Expr::Paren(x) => Expr::Paren(s(x)),
        Expr::If { c, t, f } => Expr::If {
            c: s(c),
            t: s(t),
            f: s(f),
        },
        Expr::Lambda { params, body } => Expr::Lambda {
            params: params.clone(),
            body: s(body),
        },
        Expr::Call { fun, args } => Expr::Call {
            fun: s(fun),
            args: args.iter().map(s).collect(),
        },
        Expr::Member { x, name, safe } => Expr::Member {
            x: s(x),
            name: name.clone(),
            safe: *safe,
        },
        Expr::Index { x, i } => Expr::Index { x: s(x), i: s(i) },
        Expr::With { base, patch } => Expr::With {
            base: s(base),
            patch: s(patch),
        },
        Expr::Match { subject, arms } => Expr::Match {
            subject: s(subject),
            arms: arms
                .iter()
                .map(|a| MatchArm {
                    v: a.v.clone(),
                    ty: a.ty.clone(),
                    body: s(&a.body),
                })
                .collect(),
        },
        other => other.clone(),
    });
    // a substituted node keeps the source range of the node it replaces (the reference copies `loc`)
    if let Some(l) = expr_loc(e) {
        set_expr_loc(&out, l);
    }
    out
}

// ---------------- helpers ----------------
// ---------------- patterns: the portable core (§3.6) ----------------
// A pattern body is validated against the specification's regular-
// expression core with one fixed set of messages, so every implementation
// reports the same text whatever engine runs the accepted patterns.
// Returns the reason a body is outside the core, or None when it is inside.
const PATTERN_PUNCT: &str = "\\/.*+?()[]{}|^$-";
fn pattern_escape(cs: &[char], i: &mut usize) -> Result<i64, String> {
    if *i + 1 >= cs.len() {
        return Err("trailing backslash".into());
    }
    let e = cs[*i + 1];
    *i += 2;
    if "dwsDWS".contains(e) {
        return Ok(-1);
    }
    match e {
        'n' => return Ok(10),
        't' => return Ok(9),
        'r' => return Ok(13),
        _ => {}
    }
    if PATTERN_PUNCT.contains(e) {
        return Ok(e as i64);
    }
    if e.is_ascii_digit() {
        return Err(format!("backreference \\{e} is not supported"));
    }
    Err(format!("unsupported escape \\{e}"))
}
/// Why a pattern body is outside the §3.6 core (E4119), when it is.
pub fn pattern_error(src: &str) -> Option<String> {
    let cs: Vec<char> = src.chars().collect();
    let n = cs.len();
    let (mut i, mut depth, mut can_repeat) = (0usize, 0i32, false);
    while i < n {
        match cs[i] {
            '\\' => {
                if let Err(r) = pattern_escape(&cs, &mut i) {
                    return Some(r);
                }
                can_repeat = true;
            }
            '[' => {
                i += 1;
                if i < n && cs[i] == '^' {
                    i += 1;
                }
                let mut items = 0;
                loop {
                    if i >= n {
                        return Some("unterminated character class".into());
                    }
                    if cs[i] == ']' {
                        i += 1;
                        break;
                    }
                    let lo = if cs[i] == '\\' {
                        match pattern_escape(&cs, &mut i) {
                            Ok(v) => v,
                            Err(r) => return Some(r),
                        }
                    } else {
                        let v = cs[i] as i64;
                        i += 1;
                        v
                    };
                    if i < n && cs[i] == '-' && i + 1 < n && cs[i + 1] != ']' {
                        i += 1;
                        let hi = if cs[i] == '\\' {
                            match pattern_escape(&cs, &mut i) {
                                Ok(v) => v,
                                Err(r) => return Some(r),
                            }
                        } else {
                            let v = cs[i] as i64;
                            i += 1;
                            v
                        };
                        if lo < 0 || hi < 0 || lo > hi {
                            return Some("invalid range in character class".into());
                        }
                    }
                    items += 1;
                }
                if items == 0 {
                    return Some("empty character class".into());
                }
                can_repeat = true;
            }
            ']' => return Some("unbalanced bracket".into()),
            '(' => {
                i += 1;
                if i < n && cs[i] == '?' {
                    if i + 1 < n && cs[i + 1] == ':' {
                        i += 2;
                    } else {
                        return Some("unsupported construct (?".into());
                    }
                }
                depth += 1;
                can_repeat = false;
            }
            ')' => {
                if depth == 0 {
                    return Some("unbalanced parenthesis".into());
                }
                depth -= 1;
                i += 1;
                can_repeat = true;
            }
            '|' => {
                i += 1;
                can_repeat = false;
            }
            '*' | '+' | '?' => {
                if !can_repeat {
                    return Some("nothing to repeat".into());
                }
                i += 1;
                can_repeat = false;
            }
            '{' => {
                if !can_repeat {
                    return Some("nothing to repeat".into());
                }
                let mut j = i + 1;
                let start = j;
                while j < n && cs[j].is_ascii_digit() {
                    j += 1;
                }
                if j == start {
                    return Some("malformed repetition".into());
                }
                let m: String = cs[start..j].iter().collect();
                let mut hi: Option<String> = None;
                if j < n && cs[j] == ',' {
                    j += 1;
                    let s2 = j;
                    while j < n && cs[j].is_ascii_digit() {
                        j += 1;
                    }
                    if j > s2 {
                        hi = Some(cs[s2..j].iter().collect());
                    }
                }
                if j >= n || cs[j] != '}' {
                    return Some("malformed repetition".into());
                }
                if let Some(h) = hi {
                    if h.parse::<BigInt>().unwrap_or_default()
                        < m.parse::<BigInt>().unwrap_or_default()
                    {
                        return Some("malformed repetition".into());
                    }
                }
                i = j + 1;
                can_repeat = false;
            }
            '}' => return Some("malformed repetition".into()),
            '^' | '$' => {
                i += 1;
                can_repeat = false;
            }
            _ => {
                i += 1;
                can_repeat = true;
            }
        }
    }
    if depth > 0 {
        Some("unbalanced parenthesis".into())
    } else {
        None
    }
}
/// Compile a pattern body to a regular expression.
pub fn compile_pattern(src: &str) -> Result<Regex, String> {
    Regex::new(&format!("^(?:{src})$")).map_err(|e| e.to_string())
}

/// A canonical path's text, relative to `rel_root` (`$.…`) when given.
pub fn path_str(segs: &[Seg], rel_root: Option<&str>) -> String {
    path_str_iter(segs.iter(), rel_root)
}

/// Format borrowed canonical segments without requiring a contiguous vector.
pub fn path_str_iter<'a>(
    segs: impl IntoIterator<Item = &'a Seg>,
    rel_root: Option<&str>,
) -> String {
    let mut out = String::new();
    for (i, s) in segs.into_iter().enumerate() {
        write_path_segment(&mut out, s, i == 0, rel_root);
    }
    out
}

/// Format once and retain UTF-8 byte boundaries for each complete path prefix.
/// Offsets follow segments, including roots whose bare text contains delimiters.
/// The spelling is appended to `text` and the prefix lengths, counted from
/// where it starts, to `ends`: many paths without an allocation each. `None`
/// when a length outgrows 32 bits.
pub(crate) fn path_str_ends_into(
    segs: &[Seg],
    text: &mut String,
    ends: &mut Vec<u32>,
) -> Option<()> {
    let start = text.len();
    for (i, s) in segs.iter().enumerate() {
        write_path_segment(text, s, i == 0, None);
        ends.push(u32::try_from(text.len() - start).ok()?);
    }
    Some(())
}

fn write_path_segment(out: &mut String, s: &Seg, first: bool, rel_root: Option<&str>) {
    use std::fmt::Write;
    // The root segment is bare; later segments use canonical member/bracket
    // spelling. Both ordinary formatting and prefix indexing share this writer.
    if first {
        match s {
            Seg::Name(n) | Seg::Key(n) => {
                if rel_root == Some(&**n) {
                    out.push('$');
                } else {
                    out.push_str(n);
                }
            }
            Seg::Idx(k) => {
                let t = k.to_string();
                if rel_root == Some(t.as_str()) {
                    out.push('$');
                } else {
                    out.push_str(&t);
                }
            }
        }
        return;
    }
    match s {
        Seg::Idx(k) => {
            let _ = write!(out, "[{k}]");
        }
        Seg::Key(n) => {
            let _ = write!(out, "[{}]", json_str(n));
        }
        Seg::Name(n) if dot_spellable(n) => {
            out.push('.');
            out.push_str(n);
        }
        Seg::Name(n) => {
            let _ = write!(out, "[{}]", json_str(n));
        }
    }
}

/// A path string from a document: `.name` is a member, `["…"]` a bracketed
/// segment (a map key, or a member the dot cannot spell — the canonical walk,
/// §7.5, decides which is legal where), `[n]` an index.
pub fn parse_path(s: &str, root_name: &str) -> R<SegPath> {
    let id_re = Regex::new(r"^[_A-Za-z][_A-Za-z0-9]*").unwrap();
    let mut segs = vec![];
    let mut i = if s.starts_with('$') {
        segs.push(Seg::Name(Rc::from(root_name.to_string())));
        1
    } else {
        let m = id_re
            .find(s)
            .ok_or(())
            .or_else(|_| err(format!("bad path {s}")))?;
        segs.push(Seg::Name(Rc::from(m.as_str())));
        m.end()
    };
    while i < s.len() {
        let rest = &s[i..];
        if let Some(r) = rest.strip_prefix('.') {
            let m = id_re
                .find(r)
                .ok_or(())
                .or_else(|_| err(format!("bad path {s}")))?;
            segs.push(Seg::Name(Rc::from(m.as_str())));
            i += 1 + m.end();
        } else if rest.starts_with('[') {
            let j = rest
                .find(']')
                .ok_or(())
                .or_else(|_| err(format!("bad path {s}")))?;
            let inner = &rest[1..j];
            if inner.starts_with('"') {
                segs.push(Seg::Key(Rc::from(
                    crate::parse::json_unquote(inner).unwrap_or_default(),
                )));
            } else {
                segs.push(Seg::Idx(inner.parse().unwrap_or(0)));
            }
            i += j + 1;
        } else {
            return err(format!("bad path {s}"));
        }
    }
    Ok(segs)
}

/// Canonical path order (§7.2): segment-wise, indices numerically, names and
/// keys lexicographically, a prefix first.
pub fn cmp_path(a: &[Seg], b: &[Seg]) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    for (x, y) in a.iter().zip(b) {
        // by the segment's path text (§7.2), as `seg_text` spells it, but
        // without allocating a String per comparison (F21): two name/key
        // segments compare their `Rc<str>` directly, two indices compare
        // numerically; only a rare index-vs-name pair falls back to the text
        let ord = match (x, y) {
            (Seg::Idx(i), Seg::Idx(j)) => i.cmp(j),
            (Seg::Name(p) | Seg::Key(p), Seg::Name(q) | Seg::Key(q)) => (**p).cmp(&**q),
            _ => seg_text(x).cmp(&seg_text(y)),
        };
        if ord != Ordering::Equal {
            return ord;
        }
    }
    a.len().cmp(&b.len())
}

/// Structural equality of two values (§4.5).
pub fn value_eq(a: &Value, b: &Value) -> bool {
    // Only reference equality uses places. Structural comparisons must not
    // export retained container paths that they will immediately discard.
    if matches!(a, Value::Ref(_)) || matches!(b, Value::Ref(_)) {
        let (pa, pb) = (a.place(), b.place());
        if let (Some(pa), Some(pb)) = (&pa, &pb) {
            return cmp_path(pa, pb) == std::cmp::Ordering::Equal;
        }
    }
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x == y,
        (Value::Float(x), Value::Float(y)) => x == y,
        (Value::Str(x), Value::Str(y)) => x == y,
        (Value::Bool(x), Value::Bool(y)) => x == y,
        (Value::Null, Value::Null) => true,
        // two unforced slots compare equal, as in the reference (undefined === undefined)
        (Value::Undef, Value::Undef) => true,
        (Value::Q(a), Value::Q(b)) => a.dim == b.dim && a.value == b.value,
        (Value::Arr(x), Value::Arr(y)) => {
            let (x, y) = (x.borrow(), y.borrow());
            x.items.len() == y.items.len()
                && x.items.iter().zip(&y.items).all(|(p, q)| value_eq(p, q))
        }
        (Value::Map(x), Value::Map(y)) => {
            let (x, y) = (x.borrow(), y.borrow());
            x.entries.len() == y.entries.len()
                && x.entries
                    .iter()
                    .all(|(k, v)| y.get(k).map(|w| value_eq(v, w)).unwrap_or(false))
        }
        (Value::Rec(x), Value::Rec(y)) => {
            if Rc::ptr_eq(x, y) {
                return true;
            }
            let (x, y) = (x.borrow(), y.borrow());
            for (n, s) in &x.slots {
                if s.hidden {
                    continue; // a hidden member is not part of the value (D34)
                }
                let v1 = if s.state == SlotState::Absent {
                    Value::Absent
                } else {
                    s.value.clone()
                };
                let v2 = match y.slot(n) {
                    Some(s2) if s2.state != SlotState::Absent => s2.value.clone(),
                    _ => Value::Absent,
                };
                match (&v1, &v2) {
                    (Value::Absent, Value::Absent) => continue,
                    (Value::Absent, _) | (_, Value::Absent) => return false,
                    _ => {
                        if !value_eq(&v1, &v2) {
                            return false;
                        }
                    }
                }
            }
            true
        }
        _ => false,
    }
}

// ---------------- lexical JSON (int/float by lexeme) ----------------
/// Read a JSON document (§10.2): objects keep their key order, integers stay
/// exact; trailing characters are an error.
pub fn read_json(src: &str) -> R<Value> {
    let b = src.as_bytes();
    let mut i = 0usize;
    fn ws(b: &[u8], i: &mut usize) {
        while *i < b.len() && matches!(b[*i], b' ' | b'\t' | b'\r' | b'\n') {
            *i += 1;
        }
    }
    fn string(src: &str, b: &[u8], i: &mut usize) -> R<String> {
        let mut j = *i + 1;
        let mut out = String::new();
        while j < b.len() && b[j] != b'"' {
            if b[j] == b'\\' {
                let e = b[j + 1] as char;
                match e {
                    'n' => out.push('\n'),
                    't' => out.push('\t'),
                    'r' => out.push('\r'),
                    'b' => out.push('\u{8}'),
                    'f' => out.push('\u{c}'),
                    'u' => {
                        let cp = u32::from_str_radix(&src[j + 2..j + 6], 16).unwrap_or(0xfffd);
                        out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
                        j += 4;
                    }
                    other => out.push(other),
                }
                j += 2;
            } else {
                let ch = src[j..].chars().next().unwrap();
                out.push(ch);
                j += ch.len_utf8();
            }
        }
        *i = j + 1;
        Ok(out)
    }
    fn val(src: &str, b: &[u8], i: &mut usize) -> R<Value> {
        ws(b, i);
        if *i >= b.len() {
            return err("bad JSON: unexpected end");
        }
        match b[*i] {
            b'{' => {
                *i += 1;
                let mut entries = vec![];
                ws(b, i);
                if b[*i] == b'}' {
                    *i += 1;
                    return Ok(Value::JObj(Rc::new(entries)));
                }
                loop {
                    ws(b, i);
                    let k = string(src, b, i)?;
                    ws(b, i);
                    *i += 1;
                    let v = val(src, b, i)?;
                    entries.push((k, v));
                    ws(b, i);
                    if b[*i] == b',' {
                        *i += 1;
                        continue;
                    }
                    *i += 1;
                    return Ok(Value::JObj(Rc::new(entries)));
                }
            }
            b'[' => {
                *i += 1;
                let mut items = vec![];
                ws(b, i);
                if b[*i] == b']' {
                    *i += 1;
                    return Ok(Value::JArr(Rc::new(items)));
                }
                loop {
                    items.push(val(src, b, i)?);
                    ws(b, i);
                    if b[*i] == b',' {
                        *i += 1;
                        continue;
                    }
                    *i += 1;
                    return Ok(Value::JArr(Rc::new(items)));
                }
            }
            b'"' => Ok(Value::Str(string(src, b, i)?.into())),
            _ => {
                let rest = &src[*i..];
                if rest.starts_with("true") {
                    *i += 4;
                    return Ok(Value::Bool(true));
                }
                if rest.starts_with("false") {
                    *i += 5;
                    return Ok(Value::Bool(false));
                }
                if rest.starts_with("null") {
                    *i += 4;
                    return Ok(Value::Null);
                }
                static NUMBER: LazyLock<Regex> = LazyLock::new(|| {
                    Regex::new(r"^-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?").unwrap()
                });
                let m = NUMBER
                    .captures(rest)
                    .ok_or(())
                    .or_else(|_| err(format!("bad JSON at {i}")))?;
                let whole = m.get(0).unwrap().as_str();
                *i += whole.len();
                if m.get(1).is_some() || m.get(2).is_some() {
                    Ok(Value::Float(whole.parse::<f64>().unwrap_or(0.0)))
                } else {
                    Ok(Value::Int(Num::parse_str(whole).unwrap_or_else(Num::zero)))
                }
            }
        }
    }
    let v = val(src, b, &mut i)?;
    ws(b, &mut i);
    if i < b.len() {
        return err("bad JSON: trailing characters");
    }
    Ok(v)
}

// ---------------- JS-compatible number printing ----------------
/// ECMAScript Number::toString for finite doubles (shortest round trip)
pub fn js_num_str(x: f64) -> String {
    if x == 0.0 {
        return "0".into();
    }
    let sci = format!("{:e}", x.abs());
    let (mant, exp) = sci.split_once('e').unwrap();
    let exp: i32 = exp.parse().unwrap();
    let digits: String = mant.chars().filter(|c| *c != '.').collect();
    let digits = digits.trim_end_matches('0');
    let digits = if digits.is_empty() { "0" } else { digits };
    let k = digits.len() as i32;
    let n = exp + 1;
    let body = if k <= n && n <= 21 {
        format!("{digits}{}", "0".repeat((n - k) as usize))
    } else if 0 < n && n <= 21 {
        format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
    } else if -6 < n && n <= 0 {
        format!("0.{}{digits}", "0".repeat((-n) as usize))
    } else {
        let e = n - 1;
        let mant = if k > 1 {
            format!("{}.{}", &digits[..1], &digits[1..])
        } else {
            digits.to_string()
        };
        format!("{mant}e{}{}", if e > 0 { "+" } else { "-" }, e.abs())
    };
    if x < 0.0 {
        format!("-{body}")
    } else {
        body
    }
}

/// A string as JSON text, escaped.
pub fn json_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    write_json_str(&mut out, s);
    out
}

/// Append JSON string text without allocating an intermediate quoted string.
pub(crate) fn write_json_str(out: &mut String, s: &str) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push('"');
    let mut start = 0;
    for (i, byte) in s.bytes().enumerate() {
        if byte >= 0x20 && byte != b'"' && byte != b'\\' {
            continue;
        }
        // Escapes occur only at ASCII bytes, hence at UTF-8 boundaries.
        // Copy the intervening text as a slice, including non-ASCII scalars.
        out.push_str(&s[start..i]);
        match byte {
            b'"' => out.push_str("\\\""),
            b'\\' => out.push_str("\\\\"),
            b'\n' => out.push_str("\\n"),
            b'\r' => out.push_str("\\r"),
            b'\t' => out.push_str("\\t"),
            8 => out.push_str("\\b"),
            12 => out.push_str("\\f"),
            _ => {
                out.push_str("\\u00");
                out.push(HEX[(byte >> 4) as usize] as char);
                out.push(HEX[(byte & 15) as usize] as char);
            }
        }
        start = i + 1;
    }
    out.push_str(&s[start..]);
    out.push('"');
}

#[cfg(test)]
#[path = "../tests/private/path_format_test.rs"]
mod path_format_tests;

#[cfg(test)]
#[path = "../tests/private/slot_compute_test.rs"]
mod slot_compute_tests;

#[cfg(test)]
#[path = "../tests/private/value_storage_test.rs"]
mod value_storage_tests;