submilli-engine 0.3.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
//! Expression inference — `infer_expr` and its many subroutines (binary,
//! unary, call, intrinsic call, coercion, toString/array.join, object
//! / array literals, field / index access, arrow). Includes the
//! `unify_returns` helper used by arrow-with-block bodies and the
//! `to_string_intrinsic_for` dispatcher used by both
//! `.toString()` and `String(x)` paths.

use crate::compiler_error::CompilerFailure;

use std::collections::{BTreeMap, BTreeSet};

use crate::{
    ArrowBody, BinOp, ChainPart, ClosureBody, Diagnostic, ExprId, ExprKind, Ident, Intrinsic,
    MangledName, MethodSig, ParamDecl, Severity, Span, Type, TypeAnnotation, TypedChainPart,
    TypedExpr, TypedExprKind, TypedParam, UnOp, ValueKind, ValueSymbol,
};

use super::assignable::TypeResolver;
use super::format_signature::SignatureKind;
use super::namespace_symbol;
use super::reserved::{is_reserved_object_field, override_field_signature, reserved_field_message};
use super::stmt::StaticWrite;
use super::value_operand::ValueOperand;
use crate::did_you_mean;
use crate::type_size::{TypeBudget, TypeTooLarge, map_children};
use crate::types::{EnumValue, LiteralF64};

use super::type_aliases::alias_ref_body;
use super::{Inferer, assignable, narrowing, object_normalization};

/// Typed field initializers and whether their own diagnostics explain an error.
pub(super) type InferredObjectFields = std::collections::BTreeMap<ExprId, (ExprId, Type, bool)>;

pub(super) struct StaticCallTarget<'a> {
    package: &'a str,
    symbol: &'a str,
    mangled: crate::MangledName,
}

/// What a use of a class's constructor does, for the help a private one gets.
#[derive(Clone, Copy)]
pub(super) enum ConstructorUse {
    New,
    Extend,
}

/// How [`Inferer::bind_param_call_args`] names the callee in its arity
/// diagnostic and which signature shape it lifts into the `help:` block.
#[derive(Clone, Copy)]
pub(super) enum CallLift<'a> {
    Constructor {
        class_ty: &'a Type,
    },
    /// A named callee — `http.get`, `Cls.make`, a top-level function.
    Function {
        name: &'a str,
    },
    /// An unnamed function-typed callee (a closure held in a field or
    /// local); lifts the anonymous `(T, U) => R` form.
    Anon {
        ty: &'a Type,
    },
    /// A method, lifted against the receiver it resolved on so interface
    /// generics render substituted.
    Method {
        receiver_ty: &'a Type,
        name: &'a str,
        sig: &'a MethodSig,
    },
}

/// A method resolved by a `Field` step of an optional chain, carried to the
/// `Call` step that follows it. The step's own type is a `Type::Function`,
/// which drops parameter names, defaults, and the rest slot's element type
/// — everything argument binding needs — so the signature travels alongside.
struct ChainMethod {
    /// The receiver the method resolved against, for the arity lift.
    receiver_ty: Type,
    /// The declaration as written, for the arity lift.
    sig: MethodSig,
    /// `sig.params` with the receiver's interface generics substituted.
    params: Vec<crate::Param>,
    /// The member name — `MethodSig` doesn't carry one.
    name: String,
    /// Where the method was named, so a reference that never gets its `Call`
    /// is reported at the member rather than at the whole chain.
    span: Span,
}

/// What a `Field` step of an optional chain resolved to.
struct ChainField {
    ty: Type,
    /// `Some` when the step lifts to `InterfaceProperty` — the mangled name
    /// of the interface or class that owns the member.
    iface: Option<crate::MangledName>,
    /// `Some` when `ty` is a *method*'s function type rather than a
    /// function-typed property's.
    method: Option<ChainMethod>,
}

impl ChainField {
    fn plain(ty: Type) -> Self {
        Self {
            ty,
            iface: None,
            method: None,
        }
    }

    fn property(ty: Type, iface: crate::MangledName) -> Self {
        Self {
            ty,
            iface: Some(iface),
            method: None,
        }
    }
}

/// Whether `expected` asks for a literal type: it is one `is_literal` accepts,
/// or a union with such a member. Decides whether a literal expression keeps
/// its literal type or widens to its primitive. Peels through aliases so
/// `type Status = "a" | "b"` and a plain `"a" | "b"` hint behave identically.
fn expects_literal(expected: Option<&Type>, is_literal: fn(&Type) -> bool) -> bool {
    match expected.map(crate::types::Type::peel) {
        Some(Type::Union(ms)) => ms.iter().any(|m| names_literal(m.peel(), is_literal)),
        Some(ty) => names_literal(ty, is_literal),
        None => false,
    }
}

/// Whether `ty` is a literal type `is_literal` accepts, counting `boolean` as
/// the `true | false` it is, as TypeScript does: `[s, true]` against
/// `[string, boolean]` is `[string, true]`.
fn names_literal(ty: &Type, is_literal: fn(&Type) -> bool) -> bool {
    is_literal(ty) || (matches!(ty, Type::Boolean) && is_literal(&Type::BooleanLiteral(true)))
}

/// Whether an object literal providing exactly `lit_names` could only be
/// constructing the variant whose fields are `fields`: every required field
/// is present and no provided field is foreign to the variant.
fn variant_matches(
    fields: &std::collections::BTreeMap<String, crate::ObjectField>,
    lit_names: &std::collections::BTreeSet<&str>,
) -> bool {
    let required_satisfied = fields
        .iter()
        .all(|(name, field)| field.optional || lit_names.contains(name.as_str()));
    let no_excess = lit_names.iter().all(|name| fields.contains_key(*name));
    required_satisfied && no_excess
}

/// Whether `ty` is a primitive or a unit type: it has no fields an object
/// literal could provide.
fn is_primitive(ty: &Type) -> bool {
    matches!(
        ty.peel(),
        Type::Null
            | Type::Undefined
            | Type::String
            | Type::Number
            | Type::Boolean
            | Type::StringLiteral(_)
            | Type::NumberLiteral(_)
            | Type::BooleanLiteral(_)
            | Type::BigInt
            | Type::BigIntLiteral(_)
    )
}

/// Whether a field typed `ty` can tell union members apart. As in tsc, it
/// must be a unit type (a literal, `boolean`, `null` or `undefined`) or a
/// union made only of them: `"a" | "b"` is a tag, `string | null` isn't.
fn is_tag_type(ty: &Type) -> bool {
    fn is_unit(ty: &Type) -> bool {
        let ty = ty.peel();
        matches!(
            ty,
            Type::StringLiteral(_)
                | Type::NumberLiteral(_)
                | Type::BooleanLiteral(_)
                | Type::Boolean
                | Type::Null
                | Type::Undefined
        ) || ty.is_enum_member()
    }
    match ty.peel() {
        Type::Union(members) => members.iter().all(is_unit),
        _ => is_unit(ty),
    }
}

/// Whether a field typed `ty` can hold `value`. A type this doesn't decide
/// holds it, so a member is ruled out only when it certainly can't.
fn tag_fits(ty: &Type, value: &narrowing::LiteralValue) -> bool {
    use narrowing::LiteralValue;
    match (ty.peel(), value) {
        (Type::Union(members), _) => members.iter().any(|m| tag_fits(m, value)),
        (Type::Null, LiteralValue::Null)
        | (Type::Undefined, LiteralValue::Undefined)
        | (Type::String, LiteralValue::String(_))
        | (Type::Number, LiteralValue::Number(_))
        | (Type::Boolean, LiteralValue::Boolean(_)) => true,
        (Type::StringLiteral(s), LiteralValue::String(v)) => s == v,
        (Type::NumberLiteral(n), LiteralValue::Number(v)) => n == v,
        (Type::BooleanLiteral(b), LiteralValue::Boolean(v)) => b == v,
        (member, _) if member.is_enum_member() => {
            LiteralValue::of_enum_member(member).as_ref() == Some(value)
        }
        (other, _) => !is_primitive(other),
    }
}

fn valid_fields_help(fields: &std::collections::BTreeMap<String, crate::ObjectField>) -> String {
    let rendered = fields
        .keys()
        .map(|name| format!("`{name}`"))
        .collect::<Vec<_>>()
        .join(", ");
    format!("valid fields: {rendered}")
}

fn excess_field_fix_help(
    field_name: &str,
    fields: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> String {
    let candidates = fields.keys().map(String::as_str);
    if let Some(suggestion) = did_you_mean::closest_match(field_name, candidates) {
        format!("remove `{field_name}` or rename it to `{suggestion}`")
    } else {
        format!("remove `{field_name}` or rename it to a valid field")
    }
}

/// Array methods that mutate the receiver. Rejected on tuple-typed and `readonly`
/// receivers: tuples are fixed-length, so mutation would break their arity and
/// per-position types, and a `readonly` array only permits reading.
fn is_mutating_array_method(name: &str) -> bool {
    matches!(
        name,
        "push"
            | "pop"
            | "shift"
            | "unshift"
            | "splice"
            | "reverse"
            | "sort"
            | "fill"
            | "copyWithin"
    )
}

/// The copying counterpart of a mutating array method, where the prelude has one.
fn non_mutating_alternative(name: &str) -> Option<&'static str> {
    match name {
        "push" | "unshift" => Some("concat"),
        "sort" => Some("toSorted"),
        "reverse" => Some("toReversed"),
        "splice" => Some("toSpliced"),
        _ => None,
    }
}

/// Whether `null` is one of the values `ty` can hold. `unknown` counts: it may
/// be null and nothing about it is known until it is narrowed, and a recursion
/// back-edge counts once resolved — see [`alias_ref_body`] for why the name
/// alone cannot answer.
pub(super) fn type_admits_null(ty: &Type, types: TypeResolver<'_>) -> bool {
    any_resolved_member(ty, types, &|member| {
        matches!(member, Type::Null | Type::Unknown)
    })
}

/// Whether a value may be null or undefined, including an erased void result
/// and a type parameter, which a caller may instantiate with either.
pub(super) fn type_admits_nullish(ty: &Type, types: TypeResolver<'_>) -> bool {
    type_admits_null(ty, types) || type_admits_undefined(ty, types)
}

/// Whether `undefined` is one of the values `ty` can hold: `void` results,
/// `unknown`, and type parameters, which a caller may instantiate with it, count.
fn type_admits_undefined(ty: &Type, types: TypeResolver<'_>) -> bool {
    any_resolved_member(ty, types, &admits_undefined_leaf)
}

fn admits_undefined_leaf(member: &Type) -> bool {
    matches!(
        member,
        Type::Undefined | Type::Void | Type::Unknown | Type::GenericParam { .. } | Type::TypeVar(_)
    )
}

/// Whether `JSON.stringify` of a `ty` may return `undefined`.
fn json_stringify_may_return_undefined(ty: &Type, types: TypeResolver<'_>) -> bool {
    any_resolved_member(ty, types, &Type::stringifies_to_undefined)
}

/// Whether any member of `ty`, through unions and alias bodies, satisfies
/// `leaf`. Leaves see peeled types. Unlike the syntactic [`Type::any_member`],
/// this expands alias references through the resolver.
fn any_resolved_member(ty: &Type, types: TypeResolver<'_>, leaf: &dyn Fn(&Type) -> bool) -> bool {
    fn walk(
        ty: &Type,
        types: TypeResolver<'_>,
        leaf: &dyn Fn(&Type) -> bool,
        open: &mut BTreeSet<MangledName>,
    ) -> bool {
        match ty.peel() {
            Type::Union(members) => members.iter().any(|m| walk(m, types, leaf, open)),
            // Cycle guard: an alias already on this path adds nothing new, and
            // following it again would not terminate.
            Type::AliasRef {
                mangled,
                name,
                args,
                ..
            } => {
                if !open.insert(mangled.clone()) {
                    return false;
                }
                let body = alias_ref_body(mangled, name, args, types);
                let found = walk(&body, types, leaf, open);
                open.remove(mangled);
                found
            }
            member => leaf(member),
        }
    }
    walk(ty, types, leaf, &mut BTreeSet::new())
}

/// What to tell someone who wrote `?.` on a namespace when there is no fix to
/// spell: an index step has none, since index signatures are out of scope and
/// `Number[…]` would not compile either.
const NAMESPACE_DROP_HELP: &str = "drop the `?` — a namespace is never null";

/// The first chain step spelled without its `?` and as the source wrote it, for
/// the namespace rejection's fix line. Naming both sides makes the help a
/// literal find/replace, which stays exact on a chain that continues past the
/// first step. `None` when no rewrite is legal — see [`NAMESPACE_DROP_HELP`].
fn namespace_fix_forms(
    written: &str,
    first: &ChainPart,
) -> Result<Option<(String, String)>, CompilerFailure> {
    Ok(match first {
        ChainPart::Field { name, .. } => Some((
            format!("{written}.{}", name.name),
            format!("{written}?.{}", name.name),
        )),
        ChainPart::Call { .. } => Some((format!("{written}(…)"), format!("{written}?.(…)"))),
        ChainPart::Index { .. } => None,
        // The rejection runs only when the first step is optional, and `!`
        // never is.
        ChainPart::NonNull { .. } => {
            return Err(super::inference_failure(
                "non-null assertion is not an optional namespace step",
            ));
        }
    })
}

/// How a chain step is spelled in a diagnostic, so a message reads as the
/// operation the source actually wrote. `optional_form` is the same step
/// rewritten with `?.`, which is the fix for a nullable receiver.
struct ChainStepPhrasing {
    action: String,
    optional_form: String,
    span: Span,
}

fn chain_step_phrasing(part: &ChainPart) -> Result<ChainStepPhrasing, CompilerFailure> {
    let (action, optional_form, span) = match part {
        ChainPart::Field { name, span, .. } => (
            format!("read `{}` on", name.name),
            format!("?.{}", name.name),
            *span,
        ),
        ChainPart::Index { span, .. } => ("index into".to_string(), "?.[…]".to_string(), *span),
        ChainPart::Call { span, .. } => ("call".to_string(), "?.()".to_string(), *span),
        // Every rejection site runs after the `NonNull` step is handled, so a
        // `!` never needs phrasing.
        ChainPart::NonNull { .. } => {
            return Err(super::inference_failure(
                "non-null assertion reached receiver rejection",
            ));
        }
    };
    Ok(ChainStepPhrasing {
        action,
        optional_form,
        span,
    })
}

/// Whether `++`/`--` takes an operand of `ty`: a number or a bigint, or
/// `never`, which tsc accepts as it does in arithmetic.
fn takes_postfix(ty: &Type) -> bool {
    matches!(
        ty.primitive_behavior(),
        Type::Number | Type::NumberLiteral(_) | Type::BigInt | Type::Never | Type::Error
    )
}

fn postfix_result_ty(operand_ty: &Type) -> Type {
    if operand_ty.is_bigint() {
        Type::BigInt
    } else {
        Type::Number
    }
}

/// The type an array literal reads its hint as: peeled, and narrowed to the sole
/// array-like member of a union.
pub(super) fn array_literal_hint_shape(hint: &Type) -> &Type {
    let peeled = hint.peel();
    sole_array_like_member(peeled).unwrap_or(peeled)
}

/// The one `Array`/`Tuple` member of a union hint, when it has exactly one. An array
/// literal can be none of a union's other members, so that member pins its shape —
/// `[number, number] | null` is still a tuple hint, and `new Map<string, number>([["x",
/// 7]])` reaches its literal through the constructor's `entries: [K, V][] | Iterable<[K,
/// V]> | …`. Peels aliases, at the union and at each member.
fn sole_array_like_member(hint: &Type) -> Option<&Type> {
    let Type::Union(members) = hint.peel() else {
        return None;
    };
    let mut array_like = members
        .iter()
        .map(Type::peel)
        .filter(|m| matches!(m, Type::Array(_) | Type::Tuple(_)));
    match (array_like.next(), array_like.next()) {
        (Some(sole), None) => Some(sole),
        _ => None,
    }
}

/// The element type `...src` contributes to an array literal, or `None` when `src` is
/// not spreadable. A tuple spreads as the union of its positions, and a union of
/// arrays and tuples as any member's element: both are arrays at runtime.
pub(super) fn spread_element_type(peeled_source: &Type) -> Option<Type> {
    match peeled_source {
        Type::Array(elem) => Some((**elem).clone()),
        Type::Tuple(elements) => Some(Type::union(elements.to_vec())),
        Type::Union(_) => peeled_source.array_like_union_element(),
        _ => None,
    }
}

/// Does `ty` carry an unresolved `TypeVar` anywhere in its structure? Used to spot
/// a generic receiver (e.g. `new Map()` with no resolvable element types) whose
/// parameters must be pinned by the enclosing call — from its arguments or its
/// expected type — rather than at the receiver in isolation.
pub(crate) fn type_contains_type_var(ty: &Type) -> bool {
    mentions_type_var(ty, &|_| true)
}

/// Whether a value expected as `hint` is in a type parameter's position, which
/// doesn't ask for a literal type: a fresh literal there widens before it
/// binds anything, as in tsc. `h({ k: c })` with `h<K>(o: { k: K }): K` and
/// `const c = "a"` binds `string`, and `new Map([[c, 1]])` is a
/// `Map<string, number>`.
pub(super) fn is_type_parameter_position(hint: &Type) -> bool {
    matches!(hint.peel(), Type::TypeVar(_) | Type::GenericParam { .. })
}

/// Does `ty` mention a `TypeVar` whose name `wanted` accepts?
pub(crate) fn mentions_type_var(ty: &Type, wanted: &impl Fn(&str) -> bool) -> bool {
    let recurse = |ty: &Type| mentions_type_var(ty, wanted);
    match ty {
        Type::TypeVar(name) => wanted(name),
        Type::Array(elem) | Type::Readonly(elem) => recurse(elem),
        Type::Tuple(elems) => elems.iter().any(recurse),
        Type::Function { params, ret, .. } => params.iter().any(recurse) || recurse(ret),
        Type::Object { fields, index } => {
            index.as_ref().is_some_and(|i| recurse(&i.value))
                || fields.values().any(|f| recurse(&f.ty))
        }
        Type::InterfaceRef { args, .. }
        | Type::ClassRef { args, .. }
        | Type::AliasRef { args, .. } => args.iter().any(recurse),
        Type::Alias {
            args, ty: inner, ..
        } => args.iter().any(recurse) || recurse(inner),
        Type::Union(members) => members.iter().any(recurse),
        _ => false,
    }
}

/// Replace a class type's fully-undetermined arguments with bare type
/// variables, which `assignable` treats as wildcards. Used only to ask whether
/// *some* instantiation could relate.
fn wildcard_undetermined_args(ty: &Type) -> Type {
    match ty.peel() {
        Type::ClassRef {
            mangled,
            package,
            name,
            args,
        } if !args.is_empty() && args.iter().all(|a| matches!(a, Type::Unknown)) => {
            Type::ClassRef {
                mangled: mangled.clone(),
                package: package.clone(),
                name: name.clone(),
                args: args
                    .iter()
                    .enumerate()
                    .map(|(i, _)| Type::TypeVar(format!("?{i}")))
                    .collect(),
            }
        }
        other => other.clone(),
    }
}

/// A type's union members, or the type itself — the set a runtime class test
/// has to consider one at a time.
fn class_members(ty: &Type) -> Vec<Type> {
    match ty.peel() {
        Type::Union(members) => members.clone(),
        other => vec![other.clone()],
    }
}

impl Inferer<'_> {
    // --------------------------------------------------------------------
    // Expression inference
    // --------------------------------------------------------------------

    /// [`Self::infer_expr`], keeping the literal type `expr_id` produces or
    /// passes through when `keep_literals` is set.
    pub(super) fn infer_expr_keeping_literals(
        &mut self,
        expr_id: ExprId,
        expected: Option<&Type>,
        keep_literals: bool,
    ) -> Result<(ExprId, Type), CompilerFailure> {
        self.keeps_literal_types = keep_literals;
        self.infer_expr(expr_id, expected)
    }

    pub(super) fn infer_expr(
        &mut self,
        expr_id: ExprId,
        expected: Option<&Type>,
    ) -> Result<(ExprId, Type), CompilerFailure> {
        // A limit recorded before this expression belongs to an enclosing
        // check, whose own checkpoint reports it.
        let limit_was_pending = self.type_limits.limit_reached();
        // Only this expression keeps its literal type; whatever it infers
        // inside starts out widening again, unless it passes the request on.
        let keeps_literal = std::mem::take(&mut self.keeps_literal_types);
        let keeps_returned_literals =
            std::mem::take(&mut self.next_function_keeps_returned_literals);
        // A hint is read structurally — an object literal takes its per-field
        // hints from the expected type's fields — and `peel` stops at a
        // recursion back-edge, which carries no body to read. Rehydrating first
        // is what lets the hint reach the second level of a recursive shape.
        let rehydrated_hint = expected.and_then(|want| {
            super::type_aliases::type_has_alias_ref(want).then(|| {
                self.type_limits
                    .type_or_error(self.rehydrate_alias_refs(want))
            })
        });
        let expected = rehydrated_hint.as_ref().or(expected);
        let mut held_argument = match self.held_arguments.get(&expr_id) {
            Some(&held) => Some(
                self.typed_ast
                    .try_expr(held)
                    .map_err(crate::typechecker::arena_failure)?
                    .clone(),
            ),
            None => None,
        };
        if held_argument.is_none()
            && let ExprKind::FunctionExpression {
                name,
                function,
                this_type,
            } = self
                .ast
                .try_expr(expr_id)
                .map_err(super::arena_failure)?
                .kind
                .clone()
        {
            return self.infer_function_expression(
                name,
                function,
                this_type,
                expected,
                keeps_returned_literals,
            );
        }
        let expr = self
            .ast
            .try_expr(expr_id)
            .map_err(super::arena_failure)?
            .clone();
        let span = expr.span;
        // An arrow whose own errors explain its mismatch with `expected` isn't
        // reported again as a whole.
        let mut arrow_reported = false;
        // Propagate once after dispatch: per-arm `?` creates large temporary
        // results that inflate every recursive frame in debug builds.
        let (kind, ty) = (match expr.kind {
            // An argument already evaluated into a temporary reads it again,
            // and is checked against this signature's parameter below.
            _ if let Some(held) = held_argument.take() => Ok((held.kind, held.ty)),
            // narrow primitive literals to their literal type
            // when the expected hint (directly or as a member of an
            // expected union) calls for it. Without the hint, widen
            // to the base primitive — `let x = "hi"` stays
            // `x: string`, not `x: "hi"`.
            ExprKind::Number(v) => {
                let canonical = if v == 0.0 { 0.0 } else { v };
                let literal = Type::NumberLiteral(crate::types::LiteralF64(canonical));
                // A numeric enum member type takes a number literal of its value.
                let ty = self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(
                        t,
                        Type::NumberLiteral(_)
                            | Type::NumberEnum {
                                member: Some(_),
                                ..
                            }
                    )
                });
                Ok((TypedExprKind::Number(v), ty))
            }
            ExprKind::BigInt(digits) => {
                let literal = crate::types::bigint_literal_type(&digits);
                let ty = self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(t, Type::BigIntLiteral(_))
                });
                Ok((TypedExprKind::BigInt(digits), ty))
            }
            ExprKind::String(s) => {
                let literal = Type::StringLiteral(s.clone());
                let ty = self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(t, Type::StringLiteral(_))
                });
                Ok((TypedExprKind::String(s), ty))
            }
            ExprKind::Boolean(b) => {
                let literal = Type::BooleanLiteral(b);
                let ty = self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(t, Type::BooleanLiteral(_))
                });
                Ok((TypedExprKind::Boolean(b), ty))
            }
            ExprKind::Null => Ok((TypedExprKind::Null, Type::Null)),
            ExprKind::Void { operand } => self.infer_void(operand, span),
            ExprKind::Identifier(_) if self.ast.synthetic_undefined.contains(&expr_id) => {
                Ok((TypedExprKind::Undefined, Type::Undefined))
            }
            ExprKind::Identifier(ident) => self.infer_identifier(ident, span),
            ExprKind::Binary { op, lhs, rhs } => self.infer_binary(op, lhs, rhs, expected, span),
            ExprKind::Unary { op, operand } => {
                self.infer_unary_keeping_literals(op, operand, expected, keeps_literal)
            }
            ExprKind::Call {
                callee,
                type_args,
                args,
            } => self.infer_call_running_invoked_body(callee, type_args, args, expected, span),
            ExprKind::Paren(inner) => {
                self.next_function_keeps_returned_literals = keeps_returned_literals;
                return self.infer_expr_keeping_literals(inner, expected, keeps_literal);
            }
            ExprKind::ObjectLiteral { members } => {
                self.infer_object_literal_expr(expr_id, members, expected, span)
            }
            ExprKind::ArrayLiteral { elements }
                if expected.is_none() && self.ast.tuple_pattern_sources.contains(&expr_id) =>
            {
                self.infer_pattern_tuple_literal(expr_id, elements, span)
            }
            ExprKind::ArrayLiteral { elements } => {
                self.infer_array_literal(expr_id, elements, expected, span)
            }
            ExprKind::FieldAccess { receiver, name } => {
                self.note_uninitialized_member_read(receiver, &name, span)?;
                self.infer_field_access(receiver, name, span)
            }
            ExprKind::IndexAccess { receiver, index } => {
                self.infer_index_access(receiver, index, span, expr_id)
            }
            ExprKind::FunctionExpression { .. } => {
                return Err(super::inference_failure(
                    "handled before ordinary expressions",
                ));
            }
            ExprKind::Arrow {
                params,
                return_type,
                type_predicate,
                body,
            } => {
                let (kind, ty, reported) = self.infer_arrow(
                    params,
                    return_type,
                    type_predicate,
                    body,
                    expected,
                    keeps_returned_literals,
                    span,
                )?;
                arrow_reported = reported;
                Ok((kind, ty))
            }
            ExprKind::Delete { operand } => self.reject_delete(operand, span),
            ExprKind::Typeof { operand } => self.infer_typeof_value(operand, span),
            ExprKind::New {
                callee,
                type_args,
                args,
            } => self.infer_new(callee, type_args, args, expected, span),
            ExprKind::TemplateLiteral {
                parts,
                exprs,
                substitution_spans,
            } => self.lower_template_literal(parts, exprs, substitution_spans, expected, span),
            ExprKind::Ternary { cond, then_, else_ } => {
                self.infer_ternary(cond, then_, else_, expected, span)
            }
            ExprKind::OptionalChain { base, parts } => {
                self.infer_optional_chain(base, parts, expected, span)
            }
            ExprKind::PostfixUnary { op, operand } => self.infer_postfix_unary(op, operand, span),
            ExprKind::Assign {
                target,
                op,
                op_span,
                value,
            } => self.infer_assign_expr(target, op.map(|op| (op, op_span)), value, span),
            ExprKind::As { expr: inner, ty } => self.infer_as(inner, ty, span),
            ExprKind::InstanceOf { value, ty } => self.infer_instanceof(value, ty, span),
            ExprKind::Regex { source, flags } => Ok(self.infer_regex(source, flags, span)),
            ExprKind::ThisOutsideReceiver => {
                self.error_with_help(
                    span,
                    "`this` is only valid inside a class method or constructor body".into(),
                    vec!["reference `this` from within a class method or `constructor`".into()],
                );
                Ok((TypedExprKind::Null, Type::Error))
            }
            ExprKind::This => Ok(if let Some(ty) = &self.function_this {
                (TypedExprKind::This, ty.clone())
            } else if let Some(ty) = self.current_class.clone() {
                self.note_read_before_super(span);
                (TypedExprKind::This, ty)
            } else if let Some((class, member)) = self.current_static.clone() {
                self.error_with_help(
                    span,
                    "`this` is not available in a static member".to_string(),
                    vec![format!(
                        "`{class}.{member}` runs without an instance; take the instance as \
                         a parameter, or make it an instance method. To use another static, \
                         qualify it: `{class}.<member>`"
                    )],
                );
                (TypedExprKind::Null, Type::Error)
            } else {
                self.error(
                    span,
                    "`this` is only valid inside a class method or constructor body".to_string(),
                );
                (TypedExprKind::Null, Type::Error)
            }),
            ExprKind::Super => {
                self.error_with_help(
                    span,
                    "`super` is only valid as `super(...)` or `super.method(...)`".to_string(),
                    vec![
                        "call the parent constructor with `super(...)`, or a parent method with `super.method(...)`"
                            .to_string(),
                    ],
                );
                Ok((TypedExprKind::Null, Type::Error))
            }
        })?;
        // an expression's type must be free of bare recursion
        // back-edges — codegen lowers `AliasRef` to the universal
        // `$Object`, but the equivalent inline alias-to-object peels to
        // the narrower `$ObjectShape`, and the two can't share a slot.
        // Rehydrate any `AliasRef` (read out of a recursive alias's body
        // via field / index / call) back to the inline `Alias` form.
        let ty = self
            .rehydrate_alias_refs(&ty)
            .map_err(super::type_limit_at(span))?;
        // The expression's own type may compose several values of the
        // largest size.
        crate::type_size::check(&ty).map_err(super::type_limit_at(span))?;
        // `assignable` treats `TypeVar` (signature form) as a
        // wildcard, so hints flowing through generic call sites
        // (`(T) => U` shaped) don't fire false errors here. Real
        // binding / conflict-detection happens at the call site via
        // `TypeParamSubstitution::unify`. `GenericParam` (body form)
        // is strict, so `let n: number = x` (where x is GP) does
        // reject as expected.
        if let Some(want) = expected
            && !arrow_reported
            && !self.arguments_with_replaceable_hints.contains(&expr_id)
            && !assignable(&ty, want, self.resolver())
            && !self.widens_candidate(expr_id, want, &ty)
        {
            let has_structural_diff = self
                .render_optional_help(super::type_diff::format_type_diff(want, &ty))
                .is_some();
            let mut help = self.render_help_list(super::type_diff::type_mismatch_help(want, &ty));
            // No structural diff to show (e.g. `number` vs an interface): lift
            // the expected interface's shape so the fix is visible in-place. Keyed
            // on the structural half alone — a lossy-rendering note is not a
            // description of the shape, so it must not stand in for one.
            if !has_structural_diff && matches!(want.peel(), Type::InterfaceRef { .. }) {
                help.push(self.format_definition(want));
            }
            // A value that reads at its declared type where a guard should have
            // narrowed it lands here (a `return`/assignment mismatch rather
            // than a field access), so explain the refused narrowing too.
            if let Some((narrow_help, _)) = self.narrowing_refusal_hint(&kind, &ty, want)? {
                help.extend(narrow_help);
            }
            let shown = self.reported_result_type(&kind, &ty, want)?;
            self.error_with_help(
                span,
                super::diagnostics::mismatch_message(&want, &shown),
                help,
            );
        }
        self.check_expression_arity(&kind, &ty, span);
        let id = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind,
                span,
                ty: ty.clone(),
            })
            .map_err(crate::typechecker::arena_failure)?;
        self.record_narrowed_read_freshness(id)?;
        self.record_runtime_type_test(&ty)
            .map_err(|failure| failure.with_span(span))?;
        // Report an oversized type met while inferring or checking this
        // expression at the innermost expression that met it.
        if !limit_was_pending {
            self.type_size_checkpoint(Some(span))?;
        }
        Ok((id, ty))
    }

    /// Whether `expr_id`, a literal argument slot's value, widens the earlier
    /// candidate `want` it was hinted with rather than mismatching it: the
    /// candidate fits the value's type `ty`.
    fn widens_candidate(&self, expr_id: ExprId, want: &Type, ty: &Type) -> bool {
        self.values_widening_candidates.contains(&expr_id) && assignable(want, ty, self.resolver())
    }

    /// A primitive literal's type: the literal itself where it is kept or the
    /// expected type names a literal of its kind, else its base primitive.
    fn literal_or_base(
        &self,
        keeps_literal: bool,
        expected: Option<&Type>,
        literal: Type,
        is_literal: fn(&Type) -> bool,
    ) -> Type {
        if self.keeps_literal_type(keeps_literal, expected, &literal)
            || expects_literal(expected, is_literal)
        {
            return literal;
        }
        literal.widen_literal()
    }

    /// Whether a literal asked to keep its literal type does. One that its
    /// expected type rejects reports at its base type, as TypeScript does:
    /// `o.x = "a"` with `x: number` is "got `string`".
    fn keeps_literal_type(
        &self,
        keeps_literal: bool,
        expected: Option<&Type>,
        literal: &Type,
    ) -> bool {
        keeps_literal && expected.is_none_or(|want| assignable(literal, want, self.resolver()))
    }

    /// Whether `name` reads the global `undefined`, which no binding shadows.
    fn names_global_undefined(&self, name: &str) -> bool {
        name == "undefined"
            && self.scopes.get("undefined").is_none()
            && !self.top_symbols.contains_key("undefined")
    }

    fn resolve_ident(
        &mut self,
        ident: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // Another clause's declaration hides every binding and namespace of the
        // name from outside the `switch`.
        if self
            .declaration_in_another_case_clause(&ident.name)
            .is_some()
        {
            self.report_unresolved_identifier(&ident.name, span);
            return Ok(unresolved_ref(ident));
        }
        if self.names_global_undefined(&ident.name) {
            return Ok((TypedExprKind::Undefined, Type::Undefined));
        }
        if let Some(entry) = self.scopes.get(&ident.name) {
            // Plan 75.8: consult the active narrow-scope stack. If
            // this binding has been narrowed in an enclosing branch,
            // return a `LocalRef` pointing at the shadow's synthetic
            // binding (`#narrow_<N>`) with the narrowed type. The
            // shadow lives in codegen's local-name map; this rewrite
            // is how in-region references find it.
            let path = super::narrowing::ReferencePath::root(super::narrowing::BindingId::Local {
                name: ident.name.clone(),
                decl_scope: entry.decl_scope,
            });
            if let Some(read) = self.narrowed_read(path) {
                return Ok(read);
            }
            return Ok((
                TypedExprKind::LocalRef {
                    ident: ident.clone(),
                    boxed: false,
                },
                entry.ty.clone(),
            ));
        }
        // `JSON` is a compiler-intrinsic namespace
        // recognised only as the head of a member call
        // (`JSON.stringify(x)` / `JSON.parse(s)`). Bare `JSON` and
        // partial `JSON.stringify` / `JSON.parse` references fall here
        // because the member-access expression infers its receiver via
        // `infer_expr` first. A top-level `JSON` of the user's own is an
        // ordinary value and resolves below.
        if ident.name == "JSON"
            && !self.top_symbols.contains_key("JSON")
            && !self.is_later_global("JSON")
        {
            self.error_with_help(
                span,
                "`JSON` is a compiler intrinsic, not a value".to_string(),
                vec![
                    "call it directly: `JSON.stringify(x)` or \
                     `JSON.parse(s)` — `JSON` itself cannot be \
                     referenced or assigned"
                        .to_string(),
                ],
            );
            return Ok(unresolved_ref(ident));
        }
        let visible = !self.hides_later_global(&ident.name, span)?;
        let global = self.top_symbols.get(&ident.name).filter(|_| visible);
        if let Some(entry) = global {
            let mangled = entry.mangled_name.clone();
            // Plan 75.8: globals narrow too (TS-compatible — TS
            // narrows non-exported module-level lets and all consts).
            // When narrowing is active, rewrite to `LocalRef` against
            // the synthetic shadow binding — same mechanism as for
            // locals.
            let global_path = super::narrowing::ReferencePath::root(
                super::narrowing::BindingId::Global(mangled.clone()),
            );
            if let Some(read) = self.narrowed_read(global_path) {
                return Ok(read);
            }
            // Reject generic functions used as first-class values —
            // `let f = identity` and friends. Rationale: a generic
            // function's "type as a value" needs `Type::Function` to
            // carry its own generics list, which is out of scope for
            // v1. The call form `identity(42)` is recognised
            // separately in `infer_call`, before this branch.
            if let ValueKind::Function { generics, .. } = &entry.kind
                && !generics.is_empty()
            {
                self.error(
                    span,
                    format!(
                        "cannot bind generic function `{}` to a value; \
                         call it directly instead",
                        ident.name,
                    ),
                );
                return Ok((
                    TypedExprKind::FunctionRef {
                        mangled,
                        name: ident.clone(),
                    },
                    Type::Error,
                ));
            }
            let (kind, ty) = match &entry.kind {
                ValueKind::Function {
                    params,
                    ret,
                    type_predicate,
                    ..
                } => (
                    TypedExprKind::FunctionRef {
                        mangled,
                        name: ident,
                    },
                    Type::Function {
                        params: params.iter().map(callable_parameter_type).collect(),
                        ret: Box::new(ret.clone()),
                        predicate: type_predicate.clone().map(Box::new),
                        // lift the rest flag from the resolved
                        // signature so a function-as-value reference
                        // (`const f = sum;`) carries the variadic shape
                        // through to its callers.
                        has_rest: params.last().is_some_and(|p| p.rest),
                        optional: crate::package_declaration::optional_parameter_count(params),
                    },
                ),
                ValueKind::Let { ty, .. } | ValueKind::Const { ty, .. } => (
                    TypedExprKind::GlobalRef {
                        mangled,
                        name: ident,
                    },
                    ty.clone(),
                ),
            };
            return Ok((kind, ty));
        }
        // namespace symbol (`Math`, `Temporal`, …) — sourced
        // from any loaded `PackageDeclaration` — used as a bare value, e.g.
        // `let x = Math;`. Same shape as the namespace-not-
        // a-value error, with a help block pointing at member-access.
        // A later declaration of the name shadows the namespace, but isn't
        // declared yet: report the name as unresolved.
        if self.namespace_symbols.contains_key(&ident.name) && !self.is_later_global(&ident.name) {
            return Ok(self.reject_bare_namespace_symbol(ident, span));
        }

        // namespace import used as a bare value. The
        // binding resolves but a namespace isn't a first-class
        // runtime object — point at the named-import alternative
        // so an LLM can apply the fix in one edit.
        if self.namespace_bindings.contains_key(&ident.name) {
            self.error_with_help(
                span,
                format!("namespace `{}` cannot be used as a value", ident.name,),
                vec![
                    "access a member via `<name>.<export>(…)`, or use a \
                     named import: `import { <export> } from \"<pkg>\";`"
                        .to_string(),
                ],
            );
            return Ok(unresolved_ref(ident));
        }
        // Enum types used as a bare value (without `.Variant`) get
        // a tailored diagnostic: the name resolves in type-space
        // but is not a first-class value. The common LLM misuse is
        // forgetting to qualify; point at the right syntax.
        if let Some(sym) = self.lookup_named_type(&ident.name) {
            let variant_names: Option<Vec<String>> = match &sym.kind {
                crate::TypeKind::NumberEnum { variants, .. } => Some(
                    variants
                        .iter()
                        .map(|(v, _)| format!("`{}.{}`", ident.name, v))
                        .collect(),
                ),
                crate::TypeKind::StringEnum { variants, .. } => Some(
                    variants
                        .iter()
                        .map(|(v, _)| format!("`{}.{}`", ident.name, v))
                        .collect(),
                ),
                _ => None,
            };
            if let Some(variant_list) = variant_names {
                let help = if variant_list.is_empty() {
                    Vec::new()
                } else {
                    vec![format!("variants: {}", variant_list.join(", "))]
                };
                self.error_with_help(
                    span,
                    format!(
                        "`{}` is an enum type, not a value; use `{}.<variant>`",
                        ident.name, ident.name,
                    ),
                    help,
                );
                return Ok(unresolved_ref(ident));
            }
            // Class names are not first-class values either — only `new C(…)`
            // and static member access give them expression meaning.
            if matches!(sym.kind, crate::TypeKind::Class { .. }) {
                let mangled = sym.mangled_name.clone();
                let statics = self.class_static_names(&mangled);
                let mut help = vec![format!(
                    "construct an instance with `new {}(…)`",
                    ident.name,
                )];
                if !statics.is_empty() {
                    help.push(format!(
                        "or access a static member: {}",
                        statics
                            .iter()
                            .map(|s| format!("`{}.{s}`", ident.name))
                            .collect::<Vec<_>>()
                            .join(", "),
                    ));
                }
                self.error_with_help(
                    span,
                    format!("`{}` is a class, not a value", ident.name),
                    help,
                );
                return Ok(unresolved_ref(ident));
            }
        }
        // `WeakMap` / `WeakSet` are intentionally out of scope.
        // Point at `Map` / `Set` — these are the constructor names a
        // user would reach for when calling `new WeakMap()`.
        if ident.name == "WeakMap" {
            self.error_with_help(
                span,
                "`WeakMap` is not supported".to_string(),
                vec![
                    "use `Map<K, V>` instead — Submilli has no weak references, so `WeakMap` would behave identically to `Map`".to_string(),
                ],
            );
            return Ok(unresolved_ref(ident));
        }
        if ident.name == "WeakSet" {
            self.error_with_help(
                span,
                "`WeakSet` is not supported".to_string(),
                vec![
                    "use `Set<T>` instead — Submilli has no weak references, so `WeakSet` would behave identically to `Set`".to_string(),
                ],
            );
            return Ok(unresolved_ref(ident));
        }
        // legacy `Date` is intentionally out of scope. One branch
        // covers `new Date(...)`, `Date.now()`, `Date.parse(...)`,
        // `Date.UTC(...)` — they all hit identifier resolution on `Date`
        // first, before any constructor / member-access dispatch.
        if ident.name == "Date" {
            self.error_with_help(
                span,
                "`Date` is not supported".to_string(),
                vec![
                    "use `Temporal.Now.instant()` for wall-clock time, or `Temporal.ZonedDateTime` / `Temporal.Instant` for time values. `Date` is intentionally out of scope — see Temporal for a correct, immutable, timezone-aware time API.".to_string(),
                ],
            );
            return Ok(unresolved_ref(ident));
        }
        self.report_unresolved_identifier(&ident.name, span);
        Ok(unresolved_ref(ident))
    }

    fn infer_binary(
        &mut self,
        op: BinOp,
        lhs: ExprId,
        rhs: ExprId,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // human-readable operator symbol for diagnostics.
        // Inline-defined so the helper stays scoped to this method.
        fn op_symbol(op: BinOp) -> &'static str {
            match op {
                BinOp::Add => "+",
                BinOp::Sub => "-",
                BinOp::Mul => "*",
                BinOp::Div => "/",
                BinOp::Rem => "%",
                BinOp::Pow => "**",
                BinOp::BitAnd => "&",
                BinOp::BitOr => "|",
                BinOp::BitXor => "^",
                BinOp::Shl => "<<",
                BinOp::Shr => ">>",
                BinOp::UnsignedShr => ">>>",
                BinOp::Lt => "<",
                BinOp::Gt => ">",
                BinOp::Le => "<=",
                BinOp::Ge => ">=",
                BinOp::Eq => "===",
                BinOp::NotEq => "!==",
                BinOp::And => "&&",
                BinOp::Or => "||",
                BinOp::In => "in",
                BinOp::NullishCoalesce => "??",
            }
        }
        fn mixed_string_number_add_help(lt: &Type, rt: &Type) -> Option<&'static str> {
            let left_is_string = matches!(lt.peel(), Type::String | Type::StringLiteral(_));
            let right_is_string = matches!(rt.peel(), Type::String | Type::StringLiteral(_));
            let left_is_number = matches!(lt.peel(), Type::Number | Type::NumberLiteral(_));
            let right_is_number = matches!(rt.peel(), Type::Number | Type::NumberLiteral(_));

            match (
                left_is_string,
                right_is_string,
                left_is_number,
                right_is_number,
            ) {
                (true, false, false, true) => Some(
                    "`+` does not coerce; wrap the number with `String(...)` before concatenating",
                ),
                (false, true, true, false) => Some(
                    "`+` does not coerce; convert the string with `Number(...)`, `parseInt(...)`, or `parseFloat(...)` before adding",
                ),
                _ => None,
            }
        }
        // `??` is lifted out of the generic Binary arm into
        // its own typed-AST node so codegen and the type-result rule
        // (`union(strip_nullish(lhs), rhs)`) can be specialised cleanly.
        if matches!(op, BinOp::NullishCoalesce) {
            return self.infer_nullish_coalesce(lhs, rhs, span);
        }
        match op {
            BinOp::Add => {
                // No hint propagation: `+` is overloaded on `number`/`string`,
                // and either operand alone determines the result. Pushing the
                // outer hint into operands would let the boundary check fire
                // on a mistyped operand and then the operator-level rule would
                // fire again — duplicate diagnostic.
                let (typed_lhs, lt) = self.infer_expr(lhs, None)?;
                let (typed_rhs, rt) = self.infer_expr(rhs, None)?;
                // arithmetic/concat is structural — peel
                // aliases so `type ID = number; let x: ID = 1; x + x`
                // typechecks against the (Number, Number) arm.
                let result_ty = match (lt.peel(), rt.peel()) {
                    (Type::Error, _) | (_, Type::Error) => Type::Error,
                    // `+` on un-narrowed `unknown` is rejected.
                    (Type::Unknown, _) | (_, Type::Unknown) => {
                        self.error_with_help(
                            span,
                            "cannot apply `+` to `unknown`".to_string(),
                            vec![
                                "narrow first with `typeof x === \"number\"` \
                                 or `typeof x === \"string\"` before adding"
                                    .to_string(),
                            ],
                        );
                        Type::Error
                    }
                    _ => {
                        if let Some(ty) = plus_result(&lt, &rt) {
                            ty
                        } else {
                            let message = format!("`+` not defined for `{lt}` and `{rt}`");
                            let help = mixed_string_number_add_help(&lt, &rt)
                                .map(|h| vec![h.to_string()])
                                .unwrap_or_default();
                            let culprit = self.nullable_binary_culprit(
                                (typed_lhs, &lt),
                                (typed_rhs, &rt),
                                |l, r| plus_result(l, r).is_some(),
                            );
                            self.error_with_narrowing_hint(span, message, help, culprit)?;
                            Type::Error
                        }
                    }
                };
                Ok((
                    TypedExprKind::Binary {
                        op,
                        lhs: typed_lhs,
                        rhs: typed_rhs,
                    },
                    result_ty,
                ))
            }
            BinOp::Sub
            | BinOp::Mul
            | BinOp::Div
            | BinOp::Rem
            | BinOp::Pow
            | BinOp::BitAnd
            | BinOp::BitOr
            | BinOp::BitXor
            | BinOp::Shl
            | BinOp::Shr
            | BinOp::UnsignedShr => {
                // arithmetic accepts `number × number`
                // or `bigint × bigint`. Mixed `number ↔ bigint` falls
                // through to the catch-all "not defined for" error.
                // `**` uses the same type rules; the bigint-pow host
                // function additionally traps at runtime if the
                // exponent is negative or doesn't fit in u32 (a
                // semantic constraint, not a static one).
                // Inferred without a forced hint so a literal lhs
                // picks its own widened type and the rhs gets the
                // lhs type as a hint.
                let (typed_lhs, lt) = self.infer_expr(lhs, None)?;
                let rhs_hint = match lt.peel() {
                    Type::Number | Type::NumberLiteral(_) => Some(Type::Number),
                    Type::BigInt | Type::BigIntLiteral(_) => Some(Type::BigInt),
                    _ => None,
                };
                let (typed_rhs, rt) = self.infer_expr(rhs, rhs_hint.as_ref())?;
                let result_ty = match (lt.peel(), rt.peel()) {
                    (Type::Error, _) | (_, Type::Error) => Type::Error,
                    (Type::Unknown, _) | (_, Type::Unknown) => {
                        self.error_with_help(
                            span,
                            format!("cannot apply `{}` to `unknown`", op_symbol(op)),
                            vec![
                                "narrow first with `typeof x === \"number\"` \
                                 before doing arithmetic"
                                    .to_string(),
                            ],
                        );
                        Type::Error
                    }
                    _ => {
                        if let Some(ty) = super::stmt::binary_arith_result(op, &lt, &rt) {
                            ty
                        } else {
                            let culprit = self.nullable_binary_culprit(
                                (typed_lhs, &lt),
                                (typed_rhs, &rt),
                                |l, r| super::stmt::binary_arith_result(op, l, r).is_some(),
                            );
                            self.error_with_narrowing_hint(
                                span,
                                format!("`{}` not defined for `{lt}` and `{rt}`", op_symbol(op)),
                                Vec::new(),
                                culprit,
                            )?;
                            Type::Error
                        }
                    }
                };
                Ok((
                    TypedExprKind::Binary {
                        op,
                        lhs: typed_lhs,
                        rhs: typed_rhs,
                    },
                    result_ty,
                ))
            }
            BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => {
                // ordering accepts `number × number`, `bigint × bigint`, or
                // `string × string` (lexicographic). Inferred without a forced
                // hint so the rhs takes the lhs type as a hint (mirroring
                // `===` / `!==`). Strings keep `None` as the rhs hint so a
                // mixed `string < number` doesn't also emit "expected string".
                let (typed_lhs, lt) = self.infer_expr(lhs, None)?;
                let rhs_hint = match lt.peel() {
                    Type::Number | Type::NumberLiteral(_) => Some(Type::Number),
                    Type::BigInt | Type::BigIntLiteral(_) => Some(Type::BigInt),
                    _ => None,
                };
                let (typed_rhs, rt) = self.infer_expr(rhs, rhs_hint.as_ref())?;
                if matches!(lt.peel(), Type::Unknown) || matches!(rt.peel(), Type::Unknown) {
                    // ordering comparisons on un-narrowed
                    // `unknown` are rejected. Same rationale as the
                    // arithmetic arm.
                    self.error_with_help(
                        span,
                        format!("cannot apply `{}` to `unknown`", op_symbol(op)),
                        vec![
                            "narrow first with `typeof x === \"number\"` \
                             before comparing"
                                .to_string(),
                        ],
                    );
                } else if !matches!((lt.peel(), rt.peel()), (Type::Error, _) | (_, Type::Error))
                    && !ordering_accepts(&lt, &rt)
                {
                    let culprit = self.nullable_binary_culprit(
                        (typed_lhs, &lt),
                        (typed_rhs, &rt),
                        ordering_accepts,
                    );
                    self.error_with_narrowing_hint(
                        span,
                        format!("`{}` not defined for `{lt}` and `{rt}`", op_symbol(op)),
                        Vec::new(),
                        culprit,
                    )?;
                }
                Ok((
                    TypedExprKind::Binary {
                        op,
                        lhs: typed_lhs,
                        rhs: typed_rhs,
                    },
                    Type::Boolean,
                ))
            }
            BinOp::Eq | BinOp::NotEq => {
                // forgiveness: rewrite `typeof x === "T"` and
                // `typeof x !== "T"` (plus the swapped sides) to
                // `Is` / `!Is`. Falls through if no `typeof` operand.
                if let Some(folded) = self.try_typeof_fold(op, lhs, rhs, span)? {
                    return Ok(folded);
                }
                let (typed_lhs, lt) = self.infer_expr(lhs, None)?;
                // Contextual types help literals and callbacks, but an equality
                // operand is not an assignment into the other operand's type.
                let contextual_rhs = is_context_typed_literal(self.ast, rhs)?;
                let rhs_hint = contextual_rhs.then_some(&lt);
                let (typed_rhs, _) = self.infer_expr(rhs, rhs_hint)?;
                let lhs_operand = self.comparison_operand(lhs, typed_lhs)?;
                let rhs_operand = self.comparison_operand(rhs, typed_rhs)?;
                if !super::comparison_operand::operands_comparable(
                    &lhs_operand,
                    &rhs_operand,
                    self.resolver(),
                ) {
                    self.error(
                        self.ast.try_expr(rhs).map_err(super::arena_failure)?.span,
                        super::diagnostics::mismatch_message(
                            &lhs_operand.label,
                            &rhs_operand.label,
                        ),
                    );
                }
                if self.is_global_nan(typed_lhs)? || self.is_global_nan(typed_rhs)? {
                    self.error_nan_comparison(op, span);
                }
                Ok((
                    TypedExprKind::Binary {
                        op,
                        lhs: typed_lhs,
                        rhs: typed_rhs,
                    },
                    Type::Boolean,
                ))
            }
            BinOp::And | BinOp::Or => {
                // JS value-returning logicals. The RHS is inferred
                // under the LHS predicate's narrowing — true-env
                // for `&&`, false-env for `||` — and wrapped in
                // `TypedExprKind::Narrowed` so codegen materializes
                // the shadow local for in-region references. Result
                // type is TS-style: the branch that keeps the LHS
                // contributes only the values that can short-circuit
                // there (`falsy_part` for `&&`, `truthy_part` for `||`).
                let (typed_lhs, lhs_ty) = self.infer_expr_keeping_literals(lhs, None, true)?;
                let mut condition_error = false;
                if matches!(lhs_ty.peel(), Type::Unknown) {
                    // `&&`/`||` on un-narrowed `unknown`
                    // rejected with a "narrow first" hint instead of
                    // the generic "expected boolean" mismatch.
                    condition_error = true;
                    let lhs_span = self.ast.try_expr(lhs).map_err(super::arena_failure)?.span;
                    self.error_with_help(
                        lhs_span,
                        "cannot use `unknown` in a boolean context".to_string(),
                        vec![
                            "narrow first with `typeof x === \"…\"`, \
                             `x === null`, or `Array.isArray(x)` before \
                             using as a condition"
                                .to_string(),
                        ],
                    );
                } else if !super::narrowing::condition_compatible(&lhs_ty) {
                    condition_error = true;
                    let lhs_span = self.ast.try_expr(lhs).map_err(super::arena_failure)?.span;
                    self.error_non_condition_type(lhs_span, &lhs_ty);
                }
                let (true_env, false_env) = self.predicate_envs(typed_lhs)?;
                let rhs_env = match op {
                    BinOp::And => true_env,
                    BinOp::Or => false_env,
                    _ => return Err(super::inference_failure("matched And | Or above")),
                };
                // `a || b` is `a` when `a` is never falsy, so only `a` meets what
                // is expected of it. `b` still takes it as context unless it is a
                // read, which the context can't change: `[]`, a tuple, a callback
                // or an object literal for an interface all type by it.
                let lhs_decides = op == BinOp::Or && super::narrowing::is_never_falsy(&lhs_ty);
                let rhs_expected = if lhs_decides && self.is_read(rhs)? {
                    None
                } else {
                    expected
                };
                let (typed_rhs, rhs_ty) =
                    self.infer_conditional_operand(rhs, &rhs_env, rhs_expected)?;
                let rhs_span = self.ast.try_expr(rhs).map_err(super::arena_failure)?.span;
                let wrapped_rhs = self.wrap_narrow_exprs(typed_rhs, &rhs_env, rhs_span)?;
                let lhs_kept = match op {
                    BinOp::And => super::narrowing::falsy_part(&lhs_ty),
                    BinOp::Or => super::narrowing::truthy_part(&lhs_ty),
                    _ => return Err(super::inference_failure("matched And | Or above")),
                };
                let result_ty = if condition_error {
                    Type::Error
                } else if let Some(decided) = lhs_decides
                    .then(|| self.deciding_left_type(&lhs_kept, &rhs_ty))
                    .flatten()
                {
                    decided
                } else if let Some(joined) =
                    empty_literal_join(self.ast, (lhs, &lhs_kept), (rhs, &rhs_ty))?
                {
                    joined
                } else {
                    branch_result_type(lhs_kept, rhs_ty, self.resolver())
                };
                Ok((
                    TypedExprKind::Binary {
                        op,
                        lhs: typed_lhs,
                        rhs: wrapped_rhs,
                    },
                    result_ty,
                ))
            }
            BinOp::In => self.infer_in_operator(lhs, rhs, span),
            // Lifted earlier in this function — the early-return at
            // the top of `infer_binary` keeps `NullishCoalesce` out of
            // this match.
            BinOp::NullishCoalesce => Err(super::inference_failure(
                "NullishCoalesce handled by early return",
            )),
        }
    }

    /// `"field" in obj`. LHS must be a string literal; RHS
    /// receiver must be `unknown`, an `Object`, or a union of objects.
    /// Result is `boolean`. The narrowing-engine side is driven from
    /// `predicate_envs_in_operator` — this method only enforces the
    /// type-level shape.
    fn infer_in_operator(
        &mut self,
        lhs: ExprId,
        rhs: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let lhs_span = self.ast.try_expr(lhs).map_err(super::arena_failure)?.span;
        let (typed_lhs, lhs_ty) = self.infer_expr(lhs, Some(&Type::String))?;
        if !assignable(&lhs_ty, &Type::String, self.resolver()) {
            self.error(
                lhs_span,
                "`in` operator requires a string on the left".into(),
            );
        }
        let (typed_rhs, rhs_ty) = self.infer_expr(rhs, None)?;
        let receiver_ok = match rhs_ty.peel() {
            Type::Unknown | Type::Error => true,
            ty if Self::is_field_bearing(ty) => true,
            // A union discriminated by field presence is the reason `in` exists;
            // its members are as often named (interfaces, classes) as inline.
            Type::Union(members) => members.iter().all(Self::is_field_bearing),
            _ => false,
        };
        if !receiver_ok {
            let help = vec![self.format_definition(&rhs_ty)];
            self.error_with_help(
                span,
                format!("`in` operator receiver must be an object (or `unknown`), got `{rhs_ty}`",),
                help,
            );
        }
        Ok((
            TypedExprKind::Binary {
                op: BinOp::In,
                lhs: typed_lhs,
                rhs: typed_rhs,
            },
            Type::Boolean,
        ))
    }

    /// [`infer_unary`](Self::infer_unary), giving a negated literal its literal
    /// type where the literal itself would keep one: `const n = -1` is `-1`, as
    /// TypeScript has it. Only a literal written right after the `-` counts.
    fn infer_unary_keeping_literals(
        &mut self,
        op: UnOp,
        operand: ExprId,
        expected: Option<&Type>,
        keeps_literal: bool,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (kind, ty) = self.infer_unary(op, operand)?;
        if !matches!(op, UnOp::Neg) {
            return Ok((kind, ty));
        }
        let ty = match &self
            .ast
            .try_expr(operand)
            .map_err(super::arena_failure)?
            .kind
        {
            ExprKind::BigInt(digits) => {
                let literal = Type::BigIntLiteral(crate::types::negate_bigint_digits(digits));
                self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(t, Type::BigIntLiteral(_))
                })
            }
            ExprKind::Number(value) => {
                let literal = number_literal_type(-value);
                self.literal_or_base(keeps_literal, expected, literal, |t| {
                    matches!(t, Type::NumberLiteral(_))
                })
            }
            _ => ty,
        };
        Ok((kind, ty))
    }

    fn infer_unary(
        &mut self,
        op: UnOp,
        operand: ExprId,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (operand_id, result_ty) = match op {
            UnOp::Not => {
                // The operand keeps a literal type, which can decide the result:
                // `!true` is `false`.
                let (id, operand_ty) = self.infer_expr_keeping_literals(operand, None, true)?;
                if matches!(operand_ty.peel(), Type::Unknown) {
                    // `!x` on un-narrowed `unknown` rejected
                    // with a "narrow first" hint.
                    let operand_span = self
                        .ast
                        .try_expr(operand)
                        .map_err(super::arena_failure)?
                        .span;
                    self.error_with_help(
                        operand_span,
                        "cannot use `unknown` in a boolean context".to_string(),
                        vec![
                            "narrow first with `typeof x === \"…\"`, \
                             `x === null`, or `Array.isArray(x)` before \
                             using as a condition"
                                .to_string(),
                        ],
                    );
                } else if !super::narrowing::condition_compatible(&operand_ty) {
                    let operand_span = self
                        .ast
                        .try_expr(operand)
                        .map_err(super::arena_failure)?
                        .span;
                    self.error_non_condition_type(operand_span, &operand_ty);
                    return Ok((TypedExprKind::Unary { op, operand: id }, Type::Boolean));
                }
                (id, narrowing::negation_type(&operand_ty))
            }
            UnOp::Neg | UnOp::Pos | UnOp::BitNot => {
                // No forced hint — the operand picks its own widened type and
                // the result mirrors it.
                let (id, operand_ty) = self.infer_expr(operand, None)?;
                let operand_span = self
                    .ast
                    .try_expr(operand)
                    .map_err(super::arena_failure)?
                    .span;
                let peeled = operand_ty.peel();
                if matches!(peeled, Type::Unknown) {
                    self.error_with_help(
                        operand_span,
                        "cannot apply unary arithmetic to `unknown`".to_string(),
                        vec![
                            "narrow first with `typeof x === \"number\"` \
                             before doing arithmetic"
                                .to_string(),
                        ],
                    );
                    (id, Type::Number)
                } else if let Some(ty) = unary_arith_result(op, peeled) {
                    (id, ty)
                } else {
                    let symbol = match op {
                        UnOp::Neg => "-",
                        UnOp::BitNot => "~",
                        _ => "+",
                    };
                    let mut help = Vec::new();
                    if peeled.contains_string() {
                        help.push(
                            "convert first: `Number(s)` parses the text (`NaN` if it \
                             isn't a number), and `-Number(s)` negates the result"
                                .to_string(),
                        );
                    }
                    let culprit = self.nullish_culprit(&[(id, &operand_ty)], |t| {
                        unary_arith_result(op, t).is_some()
                    });
                    self.error_with_narrowing_hint(
                        operand_span,
                        format!("unary `{symbol}` not defined for `{operand_ty}`"),
                        help,
                        culprit,
                    )?;
                    (id, Type::Error)
                }
            }
        };
        Ok((
            TypedExprKind::Unary {
                op,
                operand: operand_id,
            },
            result_ty,
        ))
    }

    /// `void operand`: the operand runs for its effects, and the result is
    /// `undefined`. Kept out of `infer_expr`, whose frame every nested
    /// expression pays for.
    #[inline(never)]
    fn infer_void(
        &mut self,
        operand: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (effect, _) = self.infer_expr(operand, None)?;
        let result = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind: TypedExprKind::Undefined,
                span,
                ty: Type::Undefined,
            })
            .map_err(super::arena_failure)?;
        Ok((
            TypedExprKind::EffectThen { effect, result },
            Type::Undefined,
        ))
    }

    /// A read of a name. A local whose storage type differs from its read type
    /// (a parameter whose default was applied) is cast to the read type. Kept
    /// out of `infer_expr`, whose frame every nested expression pays for.
    #[inline(never)]
    fn infer_identifier(
        &mut self,
        ident: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if let Some(index) = self
            .scopes
            .get(&ident.name)
            .and_then(|entry| entry.nested_function)
        {
            self.check_nested_function_use(index, span)?;
        }
        let (kind, ty) = self.resolve_ident(ident, span)?;
        let storage = if let TypedExprKind::LocalRef { ident, .. } = &kind {
            self.scopes
                .get(&ident.name)
                .map(|entry| entry.storage_type().clone())
        } else {
            None
        };
        if let Some(storage) = storage.filter(|storage| *storage != ty) {
            let value = self
                .typed_ast
                .try_push_expr(TypedExpr {
                    kind,
                    span,
                    ty: storage,
                })
                .map_err(super::arena_failure)?;
            Ok((
                TypedExprKind::Cast {
                    value,
                    target_ty: ty.clone(),
                    check: None,
                },
                ty,
            ))
        } else {
            Ok((kind, ty))
        }
    }

    /// `delete` is rejected: an object can't record one of its fields as
    /// absent unless it was built with that field optional, since other
    /// objects share one immutable names array per shape (SUB-971). The
    /// operand is still inferred, so its own errors surface.
    fn reject_delete(
        &mut self,
        operand: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        self.infer_expr(operand, None)?;
        // A runtime key can't be made optional in a declaration, so a
        // keyed collection is the fix there.
        let deletes_a_key = matches!(
            self.ast
                .try_expr(operand)
                .map_err(super::arena_failure)?
                .kind,
            ExprKind::IndexAccess { .. }
        );
        let help = if deletes_a_key {
            "keep runtime keys in a `Map` and remove one with `map.delete(key)`"
        } else {
            "declare the field optional (`x?: T`) and assign `undefined` to clear it"
        };
        self.error_with_help(
            span,
            "the `delete` operator is not supported".into(),
            vec![help.into()],
        );
        Ok((TypedExprKind::Null, Type::Error))
    }

    /// Store the operand once so a dynamic typeof decision never repeats effects.
    fn infer_typeof_value(
        &mut self,
        operand: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (value, value_ty) = self.infer_expr(operand, None)?;
        let name = Ident {
            name: format!("#typeof_{}", self.typed_ast.exprs_len()),
            span,
        };
        let binding = self
            .typed_ast
            .try_push_stmt(crate::TypedStmt {
                kind: crate::TypedStmtKind::Const {
                    name: name.clone(),
                    ty: value_ty.clone(),
                    value,
                    doc: None,
                },
                span,
            })
            .map_err(super::arena_failure)?;
        let mut result =
            self.push_synthetic_expr(TypedExprKind::String("object".into()), Type::String, span)?;
        for (tag, label) in [
            (crate::TypeofTagKind::Function, "function"),
            (crate::TypeofTagKind::Boolean, "boolean"),
            (crate::TypeofTagKind::String, "string"),
            (crate::TypeofTagKind::Number, "number"),
            (crate::TypeofTagKind::BigInt, "bigint"),
            (crate::TypeofTagKind::Undefined, "undefined"),
        ] {
            let reference = self.push_synthetic_expr(
                TypedExprKind::LocalRef {
                    ident: name.clone(),
                    boxed: false,
                },
                value_ty.clone(),
                span,
            )?;
            let condition = self.push_synthetic_expr(
                TypedExprKind::TypeofTag {
                    value: reference,
                    tag,
                },
                Type::Boolean,
                span,
            )?;
            let matched =
                self.push_synthetic_expr(TypedExprKind::String(label.into()), Type::String, span)?;
            result = self.push_synthetic_expr(
                TypedExprKind::Ternary {
                    cond: condition,
                    then_: matched,
                    else_: result,
                },
                Type::String,
                span,
            )?;
        }
        Ok((
            TypedExprKind::Sequence {
                stmts: vec![binding],
                result,
            },
            Type::String,
        ))
    }

    /// Detect `typeof X === "T"` / `typeof X !== "T"` (and the
    /// swapped-sides form) and rewrite to `Is` / `!Is`. Returns
    /// `None` if neither operand is a `typeof` expression, in which
    /// case the caller falls through to the normal equality path.
    fn try_typeof_fold(
        &mut self,
        op: BinOp,
        lhs: ExprId,
        rhs: ExprId,
        span: Span,
    ) -> Result<Option<(TypedExprKind, Type)>, CompilerFailure> {
        // Peek the *surface* AST — we want to detect `Typeof` before
        // it's inferred (inferring it would emit the "not a value"
        // error from the bare-typeof arm).
        let (operand_id, tag, tag_span) = if let ExprKind::Typeof { operand } =
            &self.ast.try_expr(lhs).map_err(super::arena_failure)?.kind
            && let ExprKind::String(s) = &self.ast.try_expr(rhs).map_err(super::arena_failure)?.kind
        {
            (
                *operand,
                s.clone(),
                self.ast.try_expr(rhs).map_err(super::arena_failure)?.span,
            )
        } else if let ExprKind::Typeof { operand } =
            &self.ast.try_expr(rhs).map_err(super::arena_failure)?.kind
            && let ExprKind::String(s) = &self.ast.try_expr(lhs).map_err(super::arena_failure)?.kind
        {
            (
                *operand,
                s.clone(),
                self.ast.try_expr(lhs).map_err(super::arena_failure)?.span,
            )
        } else {
            return Ok(None);
        };
        let (typed_operand, _) = self.infer_expr(operand_id, None)?;
        // Retained refinements cannot prove the kind of a later live read.
        let tag = match tag.as_str() {
            "number" => crate::TypeofTagKind::Number,
            "string" => crate::TypeofTagKind::String,
            "boolean" => crate::TypeofTagKind::Boolean,
            "object" => crate::TypeofTagKind::Object,
            "function" => crate::TypeofTagKind::Function,
            "undefined" => crate::TypeofTagKind::Undefined,
            "bigint" => crate::TypeofTagKind::BigInt,
            _ => {
                self.error_with_help(
                    tag_span,
                    format!(
                        "`typeof x === \"{tag}\"` is not a valid narrowing \
                         guard",
                    ),
                    vec![
                        "supported tags are \"number\", \"string\", \
                         \"boolean\", \"object\", \"function\""
                            .into(),
                    ],
                );
                crate::TypeofTagKind::Object
            }
        };
        let inner_kind = TypedExprKind::TypeofTag {
            value: typed_operand,
            tag,
        };
        Ok(match op {
            BinOp::Eq => Some((inner_kind, Type::Boolean)),
            BinOp::NotEq => {
                // Wrap in `Unary { Not, … }` — push the inner first
                // so the Unary can reference its ExprId.
                let inner_id = self
                    .typed_ast
                    .try_push_expr(TypedExpr {
                        kind: inner_kind,
                        span,
                        ty: Type::Boolean,
                    })
                    .map_err(crate::typechecker::arena_failure)?;
                Some((
                    TypedExprKind::Unary {
                        op: UnOp::Not,
                        operand: inner_id,
                    },
                    Type::Boolean,
                ))
            }
            _ => {
                return Err(super::inference_failure(
                    "try_typeof_fold called with non-eq op",
                ));
            }
        })
    }

    /// Type the arguments of a call that has already been rejected, discarding
    /// the results.
    ///
    /// The call itself produces no node, but an argument is an expression in its
    /// own right: an unresolved name or a bad nested call in one is a second
    /// real problem, and skipping the walk would hide it until the first is
    /// fixed.
    fn walk_rejected_call_args(&mut self, args: &[ExprId]) -> Result<(), CompilerFailure> {
        for arg in args {
            let _ = self.infer_expr(*arg, None)?;
        }

        Ok(())
    }

    /// Reports a call of a mutating array method (`push`, `sort`, …) on a receiver
    /// that must not change: a `readonly` array or tuple, any tuple, or a union of
    /// arrays and tuples. A union also refuses methods taking an element. Returns
    /// whether it reported, in which case the caller poisons the call.
    fn reject_unsupported_array_call(&mut self, recv_ty: &Type, name: &crate::Ident) -> bool {
        if self.reject_array_like_union_call(recv_ty, name) {
            return true;
        }
        if !is_mutating_array_method(&name.name) {
            return false;
        }
        if recv_ty.is_readonly_array() {
            let mut help = vec![format!(
                "`{}` mutates the array, and a `readonly` array or tuple only permits reading",
                name.name
            )];
            if let Some(alternative) = non_mutating_alternative(&name.name) {
                help.push(format!(
                    "`{alternative}` returns a new array instead of modifying this one"
                ));
            }
            help.push(
                "or copy it first (`[...xs]` or `xs.slice()`) and modify the copy".to_string(),
            );
            self.error_with_help(
                name.span,
                format!("cannot call `{}` on `{}`", name.name, recv_ty),
                help,
            );
            return true;
        }
        if matches!(recv_ty.peel(), Type::Tuple(_)) {
            self.error_with_help(
                name.span,
                format!("cannot call `{}` on tuple `{}`", name.name, recv_ty),
                vec![
                    "tuples are fixed-length and read-only; assign to an array-typed binding first to mutate"
                        .to_string(),
                ],
            );
            return true;
        }
        false
    }

    /// Reports a method a union of arrays and tuples can't offer through its
    /// joined element type: one that mutates the array, or one taking an element,
    /// which would have to suit every member at once.
    fn reject_array_like_union_call(&mut self, recv_ty: &Type, name: &crate::Ident) -> bool {
        let Some(view) = recv_ty.array_like_union_view() else {
            return false;
        };
        let reason = if is_mutating_array_method(&name.name) {
            "a union of arrays or tuples only permits reading, since a write could store \
             one member's element in another"
        } else if self.find_method(recv_ty, &name.name).is_none()
            && self.find_method(&view, &name.name).is_some()
        {
            "its argument would have to suit the element type of every member of the union"
        } else {
            return false;
        };
        self.error_with_help(
            name.span,
            format!("cannot call `{}` on `{}`", name.name, recv_ty),
            vec![
                format!("`{}`: {reason}", name.name),
                format!(
                    "copy it first with `slice()`, which gives a `{view}` that can be changed \
                     and searched"
                ),
            ],
        );
        true
    }

    pub(super) fn infer_call(
        &mut self,
        callee: ExprId,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        args: Vec<ExprId>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let callee_kind = string_key_callee_as_field(self.ast, callee)?;

        // Intrinsic dispatch — when the callee is a bare identifier
        // matching a reserved intrinsic name, we skip the normal
        // callee-as-expression path and produce a dedicated
        // `IntrinsicCall` node. Reserved names are rejected during
        // signature binding; local bindings still take precedence.
        if let ExprKind::Identifier(ident) = &callee_kind
            && self.scopes.get(&ident.name).is_none()
            && let Some(intrinsic) = Intrinsic::from_name(&ident.name)
        {
            return self.infer_intrinsic_call(intrinsic, args, span);
        }

        // `super(...)` delegates to the parent constructor.
        if matches!(callee_kind, ExprKind::Super) {
            return self.infer_super_call(args, span);
        }

        // `super.method(...)` — direct call of the parent's method body.
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && matches!(
                self.ast
                    .try_expr(*receiver)
                    .map_err(super::arena_failure)?
                    .kind,
                ExprKind::Super
            )
        {
            return self.infer_super_method_call(name.clone(), args, span);
        }

        // `JSON.stringify(...)` intrinsic dispatch. `JSON`
        // is recognised only at the head of a member call — bare
        // references and partial `JSON.stringify` references take
        // the `resolve_ident` path and error there. Must run before
        // the namespace dispatch so the `JSON` identifier
        // never resolves as a user-imported namespace.
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && let ExprKind::Identifier(recv_ident) = &self
                .ast
                .try_expr(*receiver)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && !self.shadows_namespace(&recv_ident.name)
            && recv_ident.name == "JSON"
        {
            return self.infer_json_namespace_call(name, args, type_args, expected, span);
        }

        // `BigInt.fromString(s)` — namespace-headed intrinsic
        // (same recognition pattern as `JSON.stringify`). Bare
        // `BigInt` is reserved by `is_reserved_call_name`, so the
        // resolve_ident path produces a focused diagnostic.
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && let ExprKind::Identifier(recv_ident) = &self
                .ast
                .try_expr(*receiver)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && self.scopes.get(&recv_ident.name).is_none()
            && recv_ident.name == "BigInt"
        {
            return self.infer_bigint_namespace_call(name, args, span);
        }

        // namespace-symbol dispatch — `Math.floor(x)`,
        // `Temporal.Now.instant()`, `Temporal.Instant.from(iso)`,
        // and any future dotted access through a `PackageDeclaration`-
        // declared namespace. Must run before the user-
        // import-namespace path so a user can't shadow these names
        // with an `import`. The chain extractor walks the
        // FieldAccess chain rooted at the callee; the
        // `namespace_symbols` map gates the dispatch.
        if let ExprKind::FieldAccess { .. } = &callee_kind
            && let Some((root, segments)) = namespace_symbol::extract_chain(self.ast, callee)?
            && !segments.is_empty()
            && !self.shadows_namespace(&root.name)
            && self.namespace_symbols.contains_key(&root.name)
        {
            return self
                .infer_namespace_symbol_call(root, segments, type_args, args, expected, span);
        }

        // namespace member dispatch — `<ns>.<member>(args)`
        // where `<ns>` was bound by `import <ns> from "<pkg>";`.
        // Resolves against the bound package's value table; emits
        // a static `Call { mangled }` matching what a named import
        // would produce. Must run *before* the
        // type-the-receiver-as-expression path so the namespace
        // identifier never reaches `resolve_ident` (which would
        // reject it as "namespace cannot be used as a value").
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && let ExprKind::Identifier(recv_ident) = &self
                .ast
                .try_expr(*receiver)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && self.scopes.get(&recv_ident.name).is_none()
            && let Some(ns) = self.namespace_bindings.get(&recv_ident.name)
        {
            let package_name = ns.members.package_name().to_string();
            let namespace_value = ns.members.value(&name.name).cloned();
            if let Some(sym) = namespace_value {
                return self.infer_namespace_call(
                    package_name,
                    sym,
                    recv_ident,
                    name,
                    type_args,
                    args,
                    expected,
                    span,
                );
            }
            let exports = ns.members.exports_help();
            self.error_with_help(
                name.span,
                format!("package `{package_name}` does not export `{}`", name.name),
                exports,
            );
            return Ok((
                TypedExprKind::Call {
                    mangled: crate::mangle::host(&package_name, &name.name),
                    args: Vec::new(),
                    type_predicate: None,
                },
                Type::Error,
            ));
        }

        // static member dispatch — `ClassName.member(args)`. The receiver is
        // peeked before being typed (a bare class name is not a value); a value
        // binding of the same name shadows the class, TS-style.
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && let ExprKind::Identifier(recv_ident) = &self
                .ast
                .try_expr(*receiver)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && self.scopes.get(&recv_ident.name).is_none()
            && !self.top_symbols.contains_key(&recv_ident.name)
        {
            let class_target = self.lookup_named_type(&recv_ident.name).and_then(|sym| {
                matches!(sym.kind, crate::TypeKind::Class { .. }).then(|| sym.mangled_name.clone())
            });
            if let Some(class_mangled) = class_target {
                return self.infer_class_static_call(
                    recv_ident.name.clone(),
                    class_mangled,
                    name.clone(),
                    type_args,
                    args,
                    expected,
                    span,
                );
            }
        }

        // `ns.Class.member(args)` — statics are not reachable through a
        // namespace import (symmetric with `new ns.Class(...)`); name the
        // direct-import fix.
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind
            && let ExprKind::FieldAccess {
                receiver: inner_recv,
                name: type_name,
            } = &self
                .ast
                .try_expr(*receiver)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && let ExprKind::Identifier(ns_ident) = &self
                .ast
                .try_expr(*inner_recv)
                .map_err(super::arena_failure)?
                .kind
                .clone()
            && self.scopes.get(&ns_ident.name).is_none()
            && let Some(ns) = self.namespace_bindings.get(&ns_ident.name)
            && matches!(
                ns.members.type_symbol(&type_name.name).map(|s| &s.kind),
                Some(crate::TypeKind::Class { .. }),
            )
        {
            let package_name = ns.members.package_name().to_string();
            self.error_with_help(
                name.span,
                "static members are not accessible through a namespace import".to_string(),
                vec![format!(
                    "import the class directly: `import {{ {} }} from \"{package_name}\"; \
                     {}.{}(…)`",
                    type_name.name, type_name.name, name.name,
                )],
            );
            self.walk_rejected_call_args(&args)?;
            return Ok((TypedExprKind::Null, Type::Error));
        }

        // method dispatch — `recv.method(args)` resolves
        // through `find_method` against the prelude's interface
        // declarations (and user-declared interfaces, when any
        // value of an InterfaceRef type ends up as a receiver).
        // Replaces the per-method special-case dispatch arms
        // (infer_to_string_call, infer_array_join_call,
        // console.log special case).
        if let ExprKind::FieldAccess { receiver, name } = &callee_kind {
            let diags_before = self.diagnostics.len();
            let (mut typed_receiver, mut recv_ty) = self.infer_expr(*receiver, None)?;
            // `r.json()` on an http `Response` has no host backing, so the
            // typechecker lowers it to `JSON.parse(r.body)`. This must run before `find_method`: the `json`
            // method is declared on `Response` only for the LLM-facing type surface and
            // must never be dispatched as a real (importless) interface method.
            if name.name == "json"
                && matches!(&recv_ty, Type::InterfaceRef { name: iface, .. } if iface == "Response")
            {
                return self.infer_response_json_call(
                    typed_receiver,
                    &recv_ty,
                    type_args,
                    args,
                    expected,
                    span,
                );
            }
            // A generic receiver inferred in isolation can't resolve its own type
            // parameters and reports a premature "cannot infer" error — e.g.
            // `new Map()` in `new Map().set(k, v)`. The enclosing call resolves
            // those parameters: from the call arguments (`set(k, v)` binds K, V)
            // and/or, for builder methods that return the receiver's own type,
            // from the call's expected type. Drop the premature diagnostic; genuine
            // ambiguity resurfaces where the value is used. Only the "cannot infer"
            // entries are removed, so any real error in the receiver survives.
            if type_contains_type_var(&recv_ty)
                && let Some((sig, interface_bindings, _, _)) =
                    self.find_method(&recv_ty, &name.name)
            {
                use crate::typechecker::type_param_substitution::TypeParamSubstitution;
                let deferred: Vec<_> = self
                    .diagnostics
                    .split_off(diags_before)
                    .into_iter()
                    .filter(|d| !d.message.starts_with("cannot infer type parameter"))
                    .collect();
                self.diagnostics.extend(deferred);
                // When the expected type pins the receiver's parameters through the
                // method's return type, re-infer with the implied type so the
                // receiver node carries fully resolved generics.
                if let Some(want) = expected {
                    let mut probe = TypeParamSubstitution::new();
                    for (k, v) in &interface_bindings {
                        probe.insert(k.clone(), v.clone());
                    }
                    let _ = probe.unify(&sig.ret, want, self.resolver());
                    let desired = probe
                        .apply(&recv_ty, &self.type_limits)
                        .map_err(super::type_limit_at(span))?;
                    if desired != recv_ty && !type_contains_type_var(&desired) {
                        let reinferred = self.infer_expr(*receiver, Some(&desired))?;
                        typed_receiver = reinferred.0;
                        recv_ty = reinferred.1;
                    }
                }
            }
            if self.reject_unsupported_array_call(&recv_ty, name) {
                return Ok((TypedExprKind::Null, Type::Error));
            }
            if let Some(methods) = self.string_or_array_methods(&recv_ty, &name.name) {
                let call = MethodCallSite {
                    name: name.clone(),
                    type_args,
                    args,
                    expected,
                    span,
                };
                return self.string_or_array_method_call(typed_receiver, methods, call);
            }
            if let Some(method) = self.find_method(&recv_ty, &name.name) {
                let call = MethodCallSite {
                    name: name.clone(),
                    type_args,
                    args,
                    expected,
                    span,
                };
                return self.infer_found_method_call(typed_receiver, &recv_ty, method, call);
            }
            if matches!(recv_ty.peel(), Type::InterfaceRef { .. })
                && self
                    .lookup_interface_property(&recv_ty, &name.name)
                    .is_none()
            {
                let help = self.interface_member_miss_help(&recv_ty, &name.name);
                self.error_with_help(
                    name.span,
                    format!("no method `{}` on `{}`", name.name, recv_ty),
                    help,
                );
                return Ok((TypedExprKind::Null, Type::Error));
            }
            // Special-case: `null.toString()` (or `(maybeNullable)
            // .toString()`) gets the narrow-first diagnostic
            // instead of the generic "no method" message — null is
            // a real type in the language and the right fix is
            // narrowing, not pretending toString doesn't exist.
            // Mirrors the old `to_string_intrinsic_for` behavior.
            if matches!(recv_ty, Type::Null) && name.name == "toString" {
                let recv_span = self
                    .typed_ast
                    .try_expr(typed_receiver)
                    .map_err(crate::typechecker::arena_failure)?
                    .span;
                let help = self.nullish_string_fix_help(recv_span, &recv_ty);
                self.error_with_help(
                    name.span,
                    "cannot call `.toString()` on a `null` value; \
                     narrow to a non-null type first"
                        .to_string(),
                    help,
                );
                // Diagnostic placeholder — the iface isn't real here
                // (Null has no interface). Codegen never sees this
                // node because the diagnostic blocks compilation.
                return Ok((
                    TypedExprKind::MethodCall {
                        receiver: typed_receiver,
                        iface: crate::mangle::prelude("Null"),
                        name: name.clone(),
                        args: Vec::new(),
                        type_predicate: None,
                    },
                    Type::String,
                ));
            }
            // A receiver that already reported has nothing left to dispatch on,
            // and the fall-through below re-infers the whole callee — which
            // re-infers this receiver and reports the identical diagnostic a
            // second time.
            if matches!(recv_ty, Type::Error) {
                self.walk_rejected_call_args(&args)?;
                return Ok((TypedExprKind::Null, Type::Error));
            }
            // Fall through: receiver type may carry a method-typed
            // field one day (function-typed object fields when those
            // land), or this is a real "no method" diagnostic. The
            // legacy field-access-then-call path below handles it.
        }

        // Generic dispatch — when the callee is a bare identifier
        // resolving to a generic top-level function, route to the
        // explicit-args + bidirectional + arg-walk pipeline.
        // Non-generic functions and explicit-type-arg-on-non-generic
        // calls fall through to the regular path below; the latter
        // produces a "type arguments not allowed on a non-generic
        // function" diagnostic so the user gets a clear error.
        if let ExprKind::Identifier(ident) = &callee_kind
            && let Some(entry) = self.lookup_top_function(&ident.name)
            && let ValueKind::Function {
                generics,
                params,
                ret,
                type_predicate,
                ..
            } = &entry.kind
            && !generics.is_empty()
        {
            return self.infer_generic_call(
                ident.clone(),
                generics.clone(),
                params.clone(),
                ret.clone(),
                entry.mangled_name.clone(),
                type_predicate.clone(),
                type_args,
                args,
                expected,
                span,
                super::generic::GenericCallee::Function,
            );
        }

        if let Some(targs) = &type_args {
            self.error(
                span,
                format!(
                    "type arguments are only valid on generic functions; got {} argument(s)",
                    targs.len(),
                ),
            );
        }

        let (typed_callee, callee_ty) = self.infer_expr(callee, None)?;
        // call-signature dispatch — when the callee types
        // as an `InterfaceRef` declaring `@call`, route through the
        // same method-call pipeline as `find_method(_, "new")` for
        // `new` Receiver is `typed_callee` (the
        // already-evaluated callee expression); the sentinel name
        // `@call` resolves against the interface's `methods` map.
        // On a miss we fall through to the existing "cannot call
        // value of type X" diagnostic below.
        if matches!(callee_ty.peel(), Type::InterfaceRef { .. })
            && let Some((sig, interface_bindings, iface_mangled, _dispatch)) =
                self.find_method(&callee_ty, "@call")
        {
            let call_name = Ident {
                name: "@call".to_string(),
                span,
            };
            return Ok(
                if interface_bindings.is_empty() && sig.generics.is_empty() {
                    self.infer_method_call(
                        typed_callee,
                        iface_mangled,
                        call_name,
                        sig,
                        type_args,
                        args,
                        span,
                    )?
                } else {
                    self.infer_generic_method_call(
                        typed_callee,
                        iface_mangled,
                        call_name,
                        sig,
                        interface_bindings,
                        type_args,
                        args,
                        expected,
                        span,
                    )?
                },
            );
        }
        // also lift `has_rest` from the function type so a
        // call through a function-typed value (arrow stored in a
        // `const`, callback param) honors the variadic signature
        // shape. Top-level named functions go through `named_params`
        // below; this path covers everything else.
        let callee_has_rest = matches!(callee_ty.peel(), Type::Function { has_rest: true, .. },);
        let callee_optional = match callee_ty.peel() {
            Type::Function { optional, .. } => *optional,
            _ => 0,
        };
        let (param_types, ret_ty) = match callee_ty.peel() {
            Type::Function { params, ret, .. } => (Some(params.clone()), (**ret).clone()),
            Type::Error => (None, Type::Error),
            // calling an un-narrowed `unknown` value is
            // rejected — the user must narrow via `typeof x ===
            // "function"` (or any of the other predicates) first.
            // The "narrow first" wording mirrors the field/index
            // rejection diagnostics introduced for `Type::Unknown`.
            Type::Unknown => {
                self.error_with_help(
                    span,
                    "cannot call value of type `unknown`".to_string(),
                    vec![
                        "narrow first with `typeof x === \"function\"` or a \
                         user-defined type guard before calling"
                            .to_string(),
                    ],
                );
                (None, Type::Error)
            }
            _ => {
                let culprit = self.nullish_culprit(&[(typed_callee, &callee_ty)], |t| {
                    matches!(t.peel(), Type::Function { .. })
                });
                let help = if culprit.is_some() {
                    let callee_span = self
                        .typed_ast
                        .try_expr(typed_callee)
                        .map_err(super::arena_failure)?
                        .span;
                    let callee = self.rewritable_snippet(callee_span);
                    vec![format!(
                        "call it only when present with `{callee}?.(…)`, or assert it with `{callee}!(…)`"
                    )]
                } else {
                    self.definition_help(&callee_ty)
                };
                self.error_with_narrowing_hint(
                    span,
                    format!("cannot call value of type `{callee_ty}`"),
                    help,
                    culprit,
                )?;
                (None, Type::Error)
            }
        };

        // if the callee is a top-level non-generic
        // identifier, fetch the full `Vec<Param>` so we can see
        // per-parameter defaults. Structural function types retain optional
        // arity; omitted arguments use undefined and the callee runs defaults.
        let named_params: Option<Vec<crate::Param>> =
            if let ExprKind::Identifier(ident) = &callee_kind {
                self.lookup_top_function(&ident.name)
                    .and_then(|entry| match &entry.kind {
                        ValueKind::Function {
                            params, generics, ..
                        } if generics.is_empty() => Some(params.clone()),
                        _ => None,
                    })
            } else {
                None
            };
        // variadic shape — `has_rest` lifts the max-args cap
        // and `fixed_count` is the number of leading non-rest params.
        // For named top-level callees we use the resolved `Param`
        // list (which carries defaults too); for any other
        // function-typed callable (arrow stored in a `const`, etc.)
        // we read the rest flag off the lifted `Type::Function`.
        let has_rest = named_params
            .as_ref()
            .is_some_and(|ps| ps.last().is_some_and(|p| p.rest))
            || (named_params.is_none() && callee_has_rest);
        let fixed_count = if let Some(ps) = &named_params {
            ps.iter().take_while(|p| !p.rest).count()
        } else if callee_has_rest {
            param_types
                .as_ref()
                .map_or(0, |t| t.len().saturating_sub(1))
        } else {
            param_types.as_ref().map_or(0, std::vec::Vec::len)
        };
        let (min_args, max_args) = match (&named_params, &param_types) {
            (Some(ps), _) => {
                let max = if has_rest { usize::MAX } else { ps.len() };
                let min = required_parameter_count(ps);
                (min, max)
            }
            (None, Some(ts)) => {
                if callee_has_rest {
                    // Trailing rest in the function type: callsite
                    // accepts `(ts.len() - 1)+` args.
                    (
                        ts.len().saturating_sub(1).saturating_sub(callee_optional),
                        usize::MAX,
                    )
                } else {
                    (ts.len().saturating_sub(callee_optional), ts.len())
                }
            }
            (None, None) => (0, 0),
        };

        let arity_ok = param_types.is_some() && args.len() >= min_args && args.len() <= max_args;

        if let Some(ref params) = param_types
            && !arity_ok
        {
            // When the callee is a bare identifier resolving to a
            // top-level non-generic function, lift the `Function` form
            // (with names from `ValueKind::Function`) instead of the
            // anonymous form. Anything else — closures, function-typed
            // values, fields — falls back to `Anon` since no names
            // exist at that callable.
            let lift_function: Option<(String, Vec<crate::Param>)> =
                if let ExprKind::Identifier(ident) = &callee_kind {
                    named_params
                        .as_ref()
                        .map(|ps| (ident.name.clone(), ps.clone()))
                } else {
                    None
                };
            let lift_doc = lift_function
                .as_ref()
                .and_then(|(n, _)| self.lookup_function_doc(n));
            let help = match &lift_function {
                Some((name, sig_params)) => self.format_signature(SignatureKind::Function {
                    name,
                    predicate: None,
                    generics: &[],
                    params: sig_params,
                    ret: &ret_ty,
                    doc: lift_doc.as_ref(),
                }),
                None => self.format_signature(SignatureKind::Anon {
                    params,
                    ret: &ret_ty,
                    has_rest,
                    optional: callee_optional,
                }),
            };
            let msg = if has_rest {
                format!("expected {}+ argument(s), got {}", min_args, args.len(),)
            } else if min_args == max_args {
                format!("expected {} argument(s), got {}", max_args, args.len())
            } else {
                format!(
                    "expected {}-{} argument(s), got {}",
                    min_args,
                    max_args,
                    args.len(),
                )
            };
            let mut hints = vec![help];
            if lift_function.is_none() {
                hints.extend(
                    self.render_optional_help(super::type_diff::guard_loss_note(&callee_ty)),
                );
            }
            self.error_with_help(span, msg, hints);
        }

        // trailing args after `fixed_count` are bound to the
        // rest element type. Use it as the per-arg hint so e.g.
        // `sum(1, 2)` against `(...n: number[])` hints each arg as
        // `number`.
        let rest_elem_ty: Option<Type> = if has_rest {
            param_types
                .as_ref()
                .and_then(|tys| tys.get(fixed_count))
                .and_then(Type::rest_element)
                .cloned()
        } else {
            None
        };
        let extra = named_params
            .as_ref()
            .map_or(0, |ps| ps.len().saturating_sub(args.len()));
        let mut typed_args = Vec::with_capacity(args.len() + extra);
        for (i, &arg_id) in args.iter().enumerate() {
            let hint = if i < fixed_count {
                param_types
                    .as_ref()
                    .and_then(|p| p.get(i))
                    .cloned()
                    .map(|ty| {
                        let optional = named_params
                            .as_ref()
                            .and_then(|ps| ps.get(i))
                            .is_some_and(crate::Param::is_omittable);
                        crate::ObjectField::widen_optional(optional, ty)
                    })
            } else {
                rest_elem_ty.clone()
            };
            let (typed_id, _) = self.infer_expr(arg_id, hint.as_ref())?;
            typed_args.push(typed_id);
        }
        if arity_ok {
            if let Some(ps) = &named_params {
                self.fill_omitted_defaults(ps, args.len(), span, &mut typed_args)?;
            } else {
                for _ in typed_args.len()..fixed_count {
                    typed_args.push(self.synthesize_default_arg(
                        &crate::DefaultValue::Undefined,
                        &Type::Undefined,
                        span,
                    )?);
                }
            }
        }
        if arity_ok && let Some(elem_ty) = rest_elem_ty {
            self.pack_rest_tail(fixed_count, elem_ty, span, &mut typed_args)?;
        }

        // Static dispatch when the callee is a bare top-level
        // identifier — emit a `Call` with the resolved mangled name
        // so codegen can lower to a direct `call $idx`. Anything else
        // (closure value, field access, etc.) goes through
        // `CallClosure`, which dispatches via `call_ref`.
        let kind = if let ExprKind::Identifier(ident) = &callee_kind
            && let Some(entry) = self.lookup_top_function(&ident.name)
        {
            let mangled = entry.mangled_name.clone();
            let package = entry.package_name.clone();
            let symbol = entry.symbol_name.clone();
            // a direct call to a guard function carries the
            // resolved predicate to its `TypedExprKind::Call` so
            // `predicate_envs` can narrow without re-looking-up the
            // symbol.
            let type_predicate = match &entry.kind {
                ValueKind::Function { type_predicate, .. } => type_predicate.clone().map(Box::new),
                _ => None,
            };
            let target = StaticCallTarget {
                package: &package,
                symbol: &symbol,
                mangled,
            };
            return self.static_call_expr(target, typed_args, type_predicate, &ret_ty, span);
        } else {
            TypedExprKind::CallClosure {
                callee: typed_callee,
                args: typed_args,
            }
        };
        Ok((kind, ret_ty))
    }

    /// `filter`, `find` and `findLast` on an array, given a type guard
    /// `(x) => x is S`, return `S[]` or `S | undefined`, as tsc's overloads do. The
    /// call keeps its declared result type and is wrapped in the cast `as`
    /// would build, so a guard that lies traps instead of reading a wrong type.
    fn narrow_by_callback_predicate(
        &mut self,
        method: &str,
        (kind, ty): (TypedExprKind, Type),
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let callback = match &kind {
            TypedExprKind::MethodCall { args, .. } => args.first().copied(),
            TypedExprKind::GenericMethodCall { args, .. } => args.first().map(|arg| arg.expr),
            _ => None,
        };
        let Some(callback) = callback else {
            return Ok((kind, ty));
        };
        let callback_ty = self
            .typed_ast
            .try_expr(callback)
            .map_err(crate::typechecker::arena_failure)?
            .ty
            .clone();
        let Type::Function {
            predicate: Some(predicate),
            ..
        } = callback_ty.peel()
        else {
            return Ok((kind, ty));
        };
        if predicate.parameter_index != 0 {
            return Ok((kind, ty));
        }
        let guarded = predicate.asserted_type.clone();
        let target_ty = match method {
            "filter" => Type::Array(Box::new(guarded)),
            "find" | "findLast" => Type::union(vec![guarded, Type::Undefined]),
            _ => return Ok((kind, ty)),
        };
        let shape = self.reduce_interfaces_to_shapes(&target_ty);
        let fits = assignable(&ty, &shape, self.resolver());
        let check = (!fits).then(|| Box::new(shape));
        let value = self
            .typed_ast
            .try_push_expr(TypedExpr { kind, span, ty })
            .map_err(crate::typechecker::arena_failure)?;
        Ok((
            TypedExprKind::Cast {
                value,
                target_ty: target_ty.clone(),
                check,
            },
            target_ty,
        ))
    }

    /// Computes `flat`'s return type by un-nesting `depth` array levels from the
    /// receiver's element type. `depth` must be a non-negative integer literal
    /// (default `1`) so the result type is statically known; anything else is a
    /// compile error and the depth falls back to `1`.
    fn array_flat_return_type(
        &mut self,
        recv_ty: &Type,
        args: &[ExprId],
    ) -> Result<Type, CompilerFailure> {
        let elem = match recv_ty.peel() {
            Type::Array(inner) => (**inner).clone(),
            _ => return Ok(Type::Error),
        };
        let depth = match args.first() {
            None => 1usize,
            Some(arg) => {
                let arg_expr = self.ast.try_expr(*arg).map_err(super::arena_failure)?;
                match &arg_expr.kind {
                    ExprKind::Number(v) if v.is_finite() && *v >= 0.0 && v.fract() == 0.0 => {
                        *v as usize
                    }
                    _ => {
                        let arg_span = arg_expr.span;
                        self.error_with_help(
                            arg_span,
                            "`flat`'s depth must be a non-negative integer literal".to_string(),
                            vec![
                                "pass a literal like `.flat()` or `.flat(2)`, or chain `.flat().flat()` for deeper flattening"
                                    .to_string(),
                            ],
                        );
                        1
                    }
                }
            }
        };
        let mut result_elem = elem;
        for _ in 0..depth {
            match result_elem.peel() {
                Type::Array(inner) => result_elem = (**inner).clone(),
                _ => break,
            }
        }
        Ok(Type::Array(Box::new(result_elem)))
    }

    /// Typecheck a method call where neither the interface nor the
    /// method declares any generic parameters. No substitution work
    /// is needed — the sig's params + return type are already
    /// concrete. Just an arity check and a per-arg infer with the
    /// declared param types as hints.
    ///
    /// Anything with substitution work (interface generics like
    /// `Array<T>`, method generics like `map<U>`, or both) routes
    /// to [`infer_generic_method_call`](super::generic) instead.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn infer_method_call(
        &mut self,
        typed_receiver: ExprId,
        iface_mangled: crate::MangledName,
        name: Ident,
        sig: MethodSig,
        type_args: Option<Vec<TypeAnnotation>>,
        args: Vec<ExprId>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if !sig.generics.is_empty() {
            return Err(
                super::inference_failure("generic method reached non-generic dispatch")
                    .with_span(span),
            );
        }
        let receiver_ty = self
            .typed_ast
            .try_expr(typed_receiver)
            .map_err(crate::typechecker::arena_failure)?
            .ty
            .clone();
        if let Some(targs) = &type_args {
            let help = self.format_signature(SignatureKind::Method {
                receiver_ty: &receiver_ty,
                name: &name.name,
                sig: &sig,
            });
            self.error_with_help(
                span,
                format!(
                    "method `{}` is not generic; got {} type argument(s)",
                    name.name,
                    targs.len(),
                ),
                vec![help],
            );
        }
        // `typed_args` comes back 1:1 with `sig.params` — omitted
        // defaulted slots synthesized, a variadic tail packed into one
        // array — which is what codegen's fixed-arity wrapper call needs.
        let typed_args = self.bind_param_call_args(
            &sig.params,
            &sig.ret,
            CallLift::Method {
                receiver_ty: &receiver_ty,
                name: &name.name,
                sig: &sig,
            },
            &args,
            span,
        )?;
        // non-generic guard methods (e.g.
        // `Array.isArray(value: unknown): value is unknown[]`)
        // land here. The sig is already concrete — no substitution
        // needed — so the declared predicate carries directly onto
        // the typed node.
        let type_predicate = sig.predicate.map(Box::new);
        // a non-generic sig with an `(ref null $Object)`-
        // shaped param (`TypeVar` / `Unknown` / a `Union(...)` whose
        // members don't share one value-type) needs the same boxing
        // that the `Type::TypeVar` path gets — primitives must be
        // boxed into `$BoxedNumber` / `$BoxedBoolean` before they
        // enter the wrapper. Detect the shape here and emit
        // `GenericMethodCall` with `is_generic: true` for those slots
        // so the codegen at
        // `function_emitter::expr::emit_method_call_with_receiver_on_stack`
        // boxes them. `Union` is conservative — even when every
        // member is already an `$Object` subtype, `emit_box` is a
        // no-op so the extra flag is harmless.
        let needs_box = |t: &Type| -> bool {
            matches!(t.peel(), Type::TypeVar(_) | Type::Unknown | Type::Union(_))
        };
        let any_object_shaped = sig.params.iter().any(|p| needs_box(&p.ty));
        let return_is_object_shaped = needs_box(&sig.ret);
        if any_object_shaped || return_is_object_shaped {
            let generic_args: Vec<crate::GenericArgument> = typed_args
                .into_iter()
                .zip(sig.params.iter())
                .map(|(expr, p)| crate::GenericArgument {
                    expr,
                    is_generic: needs_box(&p.ty),
                })
                .collect();
            let return_cast = if return_is_object_shaped {
                Some(sig.ret.clone())
            } else {
                None
            };
            return Ok((
                TypedExprKind::GenericMethodCall {
                    receiver: typed_receiver,
                    iface: iface_mangled,
                    name,
                    args: generic_args,
                    return_cast,
                    type_predicate,
                },
                sig.ret,
            ));
        }
        Ok((
            TypedExprKind::MethodCall {
                receiver: typed_receiver,
                iface: iface_mangled,
                name,
                args: typed_args,
                type_predicate,
            },
            sig.ret,
        ))
    }

    /// build a synthesized typed expression for an omitted
    /// argument from its parameter's resolved [`crate::DefaultValue`].
    /// Used at every call site that takes advantage of a defaulted
    /// parameter — defaults are re-emitted per call (matching JS / TS
    /// semantics, and so a `GlobalConst` default re-reads the const
    /// on every call rather than caching the value).
    ///
    /// `span` is the surrounding call's span — the same anchor the
    /// surrounding `Call`/`MethodCall` carries — so DWARF + diagnostic
    /// mapping point at the call site, not at the original parameter
    /// declaration.
    pub(super) fn synthesize_default_arg(
        &mut self,
        default: &crate::DefaultValue,
        param_ty: &Type,
        span: Span,
    ) -> Result<ExprId, crate::compiler_error::CompilerFailure> {
        // The primitive arms (`Number`/`String`/`Boolean`) carry the literal's
        // own type, not the parameter's. The call-boundary coercion boxes an
        // argument by comparing its typed-AST type against the parameter slot;
        // typing a bare `f64`/`i32` literal as the wider slot (`unknown`, a
        // union, `T | null`) reads as "already a ref" and skips the box, so the
        // callee sees a primitive in a ref slot. The remaining arms already
        // synthesize a reference value, so they keep the parameter's type.
        let (kind, ty) = match default {
            crate::DefaultValue::Number(n)
            | crate::DefaultValue::OmittedNumber { omitted: n, .. } => {
                (TypedExprKind::Number(*n), Type::Number)
            }
            crate::DefaultValue::String(s) => (TypedExprKind::String(s.clone()), Type::String),
            crate::DefaultValue::Boolean(b) => (TypedExprKind::Boolean(*b), Type::Boolean),
            crate::DefaultValue::Null => (TypedExprKind::Null, Type::Null),
            crate::DefaultValue::Undefined => (TypedExprKind::Undefined, Type::Undefined),
            crate::DefaultValue::EmptyArray => {
                let element_ty = match param_ty {
                    Type::Array(t) => (**t).clone(),
                    _ => Type::Error,
                };
                (
                    TypedExprKind::ArrayLiteral {
                        elements: Vec::<crate::TypedArrayElement>::new(),
                        element_ty,
                    },
                    param_ty.clone(),
                )
            }
            crate::DefaultValue::EmptyObject => (
                TypedExprKind::ObjectLiteral {
                    members: Vec::new(),
                    fields: Vec::new(),
                },
                param_ty.clone(),
            ),
            crate::DefaultValue::GlobalConst(_) => {
                // Rejected at signature time — should be unreachable.
                // Mint a `Null` placeholder so downstream emission
                // stays well-formed even if signature validation is
                // ever bypassed.
                (TypedExprKind::Null, Type::Error)
            }
            crate::DefaultValue::EnumVariant {
                enum_mangled,
                variant,
                value,
            } => {
                let variant_ident = Ident {
                    name: variant.clone(),
                    span,
                };
                match value {
                    crate::EnumVariantValue::Number(n) => (
                        TypedExprKind::NumberEnumMember {
                            enum_mangled: enum_mangled.clone(),
                            variant: variant_ident,
                            value: *n,
                        },
                        param_ty.clone(),
                    ),
                    crate::EnumVariantValue::String(s) => (
                        TypedExprKind::StringEnumMember {
                            enum_mangled: enum_mangled.clone(),
                            variant: variant_ident,
                            value: s.clone(),
                        },
                        param_ty.clone(),
                    ),
                }
            }
        };
        self.typed_ast
            .try_push_expr(TypedExpr { kind, span, ty })
            .map_err(crate::typechecker::arena_failure)
    }

    /// Append an argument for each fixed slot past `supplied` that the call
    /// left out. Must run before [`Self::pack_rest_tail`], so
    /// `typed_args[..fixed_count]` is a clean fixed partition and
    /// `[fixed_count..]` is the tail.
    ///
    /// A slot whose default is `None` had its declared default rejected at
    /// signature time — already reported — and still gets a placeholder, so
    /// the surviving defaults keep their own slots instead of sliding left.
    pub(super) fn fill_omitted_defaults(
        &mut self,
        params: &[crate::Param],
        supplied: usize,
        span: Span,
        typed_args: &mut Vec<ExprId>,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        let fixed_count = params.iter().take_while(|p| !p.rest).count();
        if supplied >= fixed_count {
            return Ok(());
        }
        for p in &params[supplied..fixed_count] {
            let id = match &p.default {
                Some(default) => self.synthesize_default_arg(default, &p.ty, span)?,
                None if p.optional => {
                    self.synthesize_default_arg(&crate::DefaultValue::Undefined, &p.ty, span)?
                }
                None => {
                    return Err(super::inference_failure(
                        "required argument omitted after arity validation",
                    )
                    .with_span(span));
                }
            };
            typed_args.push(id);
        }
        Ok(())
    }

    /// Collapse the trailing arguments past `fixed_count` into the single
    /// array that fills a variadic signature's rest slot, so `typed_args`
    /// lines up 1:1 with the parameter list and codegen emits variadic and
    /// fixed-arity calls identically. An empty tail packs an empty array.
    pub(super) fn pack_rest_tail(
        &mut self,
        fixed_count: usize,
        element_ty: Type,
        span: Span,
        typed_args: &mut Vec<ExprId>,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        // The actual per-arg types ride through as elements; `element_ty`
        // carries the rest's declared element type for downstream consumers
        // (e.g. `PackageDeclaration::from_typed_ast`).
        let elements: Vec<crate::TypedArrayElement> = if typed_args.len() > fixed_count {
            typed_args
                .drain(fixed_count..)
                .map(crate::TypedArrayElement::Value)
                .collect()
        } else {
            Vec::new()
        };
        let array_id = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind: TypedExprKind::ArrayLiteral {
                    elements,
                    element_ty: element_ty.clone(),
                },
                span,
                ty: Type::Array(Box::new(element_ty)),
            })
            .map_err(crate::typechecker::arena_failure)?;
        typed_args.push(array_id);
        Ok(())
    }

    /// `new Foo(args)` typechecks as `Foo.new(args)`. The
    /// callee must be a value typed `InterfaceRef("FooConstructor")`
    /// whose interface declares a `new` method under `Dispatch::Static`.
    /// We synthesize the equivalent of a method-call lookup via
    /// `find_method(callee_ty, "new")` and reuse the existing
    /// `infer_method_call` / `infer_generic_method_call` pipelines so
    /// `new` lowers to a `TypedExprKind::MethodCall` — codegen never
    /// sees a separate `New` node.
    ///
    /// The bare `Foo.new(args)` form keeps working through the
    /// FieldAccess-callee path in `infer_call` (forgiveness rule).
    fn infer_new(
        &mut self,
        callee: ExprId,
        type_args: Option<Vec<TypeAnnotation>>,
        args: Vec<ExprId>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // `new ClassName(args)` — the callee names a class type. Construct an
        // instance: check the constructor args, result is the class instance
        // type. (Codegen of `new` is SUB-483; this is typecheck-only.)
        if let ExprKind::Identifier(ident) = &self
            .ast
            .try_expr(callee)
            .map_err(super::arena_failure)?
            .kind
            .clone()
            && let Some((class_mangled, ctor_params, class_generics)) = self
                .lookup_named_type(&ident.name)
                .and_then(|s| match &s.kind {
                    crate::TypeKind::Class {
                        constructor,
                        generics,
                        ..
                    } => Some((
                        s.mangled_name.clone(),
                        constructor.clone(),
                        generics.clone(),
                    )),
                    _ => None,
                })
        {
            if self.reject_private_constructor(&class_mangled, ConstructorUse::New, span) {
                // The parameters are private too: type the arguments on their
                // own rather than report how they miss a hidden signature.
                for annotation in type_args.iter().flatten() {
                    self.resolve_type(annotation)?;
                }
                for arg in args {
                    self.infer_expr(arg, None)?;
                }
                return Ok((TypedExprKind::Null, Type::Error));
            }
            let package = self.type_package(&ident.name);
            let ctor_mangled = crate::mangle::extend(&class_mangled, "constructor");
            // Generic class: the constructor is a receiver-less generic call —
            // explicit type args, expected-type seeding, and inference from the
            // ctor arguments all ride the shared generic-call core, lowering to
            // `GenericCall` on `<Class>#constructor`.
            if !class_generics.is_empty() {
                let ret = Type::class_ref(
                    package,
                    ident.name.clone(),
                    class_mangled,
                    class_generics
                        .iter()
                        .map(|g| Type::TypeVar(g.clone()))
                        .collect(),
                );
                let (kind, ty) = self.infer_generic_call(
                    ident.clone(),
                    class_generics,
                    ctor_params,
                    ret,
                    ctor_mangled,
                    None,
                    type_args,
                    args,
                    expected,
                    span,
                    super::generic::GenericCallee::Constructor,
                )?;
                // Written type arguments are screened in `resolve_type`;
                // inferred ones arrive here, and a `never` argument has no value
                // representation to erase into.
                if let Type::ClassRef { args: solved, .. } = ty.peel()
                    && let Some(offender) = solved
                        .iter()
                        .find_map(super::value_operand::valueless_within_type_argument)
                {
                    let offender = offender.clone();
                    self.error_with_help(
                        span,
                        format!(
                            "cannot infer a type argument of `{offender}` for class `{}`",
                            ident.name
                        ),
                        vec![format!(
                            "`{offender}` carries no value — pass an argument with a value \
                             type, or give an explicit type argument: `new {}<…>(…)`",
                            ident.name
                        )],
                    );
                    return Ok((kind, Type::Error));
                }
                return Ok((kind, ty));
            }
            let class_ty = Type::class_ref(package, ident.name.clone(), class_mangled, Vec::new());
            if type_args.is_some() {
                self.error(
                    span,
                    format!(
                        "class `{}` is not generic; remove the type arguments",
                        ident.name
                    ),
                );
            }
            let typed_args = self.bind_param_call_args(
                &ctor_params,
                &class_ty,
                CallLift::Constructor {
                    class_ty: &class_ty,
                },
                &args,
                span,
            )?;
            // `new Foo(args)` lowers to a call of the synthesized constructor
            // function (codegen emits it; same-package only in SUB-483).
            return Ok((
                TypedExprKind::Call {
                    mangled: ctor_mangled,
                    args: typed_args,
                    type_predicate: None,
                },
                class_ty,
            ));
        }
        let (typed_callee, callee_ty) = self.infer_expr(callee, None)?;
        if matches!(callee_ty, Type::Error) {
            return Ok((TypedExprKind::Null, Type::Error));
        }
        let new_name = Ident {
            name: "new".to_string(),
            span,
        };
        let Some((sig, interface_bindings, iface_mangled, _dispatch)) =
            self.find_method(&callee_ty, "new")
        else {
            // Probe for a constructor by convention: if `<Type>` is
            // also bound as a top-level value (the prelude registers
            // `Uint8Array` / `TextEncoder` / etc. this way), point at
            // it — the LLM probably wanted `new <Type>(...)` rather
            // than `new <instance>(...)`.
            let mut help: Vec<String> = Vec::new();
            if let Some((_, _, iface_name, _)) = callee_ty.interface_routing()
                && let Some(entry) = self.top_symbols.get(iface_name)
                && let crate::ValueKind::Const {
                    ty:
                        Type::InterfaceRef {
                            name: ctor_iface, ..
                        },
                    ..
                } = &entry.kind
                && self
                    .lookup_named_type(ctor_iface)
                    .and_then(|s| match &s.kind {
                        crate::TypeKind::Interface { methods, .. } => Some(methods),
                        _ => None,
                    })
                    .is_some_and(|methods| methods.contains_key("new"))
            {
                help.push(format!(
                    "did you mean `new {iface_name}(...)`? `{iface_name}` (the constructor) declares a `new` method, but `{iface_name}` instances don't.",
                ));
            }
            help.push(self.format_definition(&callee_ty));
            self.error_with_help(
                span,
                format!("`new` expects a constructor; `{callee_ty}` declares no `new` method",),
                help,
            );
            return Ok((TypedExprKind::Null, Type::Error));
        };
        // `new foo(args)` lowers to the same MethodCall as
        // `foo.new(args)` — the dispatch mode (Static vs Direct)
        // only changes whether the receiver is pushed or dropped at
        // the call site, and that decision lives in
        // `emit_method_call`. No reason to gate `new` on Static
        // dispatch: a Direct `new` method on an instance interface
        // is just an instance method whose name happens to be `new`,
        // and the prefix form is a perfectly valid alias for the
        // dotted form.
        Ok(
            if interface_bindings.is_empty() && sig.generics.is_empty() {
                self.infer_method_call(
                    typed_callee,
                    iface_mangled,
                    new_name,
                    sig,
                    type_args,
                    args,
                    span,
                )?
            } else {
                self.infer_generic_method_call(
                    typed_callee,
                    iface_mangled,
                    new_name,
                    sig,
                    interface_bindings,
                    type_args,
                    args,
                    expected,
                    span,
                )?
            },
        )
    }

    /// Build a statically-dispatched call node. A function from an `@mcp/<server>`
    /// package (recognized by the package's `mcp_server` flag, looked up via the
    /// resolved mangled name) becomes a [`TypedExprKind::McpCall`]; everything else
    /// is a plain [`TypedExprKind::Call`]. Routing every call/import form
    /// (`ns.tool()`, named-import `tool()`, namespace-symbol calls) through here is
    /// what keeps MCP recognition syntax-independent — and out of codegen.
    pub(super) fn static_call_expr(
        &mut self,
        target: StaticCallTarget<'_>,
        args: Vec<ExprId>,
        type_predicate: Option<Box<crate::TypePredicate>>,
        ret: &Type,
        span: Span,
    ) -> Result<(TypedExprKind, Type), crate::compiler_error::CompilerFailure> {
        Ok({
            if let Some(server) = self
                .packages_by_name
                .get(target.package)
                .and_then(|defs| defs.mcp_server.clone())
            {
                let mcp_call = TypedExprKind::McpCall {
                    server,
                    tool: target.symbol.to_string(),
                    args: args.clone(),
                };
                if matches!(ret.peel(), Type::Unknown) {
                    return Ok((mcp_call, Type::Unknown));
                }

                return Ok(match self.checked_cast_around(mcp_call, ret, span)? {
                    Ok(checked) => checked,
                    Err(reason) => {
                        self.error_with_help(
                            span,
                            format!(
                                "@mcp/{} return type `{ret}` is not runtime-verifiable: {reason}",
                                target.symbol
                            ),
                            vec![
                            "declare the tool return as `unknown`, or use a return schema whose \
                             generated type is supported by `as` validation"
                                .to_string(),
                        ],
                        );
                        (TypedExprKind::Null, Type::Error)
                    }
                });
            }
            (
                TypedExprKind::Call {
                    mangled: target.mangled,
                    args,
                    type_predicate,
                },
                ret.clone(),
            )
        })
    }

    /// Rewrite `session.get<T>(key)` into a runtime-checked cast.
    ///
    /// `get` is declared generic so callers can name the shape they expect, but
    /// the ordinary generic lowering would satisfy that `T` with `return_cast`,
    /// a Wasm representation cast that tests nothing — stored data of the wrong
    /// shape would arrive statically typed as `T` and never be verified. So the
    /// call node is pushed typed `unknown` and wrapped in a `Cast` carrying the
    /// reduced check shape, exactly as an MCP call with a known return type is
    /// (see [`Self::static_call_expr`]). Codegen then emits the same structural
    /// test `x as T` gets, and a mismatch throws a catchable `TypeError`.
    ///
    /// Call only for a [`crate::stdlib::session::declaration::is_checked_get`]
    /// mangled name; `call` is the `GenericCall` node the ordinary path would
    /// have returned. `type_args_written` separates an explicit `get<unknown>`
    /// from a bare `get(key)`, whose `T` defaulted to `unknown` and keeps its
    /// pre-generic unchecked-read meaning.
    pub(super) fn checked_session_get(
        &mut self,
        call: TypedExprKind,
        result_ty: &Type,
        type_args_written: bool,
        span: Span,
    ) -> Result<(TypedExprKind, Type), crate::compiler_error::CompilerFailure> {
        Ok({
            // An `unknown` target admits every value, and the cast machinery treats
            // it as a no-op widen that emits no test at all. As the *default* that
            // is the honest reading of `get(key)` — an unchecked read. Written out,
            // it asks for a check that cannot exist, so only that form is an error.
            if matches!(result_ty.peel(), Type::Unknown) && !type_args_written {
                return Ok((call, result_ty.clone()));
            }
            if matches!(result_ty.peel(), Type::Unknown) {
                self.error_with_help(
                    span,
                    "`session.get<unknown>` would not verify anything: `unknown` admits \
                 every value, so no runtime check is possible"
                        .to_string(),
                    vec![
                        "name the shape you expect — `session.get<Progress>(key)` — or drop \
                     the type argument and narrow the result yourself with a \
                     runtime-checked `as`: `session.get(key) as Progress`. Use \
                     `session.get<Progress>(key)` returns undefined when the key is absent."
                            .to_string(),
                    ],
                );
                return Ok((TypedExprKind::Null, Type::Error));
            }

            match self.checked_cast_around(call, result_ty, span)? {
                Ok(checked) => checked,
                Err(reason) => {
                    self.error_with_help(
                        span,
                        format!(
                            "`session.get<{result_ty}>` cannot be verified at runtime: {reason}"
                        ),
                        vec![format!(
                            "`session.get` checks the stored value against its type argument, so \
                         that argument must be one the runtime can test: an object, array, \
                         tuple, union, or primitive shape, optionally `| null`. Call it at a \
                         concrete type instead of `{result_ty}` — `session.get<Progress>(key)` \
                         — or drop the type argument and narrow the result yourself with a \
                         runtime-checked `as`."
                        )],
                    );
                    (TypedExprKind::Null, Type::Error)
                }
            }
        })
    }

    /// Rewrite a schema-checked call such as `llm.call<T>(model, prompt)` into a
    /// runtime-checked cast, and emit the JSON Schema for `T` that rides along
    /// to the provider.
    ///
    /// Mirrors [`Self::checked_session_get`] — same soundness argument, same
    /// `checked_cast_around` — with one addition: the schema gate. A typed call
    /// must pass **both** gates, because the schema surface is strictly
    /// narrower than what the cast machinery can test (KTD5). `Function`,
    /// `bigint`, `Uint8Array`, and `unknown` are all castable and none has a
    /// JSON Schema in the safe subset, so a type that cleared only the cast
    /// gate would reach a provider as a schema that constrained nothing.
    ///
    /// Both gates run here rather than at the wrap, because the emitted schema
    /// has to replace the trailing `schema` argument before the call node's
    /// argument list is frozen. `Ok(None)` is the untyped form, which sends no
    /// schema and gets no check; `Ok(Some(schema))` means both gates passed and
    /// the caller must wrap the call in [`Self::schema_checked_cast`]; `Err(())`
    /// means a diagnostic was reported (or deliberately suppressed) and the
    /// call is an error.
    ///
    /// `checked` describes the call, from [`crate::stdlib::schema_checked_call`].
    /// `type_args_written` separates an explicit `call<unknown>` from a bare
    /// `call(...)`, whose result is the untyped default and needs no check.
    pub(super) fn schema_checked_call_schema(
        &mut self,
        checked: &crate::stdlib::SchemaCheckedCall,
        result_ty: &Type,
        type_args_written: bool,
        span: Span,
    ) -> Result<Option<String>, ()> {
        let crate::stdlib::SchemaCheckedCall {
            callee,
            example,
            checks,
            answerer,
            untyped_hint,
            untyped_hint_for_unknown,
            untyped_hint_for_no_schema,
            ..
        } = checked;
        // No type argument: the call keeps its pre-generic meaning and returns
        // the `Completion` envelope, which the declaration already typed. There
        // is nothing to check and no schema to send.
        if !type_args_written {
            return Ok(None);
        }
        // Written `<unknown>` asks for a check that cannot exist. Unlike
        // `session.get`, there is no honest unchecked reading to fall back on —
        // the untyped form is a different, fully-typed result — so this is
        // caught here as well as by the schema gate, which would also reject it.
        if matches!(result_ty.peel(), Type::Unknown) {
            self.error_with_help(
                span,
                format!(
                    "`{callee}<unknown>` would not verify anything: `unknown` admits every \
                     value, so no runtime check is possible and its JSON Schema could only \
                     be `{{}}`, which constrains {answerer} to nothing"
                ),
                vec![format!(
                    "name the shape you expect — `{example}` — or drop the type argument \
                     and {untyped_hint_for_unknown}."
                )],
            );
            return Err(());
        }

        // An erased `T` — a type parameter of the *calling* function — is
        // reported against the cast gate rather than the schema gate. Both
        // reject it, but only this diagnostic says what to do about it, and it
        // is the wording `as` and MCP already use for the same mistake
        // (`unsupported_cast_target_reason`'s `TypeVar | GenericParam` arm), so
        // a program hitting it under `llm.call` reads the same advice it would
        // hit under `as`.
        let shape = self.reduce_interfaces_to_shapes(result_ty);
        if matches!(shape.peel(), Type::TypeVar(_) | Type::GenericParam { .. })
            && let Some(reason) =
                unsupported_cast_target_reason(&shape, self.resolver(), &mut Vec::new())
        {
            self.error_with_help(
                span,
                format!("`{callee}<{result_ty}>` cannot be verified at runtime: {reason}"),
                vec![format!(
                    "`{callee}` checks {checks} against its type argument, so \
                     that argument must be one the runtime can test, and the schema is \
                     emitted at compile time where `{result_ty}` is not yet known. Call it \
                     at a concrete type — `{example}` — inside the \
                     generic function, or drop the type argument and {untyped_hint}."
                )],
            );
            return Err(());
        }

        // The schema gate runs before the cast gate, because it is strictly
        // narrower (KTD5) *and* its rejections name the offending field. A
        // recursive type fails both; the schema reason points at the field that
        // closes the cycle, which is the one the author has to change.
        match self.json_schema_for(result_ty) {
            Ok(schema) => {
                // The cast gate still has to pass: it is what `checked_cast_around`
                // will re-run, and the two surfaces agree everywhere except the
                // arms handled above.
                if let Some(reason) =
                    unsupported_cast_target_reason(&shape, self.resolver(), &mut Vec::new())
                {
                    self.error_with_help(
                        span,
                        format!("`{callee}<{result_ty}>` cannot be verified at runtime: {reason}"),
                        vec![format!(
                            "`{callee}` checks {checks} against its type \
                             argument, so that argument must be one the runtime can test: \
                             an object, array, tuple, union, or primitive shape. Call it \
                             at a concrete type instead of `{result_ty}` — \
                             `{example}` — or drop the type \
                             argument and {untyped_hint}."
                        )],
                    );
                    return Err(());
                }
                Ok(Some(schema))
            }
            Err(reject) => {
                // A `Type::Error` already reported its own diagnostic; a second
                // one here would blame the same mistake twice.
                if !reject.cascading {
                    self.error_with_help(
                        span,
                        format!(
                            "`{callee}<{result_ty}>` has no JSON Schema: {}",
                            reject.describe()
                        ),
                        vec![format!(
                            "the schema sent to {answerer} is fully inlined and carries no \
                             `$ref`, so every field must be an object, array, tuple, union, \
                             enum, or primitive shape. Replace that field with one — a \
                             `string` for bytes or a big number, a named shape in place of \
                             `unknown` — or drop the type argument and {untyped_hint_for_no_schema}."
                        )],
                    );
                }
                Err(())
            }
        }
    }

    /// Wrap a gated schema-checked call in its checked cast. Split from
    /// [`Self::schema_checked_call_schema`] because the gates must run before the
    /// call node's arguments are frozen and this must run after.
    /// `checked_cast_around` cannot fail here: `schema_checked_call_schema`
    /// already ran the same cast gate on the same type, and passing it is what
    /// produced the schema that got us here.
    pub(super) fn schema_checked_cast(
        &mut self,
        call: TypedExprKind,
        result_ty: &Type,
        span: Span,
    ) -> Result<(TypedExprKind, Type), crate::compiler_error::CompilerFailure> {
        Ok({
            match self.checked_cast_around(call, result_ty, span)? {
                Ok(checked) => checked,
                Err(reason) => {
                    return Err(super::inference_failure(&format!(
                        "schema-checked result cast rejected a previously validated schema: {reason}"
                    ))
                    .with_span(span));
                }
            }
        })
    }

    /// Replace the trailing `schema` argument — which the declaration's `null`
    /// default just filled — with the compile-time schema string, the way
    /// `McpCall` carries its `server` and `tool` as constants.
    ///
    /// The slot is found by name rather than by index so the declaration can
    /// grow a parameter without silently overwriting the wrong argument; a
    /// program that passed a schema by hand has it replaced, which is why the
    /// parameter is documented as not being surface a program writes.
    pub(super) fn substitute_schema_argument(
        &mut self,
        params: &[crate::Param],
        typed_args: &mut [ExprId],
        schema: &str,
        span: Span,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        let Some(slot) = params.iter().position(|p| p.name == "schema") else {
            return Ok(());
        };
        let Some(arg) = typed_args.get_mut(slot) else {
            return Ok(());
        };
        *arg = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind: TypedExprKind::String(schema.to_string()),
                span,
                ty: Type::String,
            })
            .map_err(crate::typechecker::arena_failure)?;
        Ok(())
    }

    /// The inlined JSON Schema for `target_ty`, as the compact string the host
    /// function takes.
    ///
    /// Reduces interfaces to shapes first, as [`Self::checked_cast_around`]
    /// does, so the emitter sees the same structural type the check will, and
    /// resolves alias back-edges through the type namespace — without that
    /// expander every `AliasRef` survives the walk and is rejected as
    /// unresolvable.
    fn json_schema_for(
        &mut self,
        target_ty: &Type,
    ) -> Result<String, crate::typechecker::json_schema::SchemaReject> {
        let shape = self.reduce_interfaces_to_shapes(target_ty);
        let types = self.resolver();
        let expand = |ty: &Type| assignable::expand_alias_ref(ty, types);
        let value = crate::typechecker::json_schema::json_schema_with(&shape, &expand)?;
        Ok(value.to_string())
    }

    /// Wrap `call` in the runtime-checked cast that verifies its result is
    /// really a `target_ty`. The call node is pushed typed `unknown` — so
    /// nothing downstream believes its static type before the check runs — and
    /// the `Cast` around it carries the interface-reduced shape codegen walks,
    /// giving the same structural test `x as T` gets.
    ///
    /// This is the soundness-critical construction behind every "the host
    /// handed us data, prove it matches" call — an MCP tool with a declared
    /// return type and `session.get<T>` — so both go through here rather than
    /// building the `Cast` themselves. `Err` carries the reason `target_ty`
    /// cannot be verified; the caller words its own diagnostic around it.
    fn checked_cast_around(
        &mut self,
        call: TypedExprKind,
        target_ty: &Type,
        span: Span,
    ) -> Result<Result<(TypedExprKind, Type), &'static str>, CompilerFailure> {
        let shape = self.reduce_interfaces_to_shapes(target_ty);
        if let Some(reason) =
            unsupported_cast_target_reason(&shape, self.resolver(), &mut Vec::new())
        {
            return Ok(Err(reason));
        }
        let value = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind: call,
                span,
                ty: Type::Unknown,
            })
            .map_err(crate::typechecker::arena_failure)?;
        Ok(Ok((
            TypedExprKind::Cast {
                value,
                target_ty: target_ty.clone(),
                check: Some(Box::new(shape)),
            },
            target_ty.clone(),
        )))
    }

    /// dispatch a `<ns>.<member>(args)` call where `<ns>` is
    /// a namespace-imported package. Lifts the member's
    /// package-export mangled name into a static call (or `McpCall` for
    /// `@mcp/<server>` packages). Argument binding — arity, optional/
    /// default fill-in, rest packing, and generic inference — mirrors the
    /// bare-identifier static-call path (generic calls literally route
    /// through `infer_generic_call`) so `ns.fn(...)` and the named-import
    /// `fn(...)` form bind identically (spec §2.4).
    #[allow(clippy::too_many_arguments)]
    fn infer_namespace_call(
        &mut self,
        package_name: String,
        sym: ValueSymbol,
        recv_ident: &Ident,
        member: &Ident,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        args: Vec<ExprId>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let ValueKind::Function {
            generics,
            params,
            ret,
            type_predicate,
            ..
        } = &sym.kind
        else {
            self.error(
                span,
                format!("`{}.{}` is not callable", recv_ident.name, member.name,),
            );
            return Ok((
                TypedExprKind::Call {
                    mangled: sym.mangled_name.clone(),
                    args: Vec::new(),
                    type_predicate: None,
                },
                Type::Error,
            ));
        };
        let display = format!("{}.{}", recv_ident.name, member.name);
        // Generic functions take the same explicit-args + bidirectional +
        // arg-walk pipeline as bare-identifier generic calls, threaded with
        // the package-export mangled name.
        if !generics.is_empty() {
            let callee_ident = Ident {
                name: display,
                span: member.span,
            };
            return self.infer_generic_call(
                callee_ident,
                generics.clone(),
                params.clone(),
                ret.clone(),
                sym.mangled_name.clone(),
                type_predicate.clone(),
                type_args,
                args,
                expected,
                span,
                super::generic::GenericCallee::Function,
            );
        }
        if let Some(targs) = &type_args {
            self.error(
                span,
                format!(
                    "type arguments are only valid on generic functions; got {} argument(s)",
                    targs.len(),
                ),
            );
        }
        let typed_args = self.bind_param_call_args(
            params,
            ret,
            CallLift::Function { name: &display },
            &args,
            span,
        )?;
        let type_predicate = type_predicate.clone().map(Box::new);
        let target = StaticCallTarget {
            package: &package_name,
            symbol: &member.name,
            mangled: sym.mangled_name.clone(),
        };
        self.static_call_expr(target, typed_args, type_predicate, ret, span)
    }

    /// `ClassName.member(args)` — dispatch a static method as a direct `Call`
    /// on the defining class's `Class#static#name` key (inheritance is resolved
    /// here, so `B.f()` calls `A#static#f`), call a function-typed static field
    /// through `CallClosure`, or diagnose the miss.
    #[allow(clippy::too_many_arguments)]
    fn infer_class_static_call(
        &mut self,
        class_name: String,
        class_mangled: crate::MangledName,
        member: Ident,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        args: Vec<ExprId>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        use super::classes::StaticResolution;
        let display = format!("{class_name}.{}", member.name);
        Ok(
            match self.class_static_in_chain(&class_mangled, &member.name) {
                Some((StaticResolution::Method(sig, vis), owner)) => {
                    self.check_class_callable_types(&owner, span);
                    self.check_static_privacy(vis, &owner, &class_name, &member);
                    let mangled = crate::mangle::static_member(&owner, &member.name);
                    if !sig.generics.is_empty() {
                        let callee_ident = Ident {
                            name: display,
                            span: member.span,
                        };
                        return self.infer_generic_call(
                            callee_ident,
                            sig.generics.clone(),
                            sig.params.clone(),
                            sig.ret.clone(),
                            mangled,
                            sig.predicate.clone(),
                            type_args,
                            args,
                            expected,
                            span,
                            super::generic::GenericCallee::Function,
                        );
                    }
                    if let Some(targs) = &type_args {
                        self.error(
                            span,
                            format!(
                                "type arguments are only valid on generic functions; got {} \
                             argument(s)",
                                targs.len(),
                            ),
                        );
                    }
                    let typed_args = self.bind_param_call_args(
                        &sig.params,
                        &sig.ret,
                        CallLift::Function { name: &display },
                        &args,
                        span,
                    )?;
                    (
                        TypedExprKind::Call {
                            mangled,
                            args: typed_args,
                            type_predicate: sig.predicate.clone().map(Box::new),
                        },
                        sig.ret.clone(),
                    )
                }
                Some((StaticResolution::Field(field), owner)) => {
                    self.check_class_callable_types(&owner, span);
                    self.check_static_privacy(field.visibility, &owner, &class_name, &member);
                    let mangled = crate::mangle::static_member(&owner, &member.name);
                    self.note_rebindable_static(&field, &owner, &member.name);
                    let Type::Function {
                        params,
                        ret,
                        has_rest,
                        ..
                    } = field.ty.peel().clone()
                    else {
                        self.error(span, format!("`{display}` is not callable"));
                        self.walk_rejected_call_args(&args)?;
                        return Ok((TypedExprKind::Null, Type::Error));
                    };
                    let callee = self
                        .typed_ast
                        .try_push_expr(TypedExpr {
                            kind: TypedExprKind::GlobalRef {
                                mangled,
                                name: member.clone(),
                            },
                            span: member.span,
                            ty: field.ty.clone(),
                        })
                        .map_err(crate::typechecker::arena_failure)?;
                    let typed_args = self.bind_fn_type_call_args(
                        &params,
                        &ret,
                        has_rest,
                        CallLift::Anon { ty: &field.ty },
                        &args,
                        span,
                    )?;
                    (
                        TypedExprKind::CallClosure {
                            callee,
                            args: typed_args,
                        },
                        (*ret).clone(),
                    )
                }
                None => {
                    self.report_missing_static(&class_name, &class_mangled, &member);
                    self.walk_rejected_call_args(&args)?;
                    (TypedExprKind::Null, Type::Error)
                }
            },
        )
    }

    /// `ClassName.member` in non-call position: a static field reads the backing
    /// module global; a non-generic static method becomes a `FunctionRef` value.
    fn infer_class_static_access(
        &mut self,
        class_name: String,
        class_mangled: crate::MangledName,
        member: Ident,
        span: Span,
    ) -> (TypedExprKind, Type) {
        use super::classes::StaticResolution;
        match self.class_static_in_chain(&class_mangled, &member.name) {
            Some((StaticResolution::Method(sig, vis), owner)) => {
                self.check_class_callable_types(&owner, span);
                self.check_static_privacy(vis, &owner, &class_name, &member);
                if !sig.generics.is_empty() {
                    self.error(
                        span,
                        format!(
                            "cannot bind generic function `{class_name}.{}` to a value; \
                             call it directly instead",
                            member.name,
                        ),
                    );
                    return (TypedExprKind::Null, Type::Error);
                }
                let mangled = crate::mangle::static_member(&owner, &member.name);
                let ty = Type::Function {
                    params: sig.params.iter().map(callable_parameter_type).collect(),
                    ret: Box::new(sig.ret.clone()),
                    predicate: None,
                    has_rest: sig.params.last().is_some_and(|p| p.rest),
                    optional: crate::package_declaration::optional_parameter_count(&sig.params),
                };
                (
                    TypedExprKind::FunctionRef {
                        mangled,
                        name: member,
                    },
                    ty,
                )
            }
            Some((StaticResolution::Field(field), owner)) => {
                self.check_class_callable_types(&owner, span);
                self.check_static_privacy(field.visibility, &owner, &class_name, &member);
                let mangled = crate::mangle::static_member(&owner, &member.name);
                self.note_rebindable_static(&field, &owner, &member.name);
                (
                    TypedExprKind::GlobalRef {
                        mangled,
                        name: member,
                    },
                    field.ty,
                )
            }
            None => {
                self.report_missing_static(&class_name, &class_mangled, &member);
                (TypedExprKind::Null, Type::Error)
            }
        }
    }

    /// A `private` constructor is callable, and its class extendable, only in the
    /// module that declares the class (spec §2.2's module-scoped privacy). Reports
    /// a use from another module, and says whether it did.
    pub(super) fn reject_private_constructor(
        &mut self,
        class: &crate::MangledName,
        usage: ConstructorUse,
        span: Span,
    ) -> bool {
        let Some(sym) = self.types.lookup_by_mangled(class) else {
            return false;
        };
        let crate::TypeKind::Class {
            constructor_visibility: crate::Visibility::Private,
            ..
        } = sym.kind
        else {
            return false;
        };
        if self.local_class_mangles.contains(class) {
            return false;
        }
        // The declared name: the symbol table keys a class by its local names,
        // import aliases included.
        let name = class
            .as_str()
            .rsplit_once(crate::mangle::SEP)
            .map_or(class.as_str(), |(_, name)| name)
            .to_string();
        let help = match usage {
            ConstructorUse::New => format!(
                "only `{name}`'s own module can call it; use what that module exports to \
                 create one, such as a static method"
            ),
            ConstructorUse::Extend => {
                format!("only a class in `{name}`'s own module can extend it")
            }
        };
        self.error_with_help(
            span,
            format!("the constructor of class `{name}` is private"),
            vec![help],
        );
        true
    }

    pub(super) fn check_static_privacy(
        &mut self,
        vis: crate::Visibility,
        owner: &crate::MangledName,
        class_name: &str,
        member: &Ident,
    ) {
        if vis == crate::Visibility::Private && !self.local_class_mangles.contains(owner) {
            self.error_with_help(
                member.span,
                format!(
                    "static member `{}` of class `{class_name}` is private",
                    member.name,
                ),
                vec![
                    "private statics are visible only in the module that declares the class"
                        .to_string(),
                ],
            );
        }
    }

    /// An imported class's static fields are declared in another package, so
    /// an access is where this package learns which of them can be rebound,
    /// named by the class that declares the field. Its own keep the name
    /// their declaration records.
    pub(super) fn note_rebindable_static(
        &mut self,
        field: &crate::FieldSig,
        owner: &crate::MangledName,
        member: &str,
    ) {
        if field.readonly {
            return;
        }
        let shown = self.class_by_mangled(owner).map_or_else(
            || member.to_string(),
            |class| format!("{}.{member}", class.name),
        );
        self.typed_ast
            .rebindable_globals
            .entry(crate::mangle::static_member(owner, member))
            .or_insert(shown);
    }

    pub(super) fn report_missing_static(
        &mut self,
        class_name: &str,
        class_mangled: &crate::MangledName,
        member: &Ident,
    ) {
        // An unresolvable parent could have declared this static.
        if self.inherits_unresolved_parent(class_mangled) {
            return;
        }
        if self.class_instance_member_in_chain(class_mangled, &member.name) {
            self.error_with_help(
                member.span,
                format!(
                    "`{}` is an instance member of `{class_name}`, not a static",
                    member.name,
                ),
                vec![format!(
                    "access it through an instance: `new {class_name}(…).{}` — or declare \
                     it `static`",
                    member.name,
                )],
            );
            return;
        }
        let statics = self.class_static_names(class_mangled);
        let mut help: Vec<String> =
            did_you_mean::closest_match(&member.name, statics.iter().map(String::as_str))
                .map(|s| vec![format!("did you mean `{class_name}.{s}`?")])
                .unwrap_or_default();
        let package = self.type_package(class_name);
        help.push(self.format_definition(&Type::class_ref(
            package,
            class_name.to_string(),
            class_mangled.clone(),
            Vec::new(),
        )));
        self.error_with_help(
            member.span,
            format!(
                "class `{class_name}` has no static member `{}`",
                member.name
            ),
            help,
        );
    }

    /// Bind call arguments to a resolved (non-generic) parameter list —
    /// the one place argument binding happens for every non-generic
    /// callee shape. Emits an arity diagnostic with a signature lift on
    /// mismatch, infers each arg against its parameter type (which is
    /// what type-checks it; the rest tail is hinted by the element
    /// type), synthesizes defaults for omitted optional/defaulted
    /// trailing params, and packs the rest tail into a single array so
    /// the returned `Vec<ExprId>` lines up 1:1 with the resolved
    /// signature.
    pub(super) fn bind_param_call_args(
        &mut self,
        params: &[crate::Param],
        ret: &Type,
        lift: CallLift<'_>,
        args: &[ExprId],
        span: Span,
    ) -> Result<Vec<ExprId>, CompilerFailure> {
        self.check_call_signature_types(params, ret, lift, span);
        let has_rest = params.last().is_some_and(|p| p.rest);
        let fixed_count = params.iter().take_while(|p| !p.rest).count();
        let max_args = if has_rest { usize::MAX } else { params.len() };
        let min_args = required_parameter_count(params);
        let arity_ok = args.len() >= min_args && args.len() <= max_args;
        if !arity_ok {
            let help = match lift {
                CallLift::Constructor { class_ty } => {
                    self.format_signature(SignatureKind::Constructor {
                        name: &class_ty.to_string(),
                        params,
                    })
                }
                CallLift::Function { name } => self.format_signature(SignatureKind::Function {
                    name,
                    predicate: None,
                    generics: &[],
                    params,
                    ret,
                    doc: None,
                }),
                CallLift::Anon { .. } => {
                    let tys: Vec<Type> = params.iter().map(|p| p.ty.clone()).collect();
                    self.format_signature(SignatureKind::Anon {
                        params: &tys,
                        ret,
                        has_rest: params.last().is_some_and(|p| p.rest),
                        optional: crate::package_declaration::optional_parameter_count(params),
                    })
                }
                CallLift::Method {
                    receiver_ty,
                    name,
                    sig,
                } => self.format_signature(SignatureKind::Method {
                    receiver_ty,
                    name,
                    sig,
                }),
            };
            let subject = match lift {
                CallLift::Constructor { class_ty } => {
                    format!("constructor of `{class_ty}` expects")
                }
                CallLift::Function { .. } | CallLift::Anon { .. } => "expected".to_string(),
                CallLift::Method { name, .. } => format!("method `{name}` expects"),
            };
            let msg = if has_rest {
                format!("{subject} {}+ argument(s), got {}", min_args, args.len())
            } else if min_args == max_args {
                format!("{subject} {} argument(s), got {}", max_args, args.len())
            } else {
                format!(
                    "{subject} {}-{} argument(s), got {}",
                    min_args,
                    max_args,
                    args.len(),
                )
            };
            let mut hints = vec![help];
            if let CallLift::Anon { ty } = lift {
                hints.extend(self.render_optional_help(super::type_diff::guard_loss_note(ty)));
            }
            self.error_with_help(span, msg, hints);
        }

        let rest_elem_ty: Option<Type> = if has_rest {
            params
                .get(fixed_count)
                .and_then(|p| p.ty.rest_element())
                .cloned()
        } else {
            None
        };

        let mut typed_args: Vec<ExprId> = Vec::with_capacity(args.len().max(params.len()));
        for (i, &arg_id) in args.iter().enumerate() {
            let hint = if i < fixed_count {
                params.get(i).map(callable_parameter_type)
            } else {
                rest_elem_ty.clone()
            };
            let (typed_id, _) = self.infer_expr(arg_id, hint.as_ref())?;
            typed_args.push(typed_id);
        }

        if has_rest || typed_args.len() < params.len() {
            self.typed_ast
                .record_authored_arguments(span, typed_args.clone());
        }
        if arity_ok {
            self.fill_omitted_defaults(params, args.len(), span, &mut typed_args)?;
        }
        if arity_ok && let Some(elem_ty) = rest_elem_ty {
            self.pack_rest_tail(fixed_count, elem_ty, span, &mut typed_args)?;
        }
        Ok(typed_args)
    }

    /// [`Self::bind_param_call_args`] for a callee known only by its
    /// structural [`Type::Function`]. That form carries no parameter names
    /// and no default expressions. Its optional count and rest flag determine
    /// which positional arguments may be omitted.
    fn bind_fn_type_call_args(
        &mut self,
        param_types: &[Type],
        ret: &Type,
        has_rest: bool,
        lift: CallLift<'_>,
        args: &[ExprId],
        span: Span,
    ) -> Result<Vec<ExprId>, CompilerFailure> {
        self.report_closure_arity(param_types.len(), span, None);
        let mut params: Vec<crate::Param> = param_types
            .iter()
            .enumerate()
            .map(|(i, ty)| crate::Param::new(format!("arg{i}"), ty.clone()))
            .collect();
        let optional = match lift {
            CallLift::Anon { ty } => match ty.peel() {
                Type::Function { optional, .. } => *optional,
                _ => 0,
            },
            _ => 0,
        };
        let fixed = params.len().saturating_sub(usize::from(has_rest));
        for param in params
            .iter_mut()
            .take(fixed)
            .skip(fixed.saturating_sub(optional))
        {
            param.optional = true;
        }
        if has_rest && let Some(last) = params.last_mut() {
            last.rest = true;
        }
        self.bind_param_call_args(&params, ret, lift, args, span)
    }

    /// `BigInt.<member>(args)` resolution. Today only
    /// `fromString` is supported; everything else surfaces a focused
    /// "supported forms" help block.
    fn infer_bigint_namespace_call(
        &mut self,
        name: &crate::Ident,
        args: Vec<ExprId>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        Ok(match name.name.as_str() {
            "fromString" => {
                if args.len() != 1 {
                    self.error(
                        span,
                        format!(
                            "`BigInt.fromString(s)` takes 1 argument, got {}",
                            args.len(),
                        ),
                    );
                }
                let typed_args: Vec<ExprId> = args
                    .iter()
                    .map(|&id| {
                        Ok::<_, CompilerFailure>(self.infer_expr(id, Some(&Type::String))?.0)
                    })
                    .collect::<Result<_, _>>()?;
                let arg_ty = typed_args
                    .first()
                    .map(|&id| {
                        Ok::<_, crate::compiler_error::CompilerFailure>(
                            self.typed_ast
                                .try_expr(id)
                                .map_err(crate::typechecker::arena_failure)?
                                .ty
                                .clone(),
                        )
                    })
                    .transpose()?
                    .unwrap_or(Type::Error);
                if !matches!(
                    arg_ty.peel(),
                    Type::String | Type::StringLiteral(_) | Type::Error
                ) {
                    self.error(
                        span,
                        format!("`BigInt.fromString(s)`: expected `string`, got `{arg_ty}`",),
                    );
                }
                (
                    TypedExprKind::IntrinsicCall {
                        kind: Intrinsic::BigIntFromString,
                        args: typed_args,
                    },
                    Type::BigInt,
                )
            }
            other => {
                self.error_with_help(
                    name.span,
                    format!("`BigInt` has no method `{other}`"),
                    vec![
                        "the supported forms are `BigInt(n)` (number → bigint) \
                         and `BigInt.fromString(s)` (decimal string → bigint)"
                            .to_string(),
                    ],
                );
                for &arg in &args {
                    let _ = self.infer_expr(arg, None)?;
                }
                (
                    TypedExprKind::IntrinsicCall {
                        kind: Intrinsic::BigIntFromString,
                        args: Vec::new(),
                    },
                    Type::Error,
                )
            }
        })
    }

    /// `JSON.<member>(args)` resolution. Today: `stringify`
    /// and `parse` Any other member errors out. Receives
    /// both the call's `type_args` (used only by `parse` — Form 3 /
    /// the Form-2 `as T` shortcut both surface as a
    /// single-element type argument list) and the `expected` hint
    /// (Form 1 / annotation-driven).
    fn infer_json_namespace_call(
        &mut self,
        name: &crate::Ident,
        args: Vec<ExprId>,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        Ok(match name.name.as_str() {
            "stringify" => self.infer_json_stringify_call(args, type_args, span)?,
            "parse" => self.infer_json_parse_call(args, type_args, expected, span)?,
            _ => {
                self.error_with_help(
                    name.span,
                    format!("`JSON` has no method `{}`", name.name),
                    vec![
                        "the supported forms are `JSON.stringify(x)` and \
                         `JSON.parse(s)`"
                            .to_string(),
                    ],
                );
                // Best-effort recovery: still typecheck args so
                // unrelated errors in them surface.
                for &arg in &args {
                    let _ = self.infer_expr(arg, None)?;
                }
                (
                    TypedExprKind::IntrinsicCall {
                        kind: Intrinsic::JsonStringify,
                        args: Vec::new(),
                    },
                    Type::Error,
                )
            }
        })
    }

    /// `JSON.stringify(x, null?, space?)`. Arguments may have any value type;
    /// type arguments are rejected (stringify is non-generic at the
    /// source level — the value's static type already drives codegen
    /// dispatch).
    fn infer_json_stringify_call(
        &mut self,
        args: Vec<ExprId>,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if let Some(targs) = &type_args {
            // Span over the whole call — we don't keep the `<...>`
            // span separately on `Call`, but anchoring on the call
            // span surfaces the diagnostic at the right line.
            let _ = targs;
            self.error_with_help(
                span,
                "`JSON.stringify` does not take type arguments".to_string(),
                vec![
                    "remove the `<...>` — the value's static type \
                     already drives dispatch"
                        .to_string(),
                ],
            );
            // Continue typechecking as if the type args weren't
            // there so unrelated errors still surface.
        }
        if args.is_empty() || args.len() > 3 {
            let help = self.format_signature(SignatureKind::Intrinsic {
                kind: Intrinsic::JsonStringify,
            });
            self.error_with_help(
                span,
                format!(
                    "`JSON.stringify(...)` takes 1 to 3 arguments, got {}",
                    args.len()
                ),
                vec![help],
            );
            for &arg in &args {
                let _ = self.infer_expr(arg, None)?;
            }
            return Ok((
                TypedExprKind::IntrinsicCall {
                    kind: Intrinsic::JsonStringify,
                    args: Vec::new(),
                },
                Type::String,
            ));
        }
        let (typed_arg, arg_ty) = self.infer_expr(args[0], None)?;
        let mut typed_args = vec![typed_arg];

        if let Some(&replacer) = args.get(1) {
            let (typed_replacer, replacer_ty) = self.infer_expr(
                replacer,
                Some(&Type::union(vec![Type::Null, Type::Undefined])),
            )?;
            if !matches!(
                replacer_ty.peel(),
                Type::Null | Type::Undefined | Type::Error
            ) {
                self.error_with_help(
                    self.ast.try_expr(replacer).map_err(super::arena_failure)?.span,
                    "`JSON.stringify` only accepts `null` or `undefined` as its replacer argument".to_string(),
                    vec![
                        "use `JSON.stringify(value, null, space)`; replacer functions are not supported"
                            .to_string(),
                    ],
                );
            }
            typed_args.push(typed_replacer);
        }

        if let Some(&space) = args.get(2) {
            let (typed_space, space_ty) = self.infer_expr(space, None)?;
            if !matches!(
                space_ty.peel(),
                Type::Number
                    | Type::NumberLiteral(_)
                    | Type::String
                    | Type::StringLiteral(_)
                    | Type::Null
                    | Type::Undefined
                    | Type::Error
            ) {
                self.error_with_help(
                    self.ast.try_expr(space).map_err(super::arena_failure)?.span,
                    "`JSON.stringify` space argument must be `number`, `string`, `null`, or `undefined`"
                        .to_string(),
                    vec![
                        "use a number of spaces or an indent string, for example `JSON.stringify(value, null, 2)`"
                            .to_string(),
                    ],
                );
            }
            typed_args.push(typed_space);
        }

        let result_ty = if json_stringify_may_return_undefined(&arg_ty, self.resolver()) {
            Type::union(vec![Type::String, Type::Undefined])
        } else {
            Type::String
        };
        Ok((
            TypedExprKind::IntrinsicCall {
                kind: Intrinsic::JsonStringify,
                args: typed_args,
            },
            result_ty,
        ))
    }

    /// `JSON.parse(s)` parses JSON into `unknown`. Use `JSON.parse(s) as T`
    /// for runtime validation against a concrete target type.
    fn infer_json_parse_call(
        &mut self,
        args: Vec<ExprId>,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        _expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // Arity first — we want the same arity diagnostic regardless of
        // whether the target resolves.
        if args.len() != 1 {
            let help = self.format_signature(SignatureKind::Intrinsic {
                kind: Intrinsic::JsonParse,
            });
            self.error_with_help(
                span,
                format!("`JSON.parse(...)` takes 1 argument, got {}", args.len()),
                vec![help],
            );
            for &arg in &args {
                let _ = self.infer_expr(arg, None)?;
            }
            return Ok((
                TypedExprKind::IntrinsicCall {
                    kind: Intrinsic::JsonParse,
                    args: Vec::new(),
                },
                Type::Error,
            ));
        }

        // Arg must be a `string`. Pass `Some(&Type::String)` as the
        // hint so string-literal arguments widen correctly, then
        // verify the resolved type is actually a string.
        let (typed_arg, arg_ty) = self.infer_expr(args[0], Some(&Type::String))?;
        if !matches!(
            arg_ty.peel(),
            Type::String | Type::StringLiteral(_) | Type::Error
        ) {
            self.error_with_help(
                self.ast
                    .try_expr(args[0])
                    .map_err(super::arena_failure)?
                    .span,
                format!("`JSON.parse(s)` expects a `string` argument, got `{arg_ty}`",),
                vec![
                    "wrap the value with `String(x)` if you have a non-\
                     string source"
                        .to_string(),
                ],
            );
        }

        if let Some(targs) = &type_args {
            self.error_with_help(
                span,
                format!(
                    "`JSON.parse` does not take type arguments, got {}",
                    targs.len()
                ),
                vec!["parse first, then validate with `as`: `JSON.parse(s) as User`".to_string()],
            );
        }

        Ok((
            TypedExprKind::IntrinsicCall {
                kind: Intrinsic::JsonParse,
                args: vec![typed_arg],
            },
            Type::Unknown,
        ))
    }

    fn infer_response_json_call(
        &mut self,
        typed_receiver: ExprId,
        recv_ty: &Type,
        type_args: Option<Vec<crate::TypeAnnotation>>,
        args: Vec<ExprId>,
        _expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // `r.json()` takes no value arguments — the body is the implicit source.
        if !args.is_empty() {
            self.error_with_help(
                span,
                format!("`r.json()` takes no value arguments, got {}", args.len()),
                vec![
                    "the response body is parsed automatically; validate the \
                     result with `as`, for example `r.json() as User`"
                        .to_string(),
                ],
            );
            for &arg in &args {
                let _ = self.infer_expr(arg, None)?;
            }
        }
        if let Some(targs) = &type_args {
            self.error_with_help(
                span,
                format!("`r.json` does not take type arguments, got {}", targs.len()),
                vec!["parse first, then validate with `as`: `r.json() as User`".to_string()],
            );
        }

        // Synthesize the `r.body` argument — a `string` property on `Response`.
        let Some((body_prop, _bindings, iface_mangled, _dispatch)) =
            self.find_property(recv_ty, "body")
        else {
            // `Response` always declares `body`; unreachable in practice.
            return Ok((
                TypedExprKind::IntrinsicCall {
                    kind: Intrinsic::JsonParse,
                    args: Vec::new(),
                },
                Type::Error,
            ));
        };
        let body = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind: TypedExprKind::InterfacePropertyAccess {
                    receiver: typed_receiver,
                    iface: iface_mangled,
                    name: Ident {
                        name: "body".to_string(),
                        span,
                    },
                },
                span,
                ty: body_prop.ty,
            })
            .map_err(crate::typechecker::arena_failure)?;

        Ok((
            TypedExprKind::IntrinsicCall {
                kind: Intrinsic::JsonParse,
                args: vec![body],
            },
            Type::Unknown,
        ))
    }

    /// Walk a `JSON.parse` target type and reject forbidden shapes.
    /// Infer an intrinsic call. The intrinsic's signature is fixed
    /// (see [`Intrinsic::params`] / [`Intrinsic::ret`]); we typecheck
    /// args against that signature with the same hint plumbing as a
    /// regular call.
    fn infer_intrinsic_call(
        &mut self,
        intrinsic: Intrinsic,
        args: Vec<ExprId>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let params = intrinsic.params();
        let omitted_have_defaults =
            args.len() < params.len() && params[args.len()..].iter().all(|p| p.default.is_some());
        if args.len() != params.len() && !omitted_have_defaults {
            let help = self.format_signature(SignatureKind::Intrinsic { kind: intrinsic });
            self.error_with_help(
                span,
                format!("expected {} argument(s), got {}", params.len(), args.len()),
                vec![help],
            );
        }
        let mut typed_args = Vec::with_capacity(params.len());
        for (i, &arg_id) in args.iter().enumerate() {
            let hint = params.get(i).map(|p| &p.ty);
            let (typed_id, _) = self.infer_expr(arg_id, hint)?;
            typed_args.push(typed_id);
        }
        if omitted_have_defaults {
            self.fill_omitted_defaults(&params, args.len(), span, &mut typed_args)?;
        }
        Ok((
            TypedExprKind::IntrinsicCall {
                kind: intrinsic,
                args: typed_args,
            },
            intrinsic.ret(),
        ))
    }

    /// lower a `` `parts[0]${exprs[0]}parts[1]${exprs[1]}…parts[N]` ``
    /// template literal to a `+`-concatenated chain of string literals
    /// and `<expr>.toString()` method calls. Mirrors the precedent set
    /// by the `String(x)` coercion call — interpolation
    /// slots already typed `string` pass through unchanged, others are
    /// wrapped in a synthesised `MethodCall { name: "toString" }` whose
    /// `iface` is resolved via [`Self::find_method`].
    ///
    /// Empty string parts are elided so `` `${x}` `` lowers to plain
    /// `x.toString()` rather than `"" + x.toString() + ""`. The result
    /// always has type `string` (or `Type::Error` if any interpolation
    /// failed to lower).
    fn lower_template_literal(
        &mut self,
        parts: Vec<String>,
        exprs: Vec<ExprId>,
        substitution_spans: Vec<Span>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if parts.len().checked_sub(1) != Some(exprs.len())
            || substitution_spans.len() != exprs.len()
        {
            return Err(
                super::inference_failure("template part/interpolation count mismatch")
                    .with_span(span),
            );
        }

        // Type each interpolation and (when needed) wrap in toString.
        // We track any propagated `Type::Error` separately so the
        // whole template's type degrades cleanly without poisoning the
        // surrounding inference.
        let mut had_error = false;
        // The text of each substitution TypeScript can evaluate, in order. The
        // template is the string literal they spell when every one has one.
        let mut constant_texts: Vec<Option<String>> = Vec::with_capacity(exprs.len());
        let typed_interps: Vec<ExprId> = exprs
            .into_iter()
            .zip(substitution_spans)
            .map(|(expr_id, substitution_span)| {
                let (typed_id, ty) = self.infer_expr_keeping_literals(expr_id, None, true)?;
                if matches!(ty, Type::Error) {
                    had_error = true;
                }
                constant_texts.push(self.substitution_constant_text(expr_id, typed_id, &ty)?);
                let interp_span = self
                    .typed_ast
                    .try_expr(typed_id)
                    .map_err(crate::typechecker::arena_failure)?
                    .span;
                self.wrap_interpolation_in_to_string(typed_id, &ty, interp_span, substitution_span)
            })
            .collect::<Result<_, _>>()?;

        // Assemble the operand list: alternating non-empty string
        // parts and the typed interpolations. Empty parts are elided.
        let mut operands: Vec<ExprId> = Vec::with_capacity(parts.len() + typed_interps.len());
        for (i, part) in parts.iter().enumerate() {
            if !part.is_empty() {
                let lit_id = self
                    .typed_ast
                    .try_push_expr(TypedExpr {
                        kind: TypedExprKind::String(part.clone()),
                        span,
                        ty: Type::String,
                    })
                    .map_err(crate::typechecker::arena_failure)?;
                operands.push(lit_id);
            }
            if i < typed_interps.len() {
                operands.push(typed_interps[i]);
            }
        }

        let result_ty = if had_error {
            Type::Error
        } else {
            spelled_template(&parts, constant_texts).map_or(Type::String, Type::StringLiteral)
        };

        // A constant template stays a concatenation even of one operand, so its
        // literal type reads as fresh, as a written literal's does.
        if operands.len() == 1 && matches!(result_ty, Type::StringLiteral(_)) {
            let empty = self
                .typed_ast
                .try_push_expr(TypedExpr {
                    kind: TypedExprKind::String(String::new()),
                    span,
                    ty: Type::String,
                })
                .map_err(crate::typechecker::arena_failure)?;
            operands.insert(0, empty);
        }

        // Single-operand case (e.g. `` `${x}` ``): the lone
        // interpolation *is* the result. Return its kind so the outer
        // `infer_expr` push re-uses the existing node rather than
        // synthesising an extra wrapper.
        if operands.len() == 1 {
            let single = self
                .typed_ast
                .try_expr(operands[0])
                .map_err(crate::typechecker::arena_failure)?
                .clone();
            // A template is a `string` whatever it interpolates, as in
            // TypeScript: `` `${h}` `` with `h: "hello"` is not `"hello"`,
            // unless a string literal type is expected of it.
            let keeps_literal = matches!(single.ty, Type::StringLiteral(_))
                && expects_literal(expected, |ty| matches!(ty, Type::StringLiteral(_)));
            let ty = if keeps_literal && !matches!(result_ty, Type::StringLiteral(_)) {
                single.ty
            } else {
                result_ty
            };
            return Ok((single.kind, ty));
        }

        // Defensive: the parser guarantees `exprs.len() >= 1` (the
        // no-substitution case lowers to a plain string in the
        // parser), so the only path here with `operands.is_empty()`
        // is `` `${x}` `` with `x: Error` and head/tail both empty —
        // even then the toString wrap pushes a placeholder. Treat as
        // an empty string just in case.
        if operands.is_empty() {
            return Ok((TypedExprKind::String(String::new()), Type::String));
        }

        // Left-fold the operands into a Binary(Add) chain. Push every
        // intermediate node into the typed arena except the final
        // outermost Binary — return its kind so the caller's push
        // wraps it once at the top.
        let mut acc = operands[0];
        let last_idx = operands.len() - 1;
        for &next in &operands[1..last_idx] {
            acc = self
                .typed_ast
                .try_push_expr(TypedExpr {
                    kind: TypedExprKind::Binary {
                        op: BinOp::Add,
                        lhs: acc,
                        rhs: next,
                    },
                    span,
                    ty: result_ty.clone(),
                })
                .map_err(crate::typechecker::arena_failure)?;
        }
        Ok((
            TypedExprKind::Binary {
                op: BinOp::Add,
                lhs: acc,
                rhs: operands[last_idx],
            },
            result_ty,
        ))
    }

    /// The text TypeScript evaluates a template substitution to, when it does:
    /// a string or number literal, an arithmetic of them, an enum member, or a
    /// `const` bound to a literal. `None` for anything else, a boolean included.
    fn substitution_constant_text(
        &self,
        source: ExprId,
        typed: ExprId,
        ty: &Type,
    ) -> Result<Option<String>, CompilerFailure> {
        if let Some(text) = super::comparison_operand::constant_substitution(self.ast, source)? {
            return Ok(Some(text));
        }
        let kind = &self
            .typed_ast
            .try_expr(typed)
            .map_err(crate::typechecker::arena_failure)?
            .kind;
        match kind {
            TypedExprKind::NumberEnumMember { value, .. } => {
                return Ok(Some(crate::runtime::number::format_number_js(*value)));
            }
            TypedExprKind::StringEnumMember { value, .. } => return Ok(Some(value.clone())),
            _ => {}
        }
        let text = match ty {
            Type::StringLiteral(text) => text.clone(),
            Type::NumberLiteral(value) => crate::runtime::number::format_number_js(value.0),
            _ => return Ok(None),
        };
        Ok(self.is_known_fresh_literal(typed, ty)?.then_some(text))
    }

    /// Wrap an already-typed interpolation expression in a
    /// `MethodCall { name: "toString" }` unless its type is already
    /// `Type::String`; a `never` value converts as `"" + value`, `undefined` as
    /// the text `"undefined"`, and a value that may be nullish or whose type is
    /// known only at run time through [`Intrinsic::ToString`], as `String(x)`
    /// converts it. Uses the exact valid-types allowlist / diagnostic shape as
    /// the `String(x)` coercion call, so `String(x)` and `${x}` route through
    /// the same dispatch path at codegen time.
    ///
    /// Diagnostics point at the interpolated expression. The conversion node
    /// spans the whole `${…}`: it is not the source expression, and sharing that
    /// expression's span would make the conversion's `string` read as its type.
    fn wrap_interpolation_in_to_string(
        &mut self,
        expr_id: ExprId,
        ty: &Type,
        expr_span: Span,
        substitution_span: Span,
    ) -> Result<ExprId, crate::compiler_error::CompilerFailure> {
        let peeled = ty.primitive_behavior();
        if matches!(peeled, Type::String | Type::StringLiteral(_)) {
            return Ok(expr_id);
        }
        // A `never` value has no `toString` to call, yet a read of a `never[]`
        // an alias filled holds a value.
        if matches!(peeled, Type::Never) {
            return self.concatenated_onto_empty_string(expr_id, substitution_span);
        }
        if matches!(peeled, Type::Undefined) {
            let result = self.push_synthetic_expr(
                TypedExprKind::String("undefined".into()),
                Type::String,
                substitution_span,
            )?;
            return self.push_synthetic_expr(
                TypedExprKind::EffectThen {
                    effect: expr_id,
                    result,
                },
                Type::String,
                substitution_span,
            );
        }
        if interpolates_at_run_time(peeled) {
            return self.push_synthetic_expr(
                TypedExprKind::IntrinsicCall {
                    kind: Intrinsic::ToString,
                    args: vec![expr_id],
                },
                Type::String,
                substitution_span,
            );
        }
        let method_name = crate::Ident {
            name: "toString".to_string(),
            span: expr_span,
        };
        if !has_to_string(peeled) {
            self.error(
                expr_span,
                format!(
                    "template-literal interpolation: `.toString()` \
                     not supported on `{ty}`"
                ),
            );
            return self
                .typed_ast
                .try_push_expr(TypedExpr {
                    kind: TypedExprKind::MethodCall {
                        receiver: expr_id,
                        iface: crate::mangle::prelude("Null"),
                        name: method_name,
                        args: Vec::new(),
                        type_predicate: None,
                    },
                    span: substitution_span,
                    ty: Type::Error,
                })
                .map_err(crate::typechecker::arena_failure);
        }
        let resolved = self.find_method(ty, "toString");
        let iface_mangled = resolved.as_ref().map_or_else(
            || crate::mangle::prelude("Object"),
            |(_, _, iface, _)| iface.clone(),
        );
        // Fill defaulted params (Number/BigInt `toString(radix = 10)`) the
        // same way a spelled-out call site would — the import is arity-N.
        let args = resolved
            .map(|(sig, _, _, _)| {
                sig.params
                    .iter()
                    .filter_map(|p| p.default.as_ref().map(|d| (d.clone(), p.ty.clone())))
                    .collect::<Vec<_>>()
                    .into_iter()
                    .map(|(default, param_ty)| {
                        self.synthesize_default_arg(&default, &param_ty, expr_span)
                    })
                    .collect::<Result<Vec<_>, CompilerFailure>>()
            })
            .transpose()?
            .unwrap_or_default();
        self.typed_ast
            .try_push_expr(TypedExpr {
                kind: TypedExprKind::MethodCall {
                    receiver: expr_id,
                    iface: iface_mangled,
                    name: method_name,
                    args,
                    type_predicate: None,
                },
                span: substitution_span,
                ty: if matches!(ty, Type::Error) {
                    Type::Error
                } else {
                    Type::String
                },
            })
            .map_err(crate::typechecker::arena_failure)
    }

    /// `"" + value`, the string `value` converts to.
    fn concatenated_onto_empty_string(
        &mut self,
        value: ExprId,
        span: Span,
    ) -> Result<ExprId, crate::compiler_error::CompilerFailure> {
        let empty =
            self.push_synthetic_expr(TypedExprKind::String(String::new()), Type::String, span)?;
        let kind = TypedExprKind::Binary {
            op: BinOp::Add,
            lhs: empty,
            rhs: value,
        };
        self.push_synthetic_expr(kind, Type::String, span)
    }

    /// The value of an object literal's field when it is spelled as a literal.
    /// tsc uses such values to pick the union members a literal could be
    /// constructing.
    fn literal_tag_value(
        &self,
        value: crate::ExprId,
    ) -> Result<Option<narrowing::LiteralValue>, CompilerFailure> {
        let expr = self.ast.try_expr(value).map_err(super::arena_failure)?;
        Ok(match &expr.kind {
            crate::ExprKind::Null => Some(narrowing::LiteralValue::Null),
            crate::ExprKind::Identifier(ident) if self.names_global_undefined(&ident.name) => {
                Some(narrowing::LiteralValue::Undefined)
            }
            crate::ExprKind::String(s) => Some(narrowing::LiteralValue::String(s.clone())),
            crate::ExprKind::Boolean(b) => Some(narrowing::LiteralValue::Boolean(*b)),
            crate::ExprKind::Number(n) => {
                // Mirror the number-literal inference's -0.0 → 0.0.
                let canonical = if *n == 0.0 { 0.0 } else { *n };
                Some(narrowing::LiteralValue::Number(crate::types::LiteralF64(
                    canonical,
                )))
            }
            _ => None,
        })
    }

    /// Report an object literal's fields that no member of its target union
    /// declares, when no single member was picked as the literal's hint (see
    /// [`Self::select_union_variant`]).
    ///
    /// As in tsc, fields spelled as literals first narrow the union to the
    /// members they fit (see [`Self::rule_out_by_tags`]): `{ a: null, b: "f",
    /// c: 4 }` against `{ a: null; b: string } | { a: string; c: number }`
    /// keeps only the first member, so `c` is unknown. With a spread nothing is
    /// ruled out, since the spread may overwrite a tag.
    ///
    /// Returns the unknown fields the literal's type leaves out: those of a
    /// target with a member whose fields are all optional, which would
    /// otherwise fail its weak-type check too and report twice.
    fn report_unknown_union_fields(
        &mut self,
        union_members: &[Type],
        literal: &[crate::ObjectLiteralMember],
    ) -> Result<BTreeSet<String>, CompilerFailure> {
        let mut unknown = BTreeSet::new();
        let Some(shapes) = self.union_object_shapes(union_members) else {
            return Ok(unknown);
        };
        let has_spread = literal
            .iter()
            .any(|m| matches!(m, crate::ObjectLiteralMember::Spread { .. }));
        let literal_fields: Vec<&crate::ObjectLiteralField> = literal
            .iter()
            .filter_map(|m| match m {
                crate::ObjectLiteralMember::Field(f) => Some(f),
                crate::ObjectLiteralMember::Spread { .. }
                | crate::ObjectLiteralMember::Computed { .. } => None,
            })
            .collect();
        let candidates = if has_spread {
            shapes.iter().collect()
        } else {
            let Some(candidates) = self.rule_out_by_tags(&shapes, &literal_fields)? else {
                return Ok(unknown);
            };
            candidates
        };

        // As for a single target, a field is left out of the literal's type
        // only when a member it may be has only optional fields, whose
        // weak-type check would report it again.
        let has_weak_candidate = candidates
            .iter()
            .any(|shape| shape.values().all(|field| field.optional));
        let mut known = std::collections::BTreeMap::new();
        for shape in candidates {
            for (name, field) in shape {
                known.entry(name.clone()).or_insert_with(|| field.clone());
            }
        }
        for field in literal_fields {
            if !known.contains_key(&field.name.name) {
                self.report_unknown_field(field, &known);
                if has_weak_candidate {
                    unknown.insert(field.name.name.clone());
                }
            }
        }
        Ok(unknown)
    }

    /// Rejects a literal that tsc's unknown-field check skips but its weak-type
    /// check doesn't (TS2559): one whose fields, spreads included, are all
    /// absent from a target member whose fields are all optional, when no other
    /// member of the target accepts it. Returns whether it reported one. The
    /// literal may take the target's type as a hint, which `assignable`'s own
    /// weak-type rule would then never see.
    fn report_no_field_in_common(
        &mut self,
        expected: Option<&Type>,
        literal_fields: &std::collections::BTreeMap<
            String,
            (crate::ObjectField, crate::TypedObjectFieldSource),
        >,
        span: Span,
    ) -> bool {
        let Some(expected) = expected else {
            return false;
        };
        if literal_fields.is_empty() {
            return false;
        }
        let literal_ty = Type::Object {
            index: None,
            fields: literal_fields
                .iter()
                .map(|(name, (field, _))| (name.clone(), field.clone()))
                .collect(),
        };
        let targets = match expected.peel() {
            Type::Union(members) => members.as_slice(),
            _ => std::slice::from_ref(expected),
        };
        let mut disjoint_weak = None;
        for target in targets {
            let is_disjoint_weak = self
                .weak_type_fields(target)
                .is_some_and(|weak| literal_fields.keys().all(|name| !weak.contains_key(name)));
            if is_disjoint_weak {
                disjoint_weak.get_or_insert(target);
            } else if assignable(&literal_ty, target, self.resolver()) {
                return false;
            }
        }
        let Some(weak) = disjoint_weak else {
            return false;
        };
        self.error(
            span,
            format!("object literal has no fields in common with `{weak}`, whose fields are all optional"),
        );
        true
    }

    /// The fields of an object type whose fields are all optional, if `ty` is one.
    fn weak_type_fields(&self, ty: &Type) -> Option<ObjectFields> {
        let fields = match ty.peel() {
            Type::Object {
                fields,
                index: None,
            } => fields.clone(),
            Type::InterfaceRef {
                mangled,
                name,
                args,
                ..
            } if self.resolver().index_signature(ty).is_none() => {
                self.structural_form(mangled, name, args)?
            }
            _ => return None,
        };
        (!fields.is_empty() && fields.values().all(|field| field.optional)).then_some(fields)
    }

    /// The field maps of a union's object members, skipping its primitives.
    /// `None`, so nothing is checked, when there are none or a member could
    /// take any field: one with an index signature, an empty shape, or a type
    /// whose fields aren't known here (a class, an array, a type parameter).
    fn union_object_shapes(&self, union_members: &[Type]) -> Option<Vec<ObjectFields>> {
        let mut shapes = Vec::new();
        for member in union_members {
            if is_primitive(member) {
                continue;
            }
            let fields = match member.peel() {
                Type::Object {
                    fields,
                    index: None,
                } => fields.clone(),
                Type::InterfaceRef {
                    mangled,
                    name,
                    args,
                    ..
                } if self.resolver().index_signature(member).is_none() => {
                    self.structural_form(mangled, name, args)?
                }
                // An index signature, or a type whose fields aren't known here.
                _ => return None,
            };
            if fields.is_empty() {
                return None;
            }
            shapes.push(fields);
        }
        (!shapes.is_empty()).then_some(shapes)
    }

    /// The union members an object literal could be constructing, judged by
    /// its fields spelled as literals, following tsc. A field narrows when a
    /// member declaring it types it as a tag ([`is_tag_type`]): the members
    /// left are those whose field can hold the value, and those without the
    /// field, which would accept the literal structurally. `None` when no
    /// member is left: the literal can't be any member, which assignability
    /// reports, and tsc reports no unknown field.
    fn rule_out_by_tags<'s>(
        &self,
        shapes: &'s [ObjectFields],
        literal_fields: &[&crate::ObjectLiteralField],
    ) -> Result<Option<Vec<&'s ObjectFields>>, CompilerFailure> {
        let mut candidates: Vec<_> = shapes.iter().collect();
        for field in literal_fields {
            let name = &field.name.name;
            let is_tag = shapes
                .iter()
                .any(|shape| shape.get(name).is_some_and(|f| is_tag_type(&f.ty)));
            if !is_tag {
                continue;
            }
            let Some(value) = self.literal_tag_value(field.value)? else {
                continue;
            };
            candidates.retain(|shape| {
                shape
                    .get(name)
                    .is_none_or(|f| tag_fits(&f.read_ty(), &value))
            });
            if candidates.is_empty() {
                return Ok(None);
            }
        }
        Ok(Some(candidates))
    }

    fn report_unknown_field(&mut self, field: &crate::ObjectLiteralField, known: &ObjectFields) {
        self.error_with_help(
            field.name.span,
            format!(
                "object literal has unknown field `{}` for the target type",
                field.name.name,
            ),
            vec![
                valid_fields_help(known),
                excess_field_fix_help(&field.name.name, known),
            ],
        );
    }

    /// Pick the union variant an object literal is constructing, so its
    /// fields get per-variant hints instead of being inferred hint-free —
    /// which widens literal-typed fields (`kind: "circle"` → `string`) so the
    /// literal matches no variant.
    ///
    /// Field values aren't inferred yet, so the discriminant tag is read
    /// straight from the AST and matched against the union's discriminant
    /// table; failing that, the unique variant whose fields the literal
    /// exactly satisfies wins. A spread's fields aren't known here, so with a
    /// spread only the tag selects. A later spread that overwrites the tag is
    /// still checked against the selected variant's field, so it is rejected
    /// rather than mistyped. `None` (defer to the caller's single-shape scan)
    /// for ambiguity or no match.
    fn select_union_variant<'a>(
        &self,
        members: &'a [Type],
        literal: &[crate::ObjectLiteralMember],
    ) -> Result<Option<&'a Type>, CompilerFailure> {
        let has_spread = literal
            .iter()
            .any(|m| matches!(m, crate::ObjectLiteralMember::Spread { .. }));

        // A `null` or `undefined` member has no tag, so the tag is looked for
        // among the others: `{ k: "a", … }` picks `A` from `A | B | null`.
        let tagged: Vec<&Type> = members
            .iter()
            .filter(|member| !matches!(member.peel(), Type::Null | Type::Undefined))
            .collect();
        let tagged_types: Vec<Type> = tagged.iter().map(|member| (*member).clone()).collect();
        if let Some((key, table)) = self.union_discriminant_with_nominals(&tagged_types) {
            let tag_value = literal
                .iter()
                .rev()
                .map(|m| {
                    Ok::<_, CompilerFailure>(match m {
                        crate::ObjectLiteralMember::Field(f) if f.name.name == key => {
                            self.literal_tag_value(f.value)?
                        }
                        _ => None,
                    })
                })
                .find_map(Result::transpose)
                .transpose()?;
            if let Some(value) = tag_value
                && let Some(idx) = table.get(&value)
            {
                return Ok(tagged.get(idx.0 as usize).copied());
            }
        }
        // A member with an index signature takes any names, so the names alone
        // can't choose between it and another member: `{ a: "on" }` may suit
        // `{ [k: string]: string }` though `{ a: number }` names `a`.
        if has_spread || self.has_index_signature_member(members) {
            return Ok(None);
        }

        let lit_names: std::collections::BTreeSet<&str> = literal
            .iter()
            .filter_map(|m| match m {
                crate::ObjectLiteralMember::Field(f) => Some(f.name.name.as_str()),
                crate::ObjectLiteralMember::Spread { .. }
                | crate::ObjectLiteralMember::Computed { .. } => None,
            })
            .collect();

        let mut selected: Option<&Type> = None;
        for member in members {
            let matched = match member.peel() {
                Type::Object { fields, .. } => variant_matches(fields, &lit_names),
                Type::InterfaceRef {
                    mangled,
                    name,
                    args,
                    ..
                } => self
                    .structural_form(mangled, name, args)
                    .is_some_and(|fields| variant_matches(&fields, &lit_names)),
                _ => false,
            };
            if matched {
                if selected.is_some() {
                    return Ok(None);
                }
                selected = Some(member);
            }
        }
        Ok(selected)
    }

    /// An object literal, with a lone spread of a union retyped to `expected`
    /// when each of its alternatives fits (see `spread_as_its_alternatives`).
    fn infer_object_literal_expr(
        &mut self,
        literal: ExprId,
        members: Vec<crate::ObjectLiteralMember>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let lone_spread = matches!(
            members.as_slice(),
            [crate::ObjectLiteralMember::Spread { .. }]
        );
        let errors_before = self.error_count();
        let (kind, ty) = self.infer_object_literal(literal, members, expected, span)?;
        match expected {
            Some(expected) if lone_spread && self.error_count() == errors_before => {
                self.spread_as_its_alternatives(kind, ty, expected, span)
            }
            _ => Ok((kind, ty)),
        }
    }

    fn infer_object_literal(
        &mut self,
        literal: ExprId,
        members: Vec<crate::ObjectLiteralMember>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if members
            .iter()
            .any(|member| matches!(member, crate::ObjectLiteralMember::Computed { .. }))
        {
            return self.infer_computed_object(members, expected, span);
        }
        let errors_before = self.error_count();
        // Pull `expected` apart at the *Object* shape if it has one,
        // so each field gets a hint matching its declared type.
        // peel the hint so a `type Point = { x: number }`
        // expected propagates field hints just like the inline form.
        //
        // when `expected` peels to an `InterfaceRef`, lower
        // the interface declaration into a structural Object shape
        // (methods as function-typed fields + properties as their
        // declared type, with interface-level generics substituted
        // from the receiver args) and use that as the hint source.
        // The literal then returns the `InterfaceRef` type, so the
        // outer assignability check passes trivially. The per-field
        // type check we'd lose by skipping the outer Object→Object
        // arm is re-emitted explicitly here.
        let peeled = expected.map(crate::types::Type::peel);
        // when the expected type is `T | null` (or some
        // wider union with exactly one non-null variant that's an
        // Object or InterfaceRef), peel the union too. This lets an
        // object literal flow into a nullable-options-bag param
        // (`http.download(url, path, { overwrite: true })` against
        // `options: DownloadOptions | null`) the same way it flows
        // into a non-nullable interface param.
        let dictionary_hint = match peeled {
            Some(Type::Union(union_members)) => self.dictionary_union_hint(union_members, &members),
            _ => None,
        };
        let peeled = match peeled {
            Some(Type::Union(union_members)) => {
                if let Some(variant) = self.select_union_variant(union_members, &members)? {
                    Some(variant.peel())
                } else if let Some(hint) = &dictionary_hint {
                    Some(hint)
                } else {
                    let mut shape_match: Option<&Type> = None;
                    for m in union_members {
                        let mp = m.peel();
                        if matches!(mp, Type::Null) {
                            continue;
                        }
                        if matches!(mp, Type::InterfaceRef { .. } | Type::Object { .. }) {
                            if shape_match.is_some() {
                                // More than one shape-bearing variant —
                                // ambiguous, fall back to the no-hint path.
                                shape_match = None;
                                break;
                            }
                            shape_match = Some(mp);
                        }
                    }
                    shape_match.or(peeled)
                }
            }
            other => other,
        };
        let checks_unknown_fields = !self.is_inference_source(literal);
        // Fields reported as unknown that the literal's type leaves out, so
        // the slot it fills doesn't report them again.
        let mut unknown_fields = BTreeSet::new();
        // Still the union only when no member was picked above, so this check
        // and the single-shape one below never both run.
        if checks_unknown_fields && let Some(Type::Union(union_members)) = peeled {
            unknown_fields = self.report_unknown_union_fields(union_members, &members)?;
        }
        let interface_target: Option<(crate::Package, String, crate::MangledName, Vec<Type>)> =
            match peeled {
                Some(Type::InterfaceRef {
                    mangled,
                    package,
                    name,
                    args,
                }) => Some((package.clone(), name.clone(), mangled.clone(), args.clone())),
                _ => None,
            };
        let expected_fields: Option<std::collections::BTreeMap<String, crate::ObjectField>> =
            match (peeled, &interface_target) {
                (Some(Type::Object { fields, .. }), _) => Some(fields.clone()),
                (_, Some((_iface_package, iface_name, iface_mangled, iface_args))) => {
                    self.structural_form(iface_mangled, iface_name, iface_args)
                }
                _ => None,
            };
        let expected_index = expected.and_then(|ty| self.resolver().index_signature(ty));
        if let Some(want) = expected_fields.as_ref()
            && expected_index.is_none()
            && !want.is_empty()
            && checks_unknown_fields
        {
            // Against a type whose fields are all optional, an unknown field
            // would also fail the weak-type check; elsewhere the mismatch
            // names it as an extra field.
            let is_weak_target = want.values().all(|field| field.optional);
            for member in &members {
                if let crate::ObjectLiteralMember::Field(field) = member
                    && !want.contains_key(&field.name.name)
                {
                    self.report_unknown_field(field, want);
                    if is_weak_target {
                        unknown_fields.insert(field.name.name.clone());
                    }
                }
            }
        }

        let (receiver_hint, mut inferred_fields) =
            self.infer_object_receiver(&members, expected_fields.as_ref())?;
        let inferred_ahead = self.infer_fields_ahead_of_callbacks(
            literal,
            &members,
            expected_fields.as_ref(),
            expected_index.as_ref(),
            &mut inferred_fields,
        )?;

        // walk members in source order, applying last-writer-wins
        // for both literal-position fields and spread sources. `merged`
        // tracks the resolved field shape + origin per output field.
        // `object_members` records every member's expression in that same order,
        // including values a later member overwrites, which still run.
        let has_spread = members
            .iter()
            .any(|member| matches!(member, crate::ObjectLiteralMember::Spread { .. }));
        let mut object_members: Vec<crate::TypedObjectMember> = Vec::new();
        let mut spread_count = 0;
        let mut spread_index_values = Vec::new();
        let mut merged: std::collections::BTreeMap<
            String,
            (crate::ObjectField, crate::TypedObjectFieldSource),
        > = std::collections::BTreeMap::new();

        for member in members {
            match member {
                crate::ObjectLiteralMember::Computed { .. } => {
                    self.error(
                        span,
                        "internal compiler error: computed literal was not lowered".into(),
                    );
                }
                crate::ObjectLiteralMember::Field(field) => {
                    if is_reserved_object_field(&field.name.name) {
                        self.error(field.name.span, reserved_field_message(&field.name.name));
                        // Continue inferring the value so cascading
                        // errors surface; drop the field from `merged`
                        // below to keep the typed shape consistent.
                    }
                    // a field whose name matches an
                    // override slot (`toString`) prefers its own
                    // required signature as the inference hint — so
                    // an arrow-literal value infers against
                    // `() => string`. If the surrounding hint also
                    // names the field, the override signature still
                    // wins (the override is invariant, the surrounding
                    // hint can only restate it).
                    let override_sig = override_field_signature(&field.name.name);
                    let hint = self.object_field_hint(
                        literal,
                        &field.name.name,
                        expected_fields.as_ref(),
                        expected_index.as_ref(),
                    );
                    let expected_field_ty = expected_fields
                        .as_ref()
                        .and_then(|m| m.get(&field.name.name))
                        .map(|f| f.ty.clone());
                    self.next_function_keeps_returned_literals = !inferred_ahead
                        .contains(&field.value)
                        && self.field_keeps_returned_literals(literal, expected_field_ty.as_ref());
                    let previous_hint = self.object_this_hint.take();
                    if matches!(
                        self.ast
                            .try_expr(field.value)
                            .map_err(super::arena_failure)?
                            .kind,
                        ExprKind::FunctionExpression { .. }
                    ) {
                        self.object_this_hint = Some(receiver_hint.clone());
                    }
                    let ValueOperand {
                        typed_expr: typed_value,
                        ty: value_ty,
                        already_errored,
                    } = self.infer_argument_slot_value(
                        literal,
                        &field.name.name,
                        field.value,
                        |this| {
                            this.infer_value_operand(
                                field.value,
                                hint.as_ref(),
                                inferred_fields.remove(&field.value),
                            )
                        },
                    )?;
                    self.object_this_hint = previous_hint;
                    let in_type_parameter_position = expected_field_ty
                        .as_ref()
                        .is_some_and(is_type_parameter_position);
                    let value_ty = if in_type_parameter_position {
                        self.widen_fresh_literals(typed_value, &value_ty)?
                    } else {
                        value_ty
                    };
                    if !inferred_ahead.contains(&field.value) {
                        self.infer_from_argument_slot(literal, &field.name.name, &value_ty);
                    }
                    if !has_spread {
                        object_members.push(crate::TypedObjectMember::Value(typed_value));
                    }
                    let value_span = self
                        .ast
                        .try_expr(field.value)
                        .map_err(super::arena_failure)?
                        .span;
                    // when the surrounding hint is an
                    // InterfaceRef, the outer assignability check
                    // returns the interface trivially below — do
                    // the per-field check inline.
                    if interface_target.is_some()
                        && let Some(expected_field) = expected_fields
                            .as_ref()
                            .and_then(|m| m.get(&field.name.name))
                        && !assignable(&value_ty, &expected_field.read_ty(), self.resolver())
                    {
                        self.report_contextual_mismatch(
                            value_span,
                            &expected_field.ty,
                            &value_ty,
                            format!(
                                "field `{}`: expected `{}`, got `{}`",
                                field.name.name, expected_field.ty, value_ty,
                            ),
                            already_errored,
                        );
                    }
                    // validate override-field signature.
                    // `toString` must be `() => string`; anything else
                    // is rejected with a clear "must have type" error.
                    let override_ok = if let Some(expected) = &override_sig {
                        if assignable(&value_ty, expected, self.resolver()) {
                            true
                        } else {
                            self.error(
                                field.name.span,
                                format!(
                                    "field `{}` must have type `{}` (got `{}`)",
                                    field.name.name, expected, value_ty,
                                ),
                            );
                            false
                        }
                    } else {
                        true
                    };
                    if !is_reserved_object_field(&field.name.name) && override_ok {
                        // when the value is a function /
                        // closure literal, the field's *static* type
                        // is the override signature — not whatever
                        // narrower literal-return shape the inferer
                        // produced. Keeping the override shape makes
                        // the codegen field-slot lookup deterministic.
                        // An object-literal property is mutable, so a fresh literal
                        // widens: `const a = 1; const o = { k: a };` gives `{ k: number }`
                        // and `o.k = 5` stays legal, as in TypeScript. A literal type
                        // from a declaration stays (`{ k: "x" as "x" }`), and a field
                        // the surrounding annotation pins keeps that annotation's type.
                        let pinned = expected_fields
                            .as_ref()
                            .is_some_and(|m| m.contains_key(&field.name.name));
                        let field_ty = match override_sig {
                            Some(signature) => signature,
                            None if pinned => value_ty,
                            None => self.widen_fresh_literals(typed_value, &value_ty)?,
                        };
                        if has_spread {
                            let source_ty = Type::Object {
                                index: None,
                                fields: std::collections::BTreeMap::from([(
                                    field.name.name.clone(),
                                    crate::ObjectField::required(field_ty.clone()),
                                )]),
                            };
                            let source = self
                                .typed_ast
                                .try_push_expr(TypedExpr {
                                    kind: TypedExprKind::ObjectLiteral {
                                        members: vec![crate::TypedObjectMember::Value(typed_value)],
                                        fields: vec![crate::TypedObjectFieldOrigin {
                                            name: field.name.clone(),
                                            source: crate::TypedObjectFieldSource::Literal(
                                                typed_value,
                                            ),
                                            optional: false,
                                            ty: field_ty.clone(),
                                        }],
                                    },
                                    span: value_span,
                                    ty: source_ty,
                                })
                                .map_err(crate::typechecker::arena_failure)?;
                            object_members.push(crate::TypedObjectMember::Spread {
                                source,
                                by_name: false,
                            });
                        }
                        let source = crate::TypedObjectFieldSource::Literal(typed_value);
                        merged.insert(
                            field.name.name.clone(),
                            (crate::ObjectField::required(field_ty), source),
                        );
                    }
                }
                crate::ObjectLiteralMember::Spread {
                    value,
                    span: spread_span,
                } => {
                    let (typed_source, source_ty) =
                        if let Some((id, ty, _)) = inferred_fields.remove(&value) {
                            (id, ty)
                        } else {
                            self.infer_expr(value, None)?
                        };
                    if let Some(value) = self.spread_source_index(typed_source, &source_ty)? {
                        for (field, _) in merged.values_mut() {
                            field.ty = Type::union(vec![field.ty.clone(), value.clone()]);
                        }
                        spread_index_values.push(value);
                    }
                    let Some(SpreadFields { fields, by_name }) =
                        self.spread_source_fields(typed_source, &source_ty, spread_span)?
                    else {
                        continue;
                    };
                    let source_index = spread_count;
                    spread_count += 1;
                    object_members.push(crate::TypedObjectMember::Spread {
                        source: typed_source,
                        by_name,
                    });
                    let source_ty_for_origin = Type::Object {
                        index: None,
                        fields: fields.clone(),
                    };
                    for (name, field) in fields {
                        // A spread field binds type parameters for the fields
                        // after it, as one written out does.
                        self.infer_from_argument_slot(literal, &name, &field.ty);
                        let origin = crate::TypedObjectFieldSource::Spread {
                            source_index,
                            field_name: name.clone(),
                            source_ty: source_ty_for_origin.clone(),
                            fallback: None,
                        };
                        let earlier = merged.remove(&name);
                        let merged_field = merge_spread_field(earlier, field, origin)
                            .map_err(|failure| failure.with_span(spread_span))?;
                        merged.insert(name, merged_field);
                    }
                }
            }
        }

        // A literal rejected here reads as an error, so the slot it fills
        // doesn't report it again.
        let shares_no_field = if !checks_unknown_fields && spread_index_values.is_empty() {
            self.report_no_field_in_common(expected, &merged, span)
        } else {
            false
        };

        // If we had an expected shape, surface missing required fields.
        // Fresh object literal excess fields were reported above; values that
        // flow through a binding still use ordinary structural width subtyping.
        //
        // missing optional fields are accepted; codegen fills
        // the slot with `ref.null` at construction.
        if let Some(want) = expected_fields.as_ref() {
            let missing: Vec<&String> = want
                .iter()
                .filter(|(name, field)| !field.optional && !merged.contains_key(*name))
                .map(|(name, _)| name)
                .collect();
            if !missing.is_empty() {
                let list = missing
                    .iter()
                    .map(|n| format!("`{n}`"))
                    .collect::<Vec<_>>()
                    .join(", ");
                let noun = if missing.len() == 1 {
                    "field"
                } else {
                    "fields"
                };
                match &interface_target {
                    Some((package, name, mangled, args)) => {
                        let ty = Type::interface_ref(
                            package.clone(),
                            name.clone(),
                            mangled.clone(),
                            args.clone(),
                        );
                        self.error_with_help(
                            span,
                            format!(
                                "object literal is missing required {noun} {list} of type `{name}`"
                            ),
                            vec![self.format_definition(&ty)],
                        );
                    }
                    None => self.error(
                        span,
                        format!("object literal is missing required {noun} {list}"),
                    ),
                }
            }
        }

        // Taken before the expected shape's optional fields and an interface's
        // field types are spliced into the literal's layout below.
        let own_ty = (self.error_count() == errors_before)
            .then(|| {
                self.own_object_literal_type(
                    &merged,
                    expected,
                    expected_fields.as_ref(),
                    interface_target.is_some(),
                    has_spread,
                )
            })
            .flatten();

        // when an expected shape declares optional fields,
        // splice them into the literal's resulting type. The runtime
        // arity and payload slot indices follow
        // `expr.ty`, so the type must include every declared optional
        // field that codegen will null-fill into the constructed struct.
        if let Some(want) = expected_fields.as_ref() {
            for (name, want_field) in want {
                if let Some((existing_field, existing_origin)) = merged.get_mut(name) {
                    // A literal field was checked against the target where it was
                    // written; a spread's field is checked here, before the target's
                    // optionality (and an interface's type) replaces its own.
                    let from_spread = matches!(
                        existing_origin,
                        crate::TypedObjectFieldSource::Spread { .. }
                    );
                    if from_spread && existing_field.optional && !want_field.optional {
                        self.error_with_help(
                            span,
                            format!(
                                "spread field `{name}` may be absent, but the target requires it"
                            ),
                            vec![format!("give `{name}` a value after the spread")],
                        );
                    } else if from_spread
                        && interface_target.is_some()
                        && !assignable(&existing_field.ty, &want_field.read_ty(), self.resolver())
                    {
                        let message = format!(
                            "spread field `{name}`: expected `{}`, got `{}`",
                            want_field.ty, existing_field.ty,
                        );
                        self.error(span, message);
                    }
                    existing_field.optional = want_field.optional;
                    if interface_target.is_some() {
                        // Interface writes can replace the initializer with any declared
                        // value. Vtable serialization/equality must use that same type.
                        existing_field.ty = want_field.ty.clone();
                    }
                } else if want_field.optional {
                    // An optional field the literal doesn't provide reads
                    // back as absent: its origin is a synthesized `undefined`.
                    let absent_id = self
                        .typed_ast
                        .try_push_expr(TypedExpr {
                            kind: TypedExprKind::Undefined,
                            span,
                            ty: Type::Undefined,
                        })
                        .map_err(crate::typechecker::arena_failure)?;
                    if !has_spread {
                        object_members.push(crate::TypedObjectMember::Value(absent_id));
                    }
                    merged.insert(
                        name.clone(),
                        (
                            want_field.clone(),
                            crate::TypedObjectFieldSource::Absent(absent_id),
                        ),
                    );
                }
            }
        }

        // Build the output: BTreeMap iteration order is canonical, so
        // both the result `Type::Object` and the parallel
        // `TypedObjectFieldOrigin` list end up in the same order.
        let mut field_origins: Vec<crate::TypedObjectFieldOrigin> =
            Vec::with_capacity(merged.len());
        let mut resolved: std::collections::BTreeMap<String, crate::ObjectField> =
            std::collections::BTreeMap::new();
        for (name, (field, source)) in merged {
            field_origins.push(crate::TypedObjectFieldOrigin {
                name: Ident {
                    name: name.clone(),
                    span,
                },
                source,
                optional: field.optional,
                ty: field.ty.clone(),
            });
            if !unknown_fields.contains(&name) {
                resolved.insert(name, field);
            }
        }

        if let Some(own) = own_ty {
            return Ok((
                TypedExprKind::ObjectLiteral {
                    members: object_members,
                    fields: field_origins,
                },
                own,
            ));
        }

        // when the expected type was an `InterfaceRef`, the
        // literal's inferred type is the interface — assignability at
        // the surrounding slot is trivial, and the per-field checks
        // already fired above. Codegen and the shape collector derive
        // the structural Object shape from the typed origin list.
        let kind = TypedExprKind::ObjectLiteral {
            members: object_members,
            fields: field_origins,
        };
        if shares_no_field {
            return Ok((kind, Type::Error));
        }
        if let Some((iface_package, iface_name, iface_mangled, iface_args)) = interface_target {
            return Ok((
                kind,
                Type::interface_ref(iface_package, iface_name, iface_mangled, iface_args),
            ));
        }
        Ok((
            kind,
            Type::Object {
                index: if spread_index_values.is_empty() {
                    None
                } else {
                    spread_index_values.extend(resolved.values().map(|f| f.ty.clone()));
                    Some(crate::IndexSignature {
                        value: Box::new(Type::union(spread_index_values)),
                        readonly: false,
                    })
                },
                fields: resolved,
            },
        ))
    }

    /// The type an object literal checked against `expected` keeps as its own,
    /// as in tsc: `{ value: 10 }` against `{ value: number; error?: string }` is
    /// `{ value: number }`. Codegen builds it from its field origins instead.
    /// `None` keeps the expected type: against an interface with methods, whose
    /// methods a value reaches through the interface's own dispatch; with a
    /// spread, whose fields take their optionality from the expected shape; and
    /// against an unbound type parameter, which a call site infers from the
    /// expected shape.
    fn own_object_literal_type(
        &self,
        merged: &std::collections::BTreeMap<
            String,
            (crate::ObjectField, crate::TypedObjectFieldSource),
        >,
        expected: Option<&Type>,
        expected_fields: Option<&std::collections::BTreeMap<String, crate::ObjectField>>,
        against_interface: bool,
        has_spread: bool,
    ) -> Option<Type> {
        let expected = expected?;
        let expected_fields = expected_fields?;
        let dispatches_methods = against_interface
            && expected_fields
                .values()
                .any(|field| field.method || matches!(field.ty.peel(), Type::Function { .. }));
        if dispatches_methods || has_spread || type_contains_type_var(expected) {
            return None;
        }
        let own = Type::Object {
            index: None,
            fields: merged
                .iter()
                .map(|(name, (field, _))| (name.clone(), field.clone()))
                .collect(),
        };
        assignable(&own, expected, self.resolver()).then_some(own)
    }

    /// The hint an object literal takes against a union with a member that has
    /// an index signature, which no field name can rule out: each field the
    /// literal writes is hinted with every type a member gives that name. The
    /// literal is then checked against the union itself. `None` when no member
    /// has an index signature.
    fn dictionary_union_hint(
        &self,
        members: &[Type],
        literal: &[crate::ObjectLiteralMember],
    ) -> Option<Type> {
        if !self.has_index_signature_member(members) {
            return None;
        }
        let shapes: Vec<(ObjectFields, Option<Type>)> = members
            .iter()
            .filter(|member| !matches!(member.peel(), Type::Null | Type::Undefined))
            .map(|member| {
                let index = self
                    .resolver()
                    .index_signature(member)
                    .map(|index| *index.value);
                (self.member_shape(member).unwrap_or_default(), index)
            })
            .collect();
        let fields = literal
            .iter()
            .filter_map(|member| match member {
                crate::ObjectLiteralMember::Field(field) => Some(field.name.name.as_str()),
                _ => None,
            })
            .filter_map(|name| {
                let types: Vec<Type> = shapes
                    .iter()
                    .filter_map(|(fields, index)| {
                        fields
                            .get(name)
                            .map(crate::ObjectField::read_ty)
                            .or_else(|| index.clone())
                    })
                    .collect();
                (!types.is_empty()).then(|| {
                    (
                        name.to_string(),
                        crate::ObjectField::required(Type::union(types)),
                    )
                })
            })
            .collect();
        Some(Type::Object {
            index: None,
            fields,
        })
    }

    /// `{ ...x }` checked against `expected`, where `x` is a union or a
    /// conditional. Its alternatives merge into one object type, which may not
    /// fit `expected` though each alternative does: `{ ...x }` with
    /// `x: Dict | { a: string }` is a copy of whichever `x` holds. tsc types the
    /// copy as the union of its alternatives; here the merged object is cast to
    /// `expected` when every alternative fits it.
    fn spread_as_its_alternatives(
        &mut self,
        kind: TypedExprKind,
        ty: Type,
        expected: &Type,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let TypedExprKind::ObjectLiteral { members, .. } = &kind else {
            return Ok((kind, ty));
        };
        let [crate::TypedObjectMember::Spread { source, .. }] = members.as_slice() else {
            return Ok((kind, ty));
        };
        if assignable(&ty, expected, self.resolver()) {
            return Ok((kind, ty));
        }
        let source_ty = self
            .typed_ast
            .try_expr(*source)
            .map_err(crate::typechecker::arena_failure)?
            .ty
            .clone();
        let mut alternatives = Vec::new();
        self.collect_spread_alternatives(*source, &source_ty, &mut alternatives)?;
        // A falsy alternative copies nothing, so it stands for `{}`.
        let (falsy, copying): (Vec<&Type>, Vec<&Type>) = alternatives
            .iter()
            .partition(|alternative| is_definitely_falsy(alternative));
        let empty = Type::Object {
            index: None,
            fields: ObjectFields::new(),
        };
        let every_alternative_fits = copying.len() > 1
            && copying
                .iter()
                .all(|alternative| assignable(alternative, expected, self.resolver()))
            && (falsy.is_empty() || assignable(&empty, expected, self.resolver()));
        if !every_alternative_fits {
            return Ok((kind, ty));
        }
        let copy = self.push_synthetic_expr(kind, ty, span)?;
        Ok((
            TypedExprKind::Cast {
                value: copy,
                target_ty: expected.clone(),
                check: None,
            },
            expected.clone(),
        ))
    }

    /// Whether a member of a union has an index signature, which backs any
    /// field name.
    fn has_index_signature_member(&self, members: &[Type]) -> bool {
        members
            .iter()
            .any(|member| self.resolver().index_signature(member).is_some())
    }

    /// The fields a spread copies, and whether they must be found by name at
    /// run time (`by_name`). A conditional contributes each branch rather than
    /// their join — `c ? a : {}` joins to `{}`, which would copy nothing when `a`
    /// is chosen — and a union contributes each member. Over more than one alternative, a
    /// field some lack is optional and its type is the union of theirs, as in
    /// TypeScript. Only structural object types and interfaces with an index
    /// signature spread; anything else is reported. A `by_name` spread's fields
    /// are recorded in `TypedAst::spread_mask_fields`, which codegen reads.
    pub(super) fn spread_source_fields(
        &mut self,
        typed_source: ExprId,
        source_ty: &Type,
        span: Span,
    ) -> Result<Option<SpreadFields>, crate::compiler_error::CompilerFailure> {
        let mut alternatives = Vec::new();
        self.collect_spread_alternatives(typed_source, source_ty, &mut alternatives)?;
        if alternatives.iter().all(is_definitely_falsy)
            && let Some(first) = alternatives.first()
        {
            self.error(
                span,
                format!("cannot spread `{first}` into an object literal"),
            );
            return Ok(None);
        }
        let mut objects: Vec<SpreadAlternative> = Vec::new();
        for alternative in alternatives {
            let index_value = self
                .resolver()
                .index_signature(&alternative)
                .map(|index| *index.value);
            let fields = match alternative {
                Type::Object { fields, .. } => fields,
                // A spread copies nothing from a value that is always falsy, as
                // `c && { a: 1 }` is when `c` is false, or from `null` or
                // `undefined`, when
                // another alternative is an object (as in tsc).
                ref falsy if is_definitely_falsy(falsy) => ObjectFields::new(),
                Type::InterfaceRef {
                    ref mangled,
                    ref name,
                    ref args,
                    ..
                } if index_value.is_some() => {
                    let Some(fields) = self.resolver().interface_full_form(mangled, name, args)
                    else {
                        return Ok(None);
                    };
                    fields
                }
                Type::InterfaceRef { name, .. } => {
                    self.error(
                        span,
                        format!(
                            "cannot spread interface `{name}` into an object literal — only structural object types are accepted",
                        ),
                    );
                    return Ok(None);
                }
                // Inner inference already reported it.
                Type::Error => return Ok(None),
                other => {
                    self.error(
                        span,
                        format!("cannot spread `{other}` into an object literal"),
                    );
                    return Ok(None);
                }
            };
            let object = SpreadAlternative {
                fields,
                index_value,
            };
            if !objects.contains(&object) {
                objects.push(object);
            }
        }
        if let [only] = objects.as_slice() {
            return Ok(Some(SpreadFields {
                fields: only.fields.clone(),
                by_name: false,
            }));
        }
        let fields = merge_spread_alternatives(&objects);
        self.typed_ast.spread_mask_fields.insert(
            typed_source,
            fields
                .iter()
                .map(|(name, field)| (name.clone(), field.ty.clone()))
                .collect(),
        );
        Ok(Some(SpreadFields {
            fields,
            by_name: true,
        }))
    }

    /// The object `const { a, ...rest } = source` binds to `rest`: a copy of
    /// `source` without the names `exclude` lists, built as the spread
    /// `{ ...source }` that leaves them out. `None` when `source` can't be
    /// spread: a source that isn't an object, a union of objects, or a
    /// dictionary.
    pub(super) fn object_rest(
        &mut self,
        typed_source: ExprId,
        source_ty: &Type,
        exclude: &[Ident],
        span: Span,
    ) -> Result<Option<(ExprId, Type)>, CompilerFailure> {
        if !self.spreads_as_rest_source(typed_source, source_ty)? {
            return Ok(None);
        }
        let index_value = self.spread_source_index(typed_source, source_ty)?;
        let Some(SpreadFields { mut fields, .. }) =
            self.spread_source_fields(typed_source, source_ty, span)?
        else {
            return Ok(None);
        };
        let omitted: std::collections::BTreeSet<String> =
            exclude.iter().map(|name| name.name.clone()).collect();
        fields.retain(|name, _| !omitted.contains(name));
        // Every rest is read by name, so its mask can leave the excluded names
        // out; a lone object's fields need no value check.
        let checked = self
            .typed_ast
            .spread_mask_fields
            .entry(typed_source)
            .or_default();
        checked.retain(|name, _| !omitted.contains(name));
        self.typed_ast
            .spread_omitted_fields
            .insert(typed_source, omitted);
        let origin_ty = Type::Object {
            index: None,
            fields: fields.clone(),
        };
        let origins = fields
            .iter()
            .map(|(name, field)| crate::TypedObjectFieldOrigin {
                name: Ident {
                    name: name.clone(),
                    span,
                },
                source: crate::TypedObjectFieldSource::Spread {
                    source_index: 0,
                    field_name: name.clone(),
                    source_ty: origin_ty.clone(),
                    fallback: None,
                },
                optional: field.optional,
                ty: field.ty.clone(),
            })
            .collect();
        let index = index_value.map(|value| crate::IndexSignature {
            value: Box::new(Type::union(
                std::iter::once(value)
                    .chain(fields.values().map(|field| field.ty.clone()))
                    .collect(),
            )),
            readonly: false,
        });
        let ty = Type::Object { index, fields };
        let rest = self.push_synthetic_expr(
            TypedExprKind::ObjectLiteral {
                members: vec![crate::TypedObjectMember::Spread {
                    source: typed_source,
                    by_name: true,
                }],
                fields: origins,
            },
            ty.clone(),
            span,
        )?;
        Ok(Some((rest, ty)))
    }

    /// Whether every alternative of a rest source is an object type or a
    /// dictionary, which a spread copies; other sources keep the rest's own
    /// diagnostic rather than a spread's.
    fn spreads_as_rest_source(
        &self,
        typed_source: ExprId,
        source_ty: &Type,
    ) -> Result<bool, CompilerFailure> {
        let mut alternatives = Vec::new();
        self.collect_spread_alternatives(typed_source, source_ty, &mut alternatives)?;
        Ok(!alternatives.is_empty()
            && alternatives.iter().all(|alternative| {
                matches!(alternative.peel(), Type::Object { .. })
                    || self.resolver().index_signature(alternative).is_some()
            }))
    }

    pub(super) fn spread_source_index(
        &self,
        source: ExprId,
        ty: &Type,
    ) -> Result<Option<Type>, crate::compiler_error::CompilerFailure> {
        let mut alternatives = Vec::new();
        self.collect_spread_alternatives(source, ty, &mut alternatives)?;
        let values: Vec<Type> = alternatives
            .iter()
            .filter_map(|ty| self.resolver().index_signature(ty).map(|i| *i.value))
            .collect();
        Ok((!values.is_empty()).then(|| Type::union(values)))
    }

    fn collect_spread_alternatives(
        &self,
        id: ExprId,
        ty: &Type,
        out: &mut Vec<Type>,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        if let TypedExprKind::Ternary { then_, else_, .. } = self
            .typed_ast
            .try_expr(id)
            .map_err(crate::typechecker::arena_failure)?
            .kind
        {
            for branch in [then_, else_] {
                let branch_ty = self
                    .typed_ast
                    .try_expr(branch)
                    .map_err(crate::typechecker::arena_failure)?
                    .ty
                    .clone();
                self.collect_spread_alternatives(branch, &branch_ty, out)?;
            }
            return Ok(());
        }
        collect_union_members(ty, out);
        Ok(())
    }

    fn infer_array_literal(
        &mut self,
        literal: ExprId,
        elements: Vec<crate::ArrayLiteralElement>,
        expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // a tuple-typed hint forks the literal into tuple-literal
        // inference. Tuple-ness is hint-driven — without an annotation the
        // literal still infers as `Type::Array`, matching pre-tuple behavior.
        //
        let has_spread = elements
            .iter()
            .any(|e| matches!(e, crate::ArrayLiteralElement::Spread { .. }));
        // Peel first: a tuple reached through an alias (`type Pair = [A, B]`,
        // including a generic one) is still a tuple hint, and dropping to the
        // array path below would infer `A[]` and fail the assignability check.
        let expected = expected.map(array_literal_hint_shape);
        if let Some(Type::Tuple(expected_elems)) = expected {
            if has_spread {
                return self.infer_spread_tuple_literal(elements, expected_elems, span);
            }
            let plain: Vec<ExprId> = elements
                .into_iter()
                .map(|e| match e {
                    crate::ArrayLiteralElement::Value(id) => Ok(id),
                    crate::ArrayLiteralElement::Spread { .. } => Err(super::inference_failure(
                        "spread reached plain tuple inference",
                    )),
                })
                .collect::<Result<_, _>>()?;
            return self.infer_tuple_literal(literal, plain, expected_elems.clone(), span);
        }

        if let Some(Type::Union(members)) = expected {
            let candidates: Vec<_> = members
                .iter()
                .map(Type::peel)
                .filter(|member| matches!(member, Type::Tuple(_) | Type::Array(_)))
                .cloned()
                .collect();
            if candidates.len() > 1 && candidates.iter().any(|ty| matches!(ty, Type::Tuple(_))) {
                return self.infer_tuple_union_literal(elements, candidates);
            }
            if candidates.len() > 1 {
                let element_types = candidates
                    .iter()
                    .filter_map(|member| match member {
                        Type::Array(element) => Some((**element).clone()),
                        _ => None,
                    })
                    .collect();
                return self.infer_array_union_literal(literal, elements, element_types, span);
            }
        }

        let expected_elem: Option<&Type> = match expected {
            Some(Type::Array(elem)) => Some(elem.as_ref()),
            _ => None,
        };

        if elements.is_empty() {
            // Without a hint, `[]` holds no element, so it is `never[]`, as in
            // tsc, and fits any array type it is later used as.
            let elem_ty = expected_elem.cloned().unwrap_or(Type::Never);
            return Ok((
                TypedExprKind::ArrayLiteral {
                    elements: Vec::new(),
                    element_ty: elem_ty.clone(),
                },
                Type::Array(Box::new(elem_ty)),
            ));
        }

        // Walk elements in source order. The first resolved element
        // (Value or Spread source) seeds the running element type unless
        // an expected concrete hint pins it. For Spread,
        // the source must peel to `Type::Array(T)` and `T`
        // participates in unification.
        //
        // The hint informs assignability, but a concrete inferred
        // type takes precedence over an unbound generic-param hint
        // (`TypeVar` / `GenericParam`) — otherwise the array would
        // report its type as `T[]` and lose the concrete-element
        // information a generic call site needs to bind `T`.
        let hint_pins_element_ty = matches!(
            expected_elem,
            Some(t) if !type_contains_type_var(t)
        );
        let errors_before = self.error_count();
        let object_literals = elements
            .iter()
            .map(|element| match element {
                crate::ArrayLiteralElement::Value(id) => {
                    object_normalization::literal_element(self.ast, *id)
                }
                crate::ArrayLiteralElement::Spread { .. } => {
                    Ok(object_normalization::LiteralElement::NONE)
                }
            })
            .collect::<Result<Vec<_>, _>>()?;
        let mut typed_elements: Vec<crate::TypedArrayElement> = Vec::with_capacity(elements.len());
        let mut element_ty: Option<Type> = if hint_pins_element_ty {
            expected_elem.cloned()
        } else {
            None
        };
        let mut saw_never = false;
        // Unless a hint pins it, the element type stays open: an element that types
        // itself takes no hint from the elements before it, as in tsc, and the
        // elements join by type afterwards.
        let open_element_type = !hint_pins_element_ty;
        let normalization = if open_element_type {
            object_normalization::array_normalization(self.ast, &elements)?
        } else {
            None
        };
        // Arrays of object literals type themselves, as their literals would:
        // `[[{ a: 1 }], [{ a: 2, b: 3 }]]` checks no literal against another's
        // fields, and the arrays then join by type.
        let arrays_of_object_literals = open_element_type
            && normalization.is_none()
            && object_normalization::every_array_of_object_literals(self.ast, &elements)?;
        // Whether the running element type is still the first element's, which
        // mismatch messages name.
        let mut running_is_first = true;
        // Under a pinning hint the literal still has a type of its own, as in tsc:
        // `["a"]` checked against `(string | number)[]` is `string[]`.
        let mut own_element_types = Vec::new();
        for el in elements {
            match el {
                crate::ArrayLiteralElement::Value(elem_id) => {
                    let elem_span = self
                        .ast
                        .try_expr(elem_id)
                        .map_err(super::arena_failure)?
                        .span;
                    let types_itself = self.types_itself(elem_id)?;
                    // A literal that will normalize takes a hint only from a running
                    // type of its own shape, which one with other fields can't match.
                    let lacks_running_shape = normalization.is_some()
                        && !object_normalization::has_running_shape(
                            self.ast,
                            elem_id,
                            element_ty.as_ref(),
                        )?;
                    // Such a literal still takes the expected element type, which only
                    // reaches here when it holds an unbound type parameter: its empty
                    // arrays and callbacks need that context, as in tsc.
                    // An empty array's `never[]` says nothing of what later elements
                    // hold, so it hints none: `[[], [1]]` holds `number[]`. Nor does
                    // a running type of only `null`/`undefined`, unless a hint pins
                    // it: the element widens the type instead (`[undefined, { a: 1 }]`).
                    let running_hint = element_ty.as_ref().filter(|t| {
                        !holds_no_element(t) && (hint_pins_element_ty || !is_nullish_only(t))
                    });
                    let hint = if open_element_type && (types_itself || arrays_of_object_literals) {
                        None
                    } else if open_element_type && lacks_running_shape {
                        expected_elem
                    } else {
                        running_hint.or(expected_elem)
                    };
                    let ValueOperand {
                        typed_expr: typed_id,
                        ty: elem_ty,
                        already_errored,
                    } = self.infer_value_operand(elem_id, hint, None)?;
                    // A `never` element holds no value (it is read in code no value
                    // reaches), so it neither seeds nor narrows the element type.
                    if matches!(elem_ty.peel(), Type::Never) {
                        saw_never = true;
                        typed_elements.push(crate::TypedArrayElement::Value(typed_id));
                        continue;
                    }
                    if hint_pins_element_ty {
                        own_element_types.push(elem_ty.clone());
                    }
                    let Some(running) = &element_ty else {
                        // First resolved value seeds the running
                        // element type. Hint did not pin it (None
                        // or unbound generic param).
                        //
                        // The seed widens: array elements are mutable, so
                        // `const a = 1; const xs = [a, 2];` is `number[]`, not
                        // `1[]`. An annotation that pins the element type takes
                        // the `hint_pins_element_ty` path above instead.
                        element_ty = Some(elem_ty.widen_literal());
                        typed_elements.push(crate::TypedArrayElement::Value(typed_id));
                        continue;
                    };
                    let join = ElementJoin {
                        widens: open_element_type && !already_errored,
                        joins_as_union: normalization.is_some() || arrays_of_object_literals,
                    };
                    match self.joined_element_type(running, &elem_ty, join) {
                        Some(joined) => {
                            running_is_first &= joined == *running;
                            element_ty = Some(joined);
                        }
                        None => self.report_array_element_mismatch(
                            elem_span,
                            running,
                            &elem_ty,
                            ElementMismatch {
                                hint_pins_element_ty,
                                running_is_first,
                                already_errored,
                            },
                        ),
                    }
                    typed_elements.push(crate::TypedArrayElement::Value(typed_id));
                }
                crate::ArrayLiteralElement::Spread {
                    value,
                    span: spread_span,
                } => {
                    // A spread only reads its source, so a readonly one qualifies.
                    // Only `null`/`undefined` so far is no context for a source
                    // that types itself: the spread widens the element type
                    // instead (`[undefined, ...xs]`). An annotation, or a source
                    // like `[]` that needs one, still takes it.
                    let source_needs_context = cannot_be_typed_alone(self.ast, value)?;
                    let source_hint = element_ty
                        .as_ref()
                        .filter(|running| {
                            hint_pins_element_ty
                                || source_needs_context
                                || !is_nullish_only(running)
                        })
                        .map(|t| Type::Readonly(Box::new(Type::Array(Box::new(t.clone())))));
                    let errors_before = self.error_count();
                    let (typed_source, source_ty) = self.infer_expr(value, source_hint.as_ref())?;
                    let already_errored = self.error_count() > errors_before;
                    if let Some(hint) = &source_hint {
                        self.drop_readonly_from_hint_mismatch(value, hint, &source_ty)?;
                    }
                    // The spread source must be an array, or a tuple or a union of
                    // arrays and tuples, which are arrays at runtime. Reject other
                    // shapes (primitive, object, unknown, other unions, function)
                    // with a typed diagnostic. Aliases peel first.
                    let peeled_source = source_ty.peel().clone();
                    if hint_pins_element_ty {
                        own_element_types.extend(spread_element_type(&peeled_source));
                    }
                    match spread_element_type(&peeled_source) {
                        // A `Type::Error` source was already reported by inner inference.
                        None if matches!(peeled_source, Type::Error) => {}
                        // An empty source adds no element, as a `never` value doesn't.
                        Some(Type::Never) => saw_never = true,
                        None => self.error(
                            spread_span,
                            format!("expected an array to spread, got `{peeled_source}`"),
                        ),
                        Some(elem_t) => match &element_ty {
                            // Widens for the same reason as the value seed above.
                            None => element_ty = Some(elem_t.widen_literal()),
                            Some(running)
                                if !hint_pins_element_ty
                                    && let Some(widened) =
                                        Self::widen_nullish_seed(running, &elem_t) =>
                            {
                                element_ty = Some(widened);
                            }
                            Some(running) if !assignable(&elem_t, running, self.resolver()) => {
                                if !hint_pins_element_ty {
                                    self.report_contextual_mismatch(
                                        self.ast
                                            .try_expr(value)
                                            .map_err(super::arena_failure)?
                                            .span,
                                        &Type::Array(Box::new(running.clone())),
                                        &source_ty,
                                        format!(
                                            "expected `{running}` ({}), got `{elem_t}`",
                                            matched_elements(running_is_first),
                                        ),
                                        already_errored,
                                    );
                                } else if !already_errored {
                                    self.error(
                                        spread_span,
                                        super::diagnostics::mismatch_message(&running, &elem_t),
                                    );
                                }
                            }
                            Some(_) => {}
                        },
                    }
                    // Push the source even when it was rejected, so the typed AST stays
                    // well-formed for downstream passes.
                    typed_elements.push(crate::TypedArrayElement::Spread(typed_source));
                }
            }
        }

        // Reached only without a pinning hint, which seeds `element_ty`
        // above. When no element fixed an element type, take `never` if the
        // elements were all `never` (`[x]` is `never[]`, as in TypeScript, and
        // a generic hint then infers from it); else the hint, or `Type::Error`
        // (every spread had an invalid source) rather than panicking.
        let element_ty = element_ty.unwrap_or_else(|| {
            if saw_never {
                Type::Never
            } else {
                expected_elem.cloned().unwrap_or(Type::Error)
            }
        });
        // The seed widened every literal type to check the elements against;
        // the regular ones stay, as in TypeScript: `[h]` with `h: "hello"` is
        // `"hello"[]`.
        let element_ty = if let Some(normalizing) = &normalization {
            // tsc reduces the literals' types to those no other is a subtype
            // of before normalizing them against one another. An element that
            // reported an error still normalizes, so reads of its siblings'
            // fields don't report again.
            let element_types = self.array_literal_element_types(&typed_elements)?;
            let reduced = self.without_fresh_subtypes(element_types);
            object_normalization::normalized(&reduced, normalizing)
        } else if hint_pins_element_ty {
            if self.error_count() == errors_before && !own_element_types.is_empty() {
                Type::union(own_element_types)
            } else {
                element_ty
            }
        } else if self.error_count() > errors_before {
            self.kept_element_type(element_ty, &typed_elements)?
        } else {
            let element_ty =
                self.best_common_element_type(element_ty, &typed_elements, &object_literals)?;
            self.kept_element_type(element_ty, &typed_elements)?
        };

        Ok((
            TypedExprKind::ArrayLiteral {
                elements: typed_elements,
                element_ty: element_ty.clone(),
            },
            Type::Array(Box::new(element_ty)),
        ))
    }

    /// An array literal expected as a union of array types, as tsc types it: each
    /// element takes any member's element type as its context, and the literal
    /// is the first member whose element type every element fits. `[]` is the
    /// first member, as its `never[]` in tsc fits them all. When no member fits
    /// every element, the literal keeps the union of the elements' context, which
    /// the caller then reports against the union.
    fn infer_array_union_literal(
        &mut self,
        literal: ExprId,
        elements: Vec<crate::ArrayLiteralElement>,
        member_elements: Vec<Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let context = if elements.is_empty() {
            member_elements.first().cloned().unwrap_or(Type::Error)
        } else {
            Type::union(member_elements.clone())
        };
        let errors_before = self.error_count();
        let (kind, ty) = self.infer_array_literal(
            literal,
            elements,
            Some(&Type::Array(Box::new(context))),
            span,
        )?;
        let TypedExprKind::ArrayLiteral { elements, .. } = kind else {
            return Ok((kind, ty));
        };
        let element_types = self.array_literal_element_types(&elements)?;
        let fitting = member_elements.into_iter().find(|member| {
            element_types
                .iter()
                .all(|element| assignable(element, member, self.resolver()))
        });
        // An element that failed its context was reported already, and the
        // literal as a whole needn't be again.
        let element_ty = match (fitting, ty) {
            (Some(member), _) => member,
            _ if self.error_count() > errors_before => Type::Error,
            (None, Type::Array(element)) => *element,
            (None, _) => Type::Error,
        };
        Ok((
            TypedExprKind::ArrayLiteral {
                elements,
                element_ty: element_ty.clone(),
            },
            Type::Array(Box::new(element_ty)),
        ))
    }

    /// The type each element of a typed array literal holds: a value's own type,
    /// and the element type of a spread's source.
    fn array_literal_element_types(
        &self,
        elements: &[crate::TypedArrayElement],
    ) -> Result<Vec<Type>, CompilerFailure> {
        let mut types = Vec::with_capacity(elements.len());
        for element in elements {
            let ty = &self
                .typed_ast
                .try_expr(element.expr_id())
                .map_err(crate::typechecker::arena_failure)?
                .ty;
            match element {
                crate::TypedArrayElement::Value(_) => types.push(ty.clone()),
                // A spread literal took the union's context too, so its own
                // elements say what it holds: `[...[1, 2], 3]` holds numbers.
                crate::TypedArrayElement::Spread(source) => {
                    match &self
                        .typed_ast
                        .try_expr(*source)
                        .map_err(crate::typechecker::arena_failure)?
                        .kind
                    {
                        TypedExprKind::ArrayLiteral { elements, .. } => {
                            types.extend(self.array_literal_element_types(elements)?);
                        }
                        _ => types.extend(spread_element_type(ty.peel())),
                    }
                }
            }
        }
        Ok(types)
    }

    /// The element type of an array literal that so far held only `null` or
    /// `undefined`, once a value with a type of its own arrives. A spread
    /// widens only this way: its source's elements are already one type.
    fn widen_nullish_seed(running: &Type, elem: &Type) -> Option<Type> {
        if is_nullish_only(running) && !is_nullish_only(elem) {
            let undefined_as_value = |ty: &Type| match ty.peel() {
                Type::Void => Type::Undefined,
                Type::Union(members) => Type::union(
                    members
                        .iter()
                        .map(|m| match m.peel() {
                            Type::Void => Type::Undefined,
                            _ => m.clone(),
                        })
                        .collect(),
                ),
                _ => ty.clone(),
            };
            Some(Type::union(vec![
                undefined_as_value(running),
                elem.widen_literal(),
            ]))
        } else {
            None
        }
    }

    /// The running element type widened by `null`/`undefined`: an element that
    /// is the running type plus a nullish member, or a nullish seed followed by
    /// a value. Arrays stay homogeneous otherwise.
    fn widen_by_nullish(&self, running: &Type, elem: &Type) -> Option<Type> {
        if let Some(widened) = Self::widen_nullish_seed(running, elem) {
            return Some(widened);
        }
        if assignable(elem, running, self.resolver()) {
            return None;
        }
        let present = super::narrowing::strip_nullish(elem);
        if present == *elem || !assignable(&present, running, self.resolver()) {
            return None;
        }
        let mut members = vec![running.clone()];
        if elem.spells_null() {
            members.push(Type::Null);
        }
        if elem.spells_undefined() {
            members.push(Type::Undefined);
        }
        Some(Type::union(members))
    }

    fn report_array_element_mismatch(
        &mut self,
        span: Span,
        expected: &Type,
        actual: &Type,
        mismatch: ElementMismatch,
    ) {
        if !mismatch.hint_pins_element_ty || !mismatch.already_errored {
            self.report_contextual_mismatch(
                span,
                expected,
                actual,
                format!(
                    "expected `{expected}` ({}), got `{actual}`",
                    matched_elements(mismatch.running_is_first)
                ),
                mismatch.already_errored,
            );
        }
    }

    /// The element type once `elem_ty` joins the `running` one, or `None` when
    /// they don't join.
    fn joined_element_type(
        &self,
        running: &Type,
        elem_ty: &Type,
        join: ElementJoin,
    ) -> Option<Type> {
        // `[o.x, o.y]` with an optional `y` is `(number | undefined)[]`, as in
        // TypeScript.
        if join.widens
            && let Some(widened) = self.widen_by_nullish(running, elem_ty)
        {
            return Some(widened);
        }
        if assignable(elem_ty, running, self.resolver()) {
            return Some(running.clone());
        }
        // A later element every earlier one fits becomes the element type, as
        // tsc's best common type: `[(x) => x, (x, y) => x * y]` holds
        // two-parameter functions.
        if join.widens && assignable(running, elem_ty, self.resolver()) {
            return Some(elem_ty.widen_literal());
        }
        join.joins_as_union
            .then(|| Type::union(vec![running.clone(), elem_ty.widen_literal()]))
    }

    /// Whether an expression reads a variable, a field or `this`.
    fn is_read(&self, expr: ExprId) -> Result<bool, CompilerFailure> {
        let id = peel_parens(self.ast, expr)?;
        Ok(matches!(
            self.ast.try_expr(id).map_err(super::arena_failure)?.kind,
            ExprKind::Identifier(_) | ExprKind::FieldAccess { .. } | ExprKind::This
        ))
    }

    /// Whether an array element is typed on its own rather than against the
    /// elements before it: an identifier or field read, `null`, a fully
    /// annotated function, or an object literal none of whose fields needs a
    /// hint.
    fn types_itself(&self, expr: ExprId) -> Result<bool, CompilerFailure> {
        let id = peel_parens(self.ast, expr)?;
        Ok(
            match &self.ast.try_expr(id).map_err(super::arena_failure)?.kind {
                ExprKind::Identifier(_)
                | ExprKind::FieldAccess { .. }
                | ExprKind::This
                | ExprKind::Null => true,
                ExprKind::Arrow { .. } | ExprKind::FunctionExpression { .. } => {
                    self.is_fully_annotated_function(id)?
                }
                ExprKind::ObjectLiteral { .. } => !self.needs_hint(id)?,
                ExprKind::New {
                    callee, type_args, ..
                } => type_args.is_some() || self.names_non_generic_class(*callee)?,
                _ => false,
            },
        )
    }

    /// Whether `callee` names a class without type parameters, whose `new`
    /// takes nothing from a hint.
    fn names_non_generic_class(&self, callee: ExprId) -> Result<bool, CompilerFailure> {
        let ExprKind::Identifier(ident) = &self
            .ast
            .try_expr(callee)
            .map_err(super::arena_failure)?
            .kind
        else {
            return Ok(false);
        };
        Ok(self.lookup_named_type(&ident.name).is_some_and(|symbol| {
            matches!(&symbol.kind, crate::TypeKind::Class { generics, .. } if generics.is_empty())
        }))
    }

    /// Whether an expression needs a hint to be typed. Leaves that type themselves
    /// need none, an expression built from others needs one when a part does, and
    /// any other kind, such as a call that may infer from its return type, is
    /// assumed to.
    fn needs_hint(&self, expr: ExprId) -> Result<bool, CompilerFailure> {
        let id = peel_parens(self.ast, expr)?;
        Ok(
            match &self.ast.try_expr(id).map_err(super::arena_failure)?.kind {
                ExprKind::Number(_)
                | ExprKind::BigInt(_)
                | ExprKind::String(_)
                | ExprKind::Boolean(_)
                | ExprKind::Null
                | ExprKind::Identifier(_)
                | ExprKind::FieldAccess { .. }
                | ExprKind::This
                | ExprKind::TemplateLiteral { .. }
                | ExprKind::Unary { .. }
                | ExprKind::Typeof { .. }
                | ExprKind::Void { .. }
                | ExprKind::IndexAccess { .. }
                | ExprKind::As { .. }
                | ExprKind::InstanceOf { .. } => false,
                ExprKind::Binary { lhs, rhs, .. } => {
                    self.any_needs_hint([*lhs, *rhs].into_iter())?
                }
                ExprKind::Arrow { .. } | ExprKind::FunctionExpression { .. } => {
                    !self.is_fully_annotated_function(id)?
                }
                ExprKind::ObjectLiteral { members } => {
                    self.any_needs_hint(members.iter().map(crate::ObjectLiteralMember::value))?
                }
                ExprKind::ArrayLiteral { elements } => {
                    elements.is_empty()
                        || self.any_needs_hint(
                            elements.iter().map(crate::ArrayLiteralElement::value),
                        )?
                }
                ExprKind::Ternary { then_, else_, .. } => {
                    self.needs_hint(*then_)? || self.needs_hint(*else_)?
                }
                _ => true,
            },
        )
    }

    fn any_needs_hint(
        &self,
        mut exprs: impl Iterator<Item = ExprId>,
    ) -> Result<bool, CompilerFailure> {
        exprs.try_fold(false, |found, expr| Ok(found || self.needs_hint(expr)?))
    }

    /// A spread source is hinted `readonly T[]` only so a readonly source is
    /// accepted; any mismatch left is in the elements, so the diagnostic names the
    /// `T[]` the writer thinks in rather than a `readonly` they never wrote.
    fn drop_readonly_from_hint_mismatch(
        &mut self,
        source: ExprId,
        hint: &Type,
        actual: &Type,
    ) -> Result<(), CompilerFailure> {
        let span = self
            .ast
            .try_expr(source)
            .map_err(super::arena_failure)?
            .span;
        let _: () = if let Some(diagnostic) = self.diagnostics.last_mut()
            && diagnostic.span == span
            && diagnostic.message == super::diagnostics::mismatch_message(&hint, &actual)
        {
            diagnostic.message = super::diagnostics::mismatch_message(hint.peel(), &actual);
        };
        Ok(())
    }

    fn report_contextual_mismatch(
        &mut self,
        span: Span,
        expected: &Type,
        actual: &Type,
        message: String,
        already_errored: bool,
    ) {
        if !already_errored {
            self.error(span, message);
            return;
        }
        // Keep the inner diagnostic's help and location while adding slot context.
        if let Some(diagnostic) = self.diagnostics.last_mut()
            && diagnostic.span == span
            && diagnostic.message == super::diagnostics::mismatch_message(&expected, &actual)
        {
            diagnostic.message = message;
        }
    }

    fn infer_spread_tuple_literal(
        &mut self,
        elements: Vec<crate::ArrayLiteralElement>,
        expected: &crate::types::TupleType,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let mut typed = Vec::with_capacity(elements.len());
        let mut slots = crate::types::TupleType::from(Vec::new());
        let mut diagnosed = Vec::new();
        for element in &elements {
            match element {
                crate::ArrayLiteralElement::Value(value) => {
                    let errors_before = self.error_count();
                    let first_position = slots.required_len();
                    let last_position = slots.len();
                    let hint = tuple_position_hint(expected, first_position, last_position);
                    let (id, ty) = self.infer_expr(*value, hint.as_ref())?;
                    slots = append_tuple_literal_types(slots, &vec![ty].into(), &self.type_limits)
                        .map_err(super::type_limit_at(span))?;
                    diagnosed.resize(slots.len(), false);
                    if self.error_count() > errors_before {
                        for diagnosed in diagnosed
                            .iter_mut()
                            .take(last_position.saturating_add(1))
                            .skip(first_position)
                        {
                            *diagnosed = true;
                        }
                    }
                    typed.push(crate::TypedArrayElement::Value(id));
                }
                crate::ArrayLiteralElement::Spread { value, span } => {
                    let (id, ty) = self.infer_expr(*value, None)?;
                    match ty.peel() {
                        Type::Tuple(types) => {
                            slots = append_tuple_literal_types(slots, types, &self.type_limits)
                                .map_err(super::type_limit_at(*span))?;
                            diagnosed.resize(slots.len(), false);
                        },
                        Type::Error => {},
                        _ => self.error_with_help(*span,
                            format!("tuple literal spread requires a fixed-length tuple, got `{ty}`"),
                            vec!["annotate the spread source as a tuple, or use an array result type".into()]),
                    }
                    typed.push(crate::TypedArrayElement::Spread(id));
                }
            }
        }
        if slots.required_len() < expected.required_len() || slots.len() > expected.len() {
            let actual_count = if slots.optional == 0 {
                slots.len().to_string()
            } else {
                format!("{} to {}", slots.required_len(), slots.len())
            };
            self.error(
                span,
                format!(
                    "tuple literal has {actual_count} elements, but type expects {} to {}",
                    expected.required_len(),
                    expected.len()
                ),
            );
        }
        for ((actual, want), already_errored) in
            slots.elements.iter_mut().zip(expected).zip(diagnosed)
        {
            if matches!(want, Type::TypeVar(_) | Type::GenericParam { .. }) {
                continue;
            }
            if !already_errored && !assignable(actual, want, self.resolver()) {
                self.error(span, super::diagnostics::mismatch_message(&want, &actual));
            }
            *actual = want.clone();
        }
        // Both literals use erased $Array storage. Preserve the positional type
        // on the expression while reusing spread evaluation and copying.
        Ok((
            TypedExprKind::ArrayLiteral {
                elements: typed,
                element_ty: Type::Unknown,
            },
            Type::Tuple(slots),
        ))
    }

    /// Keep the inferred slots rather than the union of contextual slots: the
    /// enclosing assignment must still validate one complete tuple variant.
    fn infer_tuple_union_literal(
        &mut self,
        elements: Vec<crate::ArrayLiteralElement>,
        mut candidates: Vec<Type>,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if !elements
            .iter()
            .any(|element| matches!(element, crate::ArrayLiteralElement::Spread { .. }))
        {
            let matching: Vec<_> = candidates
                .iter()
                .filter(|candidate| match candidate {
                    Type::Tuple(slots) => {
                        elements.len() >= slots.required_len() && elements.len() <= slots.len()
                    }
                    _ => true,
                })
                .cloned()
                .collect();
            if !matching.is_empty() {
                candidates = matching;
            }
        }
        let mut typed = Vec::with_capacity(elements.len());
        let mut slots = crate::types::TupleType::from(Vec::new());
        let allows_array = candidates.iter().any(|ty| matches!(ty, Type::Array(_)));
        let mut has_array_spread = false;
        for element in elements {
            match element {
                crate::ArrayLiteralElement::Value(value) => {
                    let hints: Vec<_> = candidates
                        .iter()
                        .filter_map(|candidate| match candidate {
                            Type::Tuple(tuple) if !has_array_spread => {
                                tuple_position_hint(tuple, slots.required_len(), slots.len())
                            }
                            Type::Array(element) => Some((**element).clone()),
                            _ => None,
                        })
                        .collect();
                    let hint = (!hints.is_empty()).then(|| Type::union(hints));
                    let (id, ty) = self.infer_expr(value, hint.as_ref())?;
                    let span = self.ast.try_expr(value).map_err(super::arena_failure)?.span;
                    slots = append_tuple_literal_types(slots, &vec![ty].into(), &self.type_limits)
                        .map_err(super::type_limit_at(span))?;
                    typed.push(crate::TypedArrayElement::Value(id));
                }
                crate::ArrayLiteralElement::Spread { value, span } => {
                    let (id, ty) = self.infer_expr(value, None)?;
                    match ty.peel() {
                        Type::Tuple(types) => {
                            slots = append_tuple_literal_types(slots, types, &self.type_limits)
                                .map_err(super::type_limit_at(span))?;
                        },
                        Type::Array(element) if allows_array => {
                            has_array_spread = true;
                            slots = append_tuple_literal_types(slots, &vec![(**element).clone()].into(), &self.type_limits)
                                .map_err(super::type_limit_at(span))?;
                        }
                        Type::Error => {},
                        _ => self.error_with_help(span,
                            format!("tuple literal spread requires a fixed-length tuple, got `{ty}`"),
                            vec!["annotate the spread source as a tuple, or use an array result type".into()]),
                    }
                    typed.push(crate::TypedArrayElement::Spread(id));
                }
            }
            let matching: Vec<_> = candidates
                .iter()
                .filter(|candidate| match candidate {
                    Type::Tuple(tuple) => {
                        !has_array_spread
                            && slots.len() <= tuple.len()
                            && slots.iter().zip(tuple).all(|(actual, expected)| {
                                assignable(actual, expected, self.resolver())
                            })
                    }
                    Type::Array(element) => slots
                        .iter()
                        .all(|actual| assignable(actual, element, self.resolver())),
                    _ => false,
                })
                .cloned()
                .collect();
            if !matching.is_empty() {
                candidates = matching;
            }
        }
        Ok((
            TypedExprKind::ArrayLiteral {
                elements: typed,
                element_ty: Type::Unknown,
            },
            if has_array_spread {
                Type::Array(Box::new(Type::union(slots.elements)))
            } else {
                Type::Tuple(slots)
            },
        ))
    }

    /// An unannotated array literal that an array pattern destructures: a tuple
    /// of its elements' widened types, as TypeScript infers from the pattern.
    fn infer_pattern_tuple_literal(
        &mut self,
        literal: ExprId,
        elements: Vec<crate::ArrayLiteralElement>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let mut typed_elements = Vec::with_capacity(elements.len());
        let mut element_types = Vec::with_capacity(elements.len());
        for element in &elements {
            let crate::ArrayLiteralElement::Value(id) = element else {
                return self.infer_array_literal(literal, elements, None, span);
            };
            let (typed_id, ty) = self.infer_expr(*id, None)?;
            element_types.push(self.widen_fresh_literals(typed_id, &ty)?);
            typed_elements.push(typed_id);
        }
        Ok((
            TypedExprKind::TupleLiteral {
                elements: typed_elements,
                element_types: element_types.clone(),
            },
            Type::Tuple(element_types.into()),
        ))
    }

    /// array-literal expression interpreted as a tuple. Caller
    /// has already established that `expected` is `Type::Tuple`. Each
    /// source element is inferred against its position's expected type;
    /// arity mismatch and element-type mismatches produce diagnostics
    /// but the returned `Type::Tuple(...)` still reflects the
    /// annotation so downstream type-checking doesn't cascade.
    fn infer_tuple_literal(
        &mut self,
        literal: ExprId,
        elements: Vec<ExprId>,
        expected_elems: crate::types::TupleType,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if elements.len() < expected_elems.required_len() || elements.len() > expected_elems.len() {
            self.error(
                span,
                format!(
                    "tuple literal has {} element{}, but type expects {}",
                    elements.len(),
                    if elements.len() == 1 { "" } else { "s" },
                    expected_elems.len(),
                ),
            );
            // Still infer each element so any nested errors get
            // reported. Pair against the available expected slots;
            // extra source elements get no hint, extra expected slots
            // are silently unfilled in the typed AST.
            let mut typed_elements: Vec<ExprId> = Vec::with_capacity(elements.len());
            for (i, elem_id) in elements.iter().enumerate() {
                let hint = expected_elems.get(i);
                let (typed_id, _ty) = self.infer_expr(*elem_id, hint)?;
                typed_elements.push(typed_id);
            }
            return Ok((
                TypedExprKind::TupleLiteral {
                    elements: typed_elements,
                    element_types: expected_elems.to_vec(),
                },
                Type::Tuple(expected_elems),
            ));
        }

        // A generic call's argument types its function literal elements with
        // an unannotated parameter last, each with what the other elements
        // bound, as tsc's intra-expression inference does. The elements still
        // run in source order.
        let mut order: Vec<usize> = (0..elements.len()).collect();
        if self.infers_one_at_a_time(literal) {
            let mut context_sensitive = Vec::new();
            for (index, elem_id) in elements.iter().enumerate() {
                if self.is_context_sensitive_function(*elem_id)? {
                    context_sensitive.push(index);
                }
            }
            order.retain(|index| !context_sensitive.contains(index));
            order.extend(context_sensitive);
        }
        let mut inferred: Vec<Option<(ExprId, Type)>> = vec![None; elements.len()];
        for index in order {
            let (Some(elem_id), Some(expected_ty)) =
                (elements.get(index), expected_elems.get(index))
            else {
                continue;
            };
            let element = self.infer_tuple_element(literal, index, *elem_id, expected_ty)?;
            if let Some(slot) = inferred.get_mut(index) {
                *slot = Some(element);
            }
        }
        let (typed_elements, slot_types): (Vec<ExprId>, Vec<Type>) =
            inferred.into_iter().flatten().unzip();

        Ok((
            TypedExprKind::TupleLiteral {
                elements: typed_elements,
                element_types: slot_types.clone(),
            },
            Type::Tuple(slot_types.into()),
        ))
    }

    /// Infer element `index` of the tuple literal `literal` against its slot
    /// `expected_ty`, returning the typed element and the slot's type.
    fn infer_tuple_element(
        &mut self,
        literal: ExprId,
        index: usize,
        elem_id: ExprId,
        expected_ty: &Type,
    ) -> Result<(ExprId, Type), CompilerFailure> {
        let elem_span = self
            .ast
            .try_expr(elem_id)
            .map_err(super::arena_failure)?
            .span;
        let errors_before = self.error_count();
        let index = index.to_string();
        let hint = self.argument_slot_hint(literal, &index);
        let (typed_id, elem_ty) =
            self.infer_argument_slot_value(literal, &index, elem_id, |this| {
                this.infer_expr(elem_id, Some(hint.as_ref().unwrap_or(expected_ty)))
            })?;
        // Unbound generic-param slots take the inferred element type —
        // `new Map([["a", 1]])` must report `[string, number]`, not
        // `[K, V]`, so the call site can bind K and V.
        let slot = if is_type_parameter_position(expected_ty) {
            self.widen_fresh_literals(typed_id, &elem_ty)?
        } else if type_contains_type_var(expected_ty) {
            // A slot naming a type parameter still being inferred takes
            // the element's own type too: `{ v: "x" }` for `{ v: T }`
            // must reach the call as `{ v: string }` to bind `T`.
            elem_ty
        } else if assignable(&elem_ty, expected_ty, self.resolver()) {
            // The literal keeps its own element type, as in tsc; the slot it
            // lands in has already accepted it.
            elem_ty
        } else {
            if self.error_count() == errors_before {
                self.error(
                    elem_span,
                    super::diagnostics::mismatch_message(&expected_ty, &elem_ty),
                );
            }
            expected_ty.clone()
        };
        self.infer_from_argument_slot(literal, &index, &slot);
        Ok((typed_id, slot))
    }

    /// Whether a user binding named `name` — local, top-level, or another `case`
    /// clause's — hides the prelude namespace of that name (`const Math = { … }`
    /// makes `Math.floor` the user's).
    /// Only for namespaces the prelude does not itself bind at top level: `BigInt` is a
    /// top-level constructor binding, so it would always read as shadowed.
    fn shadows_namespace(&self, name: &str) -> bool {
        self.scopes.get(name).is_some()
            || self.top_symbols.contains_key(name)
            || self.is_later_global(name)
            || self.declaration_in_another_case_clause(name).is_some()
    }

    fn infer_field_access(
        &mut self,
        receiver: ExprId,
        name: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // namespace-symbol member read in non-call
        // position. `Math.PI` returns a const; `Temporal.Now` (no
        // following member) errors as a namespace-not-a-value. Must
        // run before the import-namespace check; locals still take precedence.
        // The chain extractor
        // reconstructs the dotted path from `receiver` + `name`;
        // the chain root must be in `namespace_symbols` for the
        // dispatch to engage.
        if let Some((root, mut segments)) = namespace_symbol::extract_chain(self.ast, receiver)?
            && !self.shadows_namespace(&root.name)
            && self.namespace_symbols.contains_key(&root.name)
        {
            segments.push(name.clone());
            return Ok(self.infer_namespace_symbol_field_access(root, segments, span));
        }

        // namespace member in non-call position
        // (`uuid.v4` without `(…)`). Reaching here means the call
        // intercept in `infer_call` didn't fire — i.e., the
        // namespace member is being read as a value. Reject with a
        // tailored fix.
        if let ExprKind::Identifier(ref recv_ident) = self
            .ast
            .try_expr(receiver)
            .map_err(super::arena_failure)?
            .kind
            && self.scopes.get(&recv_ident.name).is_none()
            && self.namespace_bindings.contains_key(&recv_ident.name)
        {
            let recv_name = recv_ident.name.clone();
            self.error_with_help(
                span,
                format!(
                    "namespace member `{}.{}` is only valid in call position",
                    recv_name, name.name,
                ),
                vec![format!(
                    "to bind it as a value, use `import {{ {} }} from \"<pkg>\";`",
                    name.name,
                )],
            );
            return Ok((
                TypedExprKind::LocalRef {
                    ident: name,
                    boxed: false,
                },
                Type::Error,
            ));
        }

        // Syntactic enum-namespace form: `EnumName.Variant`. We
        // peek at the receiver AST *before* typing it — bare
        // enum-name identifiers are not first-class values and
        // would error in `resolve_ident`. Doing the check here
        // means `EnumName.Variant` typechecks cleanly without that
        // diagnostic firing first.
        if let ExprKind::Identifier(ref recv_ident) = self
            .ast
            .try_expr(receiver)
            .map_err(super::arena_failure)?
            .kind
        {
            let recv_name = recv_ident.name.clone();
            if self.scopes.get(&recv_name).is_none()
                && !self.top_symbols.contains_key(&recv_name)
                && let Some(sym) = self.lookup_named_type(&recv_name)
            {
                let enum_mangled = sym.mangled_name.clone();
                let enum_package = self.type_package(&recv_name);
                match &sym.kind {
                    crate::TypeKind::NumberEnum { variants, .. } => {
                        let variants = variants.clone();
                        if let Some((_, value)) = variants.iter().find(|(v, _)| v == &name.name) {
                            return Ok((
                                TypedExprKind::NumberEnumMember {
                                    enum_mangled: enum_mangled.clone(),
                                    variant: name.clone(),
                                    value: *value,
                                },
                                Type::number_enum(enum_package, recv_name, enum_mangled)
                                    .with_enum_member(
                                        &name.name,
                                        EnumValue::Number(LiteralF64(*value)),
                                        variants.len(),
                                    ),
                            ));
                        }
                        let help = enum_variant_help(&recv_name, variants.iter().map(|(v, _)| v));
                        self.error_with_help(
                            name.span,
                            format!("no variant `{}` on enum `{}`", name.name, recv_name,),
                            help,
                        );
                        return Ok((
                            TypedExprKind::NumberEnumMember {
                                enum_mangled,
                                variant: name,
                                // Placeholder: codegen never reaches
                                // this path; the diagnostic blocked
                                // compilation. 0.0 keeps the variant
                                // well-formed.
                                value: 0.0,
                            },
                            Type::Error,
                        ));
                    }
                    crate::TypeKind::StringEnum { variants, .. } => {
                        let variants = variants.clone();
                        if let Some((_, value)) = variants.iter().find(|(v, _)| v == &name.name) {
                            return Ok((
                                TypedExprKind::StringEnumMember {
                                    enum_mangled: enum_mangled.clone(),
                                    variant: name.clone(),
                                    value: value.clone(),
                                },
                                Type::string_enum(enum_package, recv_name, enum_mangled)
                                    .with_enum_member(
                                        &name.name,
                                        EnumValue::String(value.clone()),
                                        variants.len(),
                                    ),
                            ));
                        }
                        let help = enum_variant_help(&recv_name, variants.iter().map(|(v, _)| v));
                        self.error_with_help(
                            name.span,
                            format!("no variant `{}` on enum `{}`", name.name, recv_name,),
                            help,
                        );
                        return Ok((
                            TypedExprKind::StringEnumMember {
                                enum_mangled,
                                variant: name,
                                value: String::new(),
                            },
                            Type::Error,
                        ));
                    }
                    crate::TypeKind::Class { .. }
                        if self.scopes.get(&recv_name).is_none()
                            && !self.top_symbols.contains_key(&recv_name) =>
                    {
                        // `ClassName.member` read: static field → backing global,
                        // static method → function value. A value binding of the
                        // same name shadows the class (checked above).
                        return Ok(self.infer_class_static_access(
                            recv_name,
                            enum_mangled,
                            name,
                            span,
                        ));
                    }
                    _ => {
                        // Identifier resolves to a non-enum type —
                        // fall through to the normal field-access
                        // path below.
                    }
                }
            }
        }
        self.infer_property_access(receiver, name, span)
    }

    fn infer_property_access(
        &mut self,
        receiver: ExprId,
        name: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (typed_receiver, receiver_ty) = self.infer_expr(receiver, None)?;
        // Plan 75.17: in-region rewrite for field-path
        // narrowings. If the candidate path `<receiver>.<name>` has an
        // active `NarrowedView`, return a `LocalNarrowRef` to the
        // shadow instead of building a fresh `FieldAccess` — codegen
        // then reads the narrowed shadow slot once, not the field
        // every time. Mirrors the identifier-path rewrite in
        // `resolve_ident`. `expr_to_reference_path` returns `None` for
        // non-path receivers (calls, binops, …) — the rewrite then
        // skips and we fall through to the normal field-access path.
        if let Some(path) = self
            .expr_to_reference_path(
                self.typed_ast
                    .try_expr(typed_receiver)
                    .map_err(crate::typechecker::arena_failure)?,
            )?
            .map(|mut p| {
                p.chain
                    .push(super::narrowing::PathElem::Field(name.name.clone()));
                p
            })
            && let Some(read) = self.narrowed_read(path)
        {
            return Ok(read);
        }
        if name.name == "length"
            && let Some(arrays) = receiver_ty.string_or_array_union_arrays()
        {
            return self.string_or_array_length(typed_receiver, arrays, name, span);
        }
        if name.name == "length"
            && let Some(length_ty) = tuple_receiver_length_type(&receiver_ty)
        {
            return Ok((
                TypedExprKind::InterfacePropertyAccess {
                    receiver: typed_receiver,
                    iface: crate::mangle::prelude("Array"),
                    name,
                },
                length_ty,
            ));
        }
        // interface-property dispatch lands here BEFORE the
        // user-object field path. `lookup_interface_property` returns `None`
        // for `Object` so user-object reads aren't shadowed by a hypothetical
        // `Object.foo`.
        if let Some((prop_sig, bindings, iface_mangled, dispatch)) =
            self.lookup_interface_property(&receiver_ty, &name.name)
        {
            let resolved_ty = if bindings.is_empty() {
                prop_sig.ty.clone()
            } else {
                super::generic::substitute_typevars(&prop_sig.ty, &bindings, &self.type_limits)
                    .map_err(super::type_limit_at(span))?
            };
            // VTable interfaces (every user-declared interface) have no
            // getter import — read through shape-based field dispatch, the
            // same path object fields and the for-of desugar use. The getter
            // funcref returns undefined for an absent optional field, so an
            // optional read widens to `T | undefined` like the Object arm below.
            if dispatch == crate::Dispatch::VTable {
                let read_ty = if prop_sig.optional {
                    Type::union(vec![resolved_ty, Type::Undefined])
                } else {
                    resolved_ty
                };
                return Ok((
                    TypedExprKind::FieldAccess {
                        receiver: typed_receiver,
                        name,
                    },
                    read_ty,
                ));
            }
            return Ok((
                TypedExprKind::InterfacePropertyAccess {
                    receiver: typed_receiver,
                    iface: iface_mangled,
                    name,
                },
                resolved_ty,
            ));
        }
        if let Type::ClassRef { mangled, args, .. } = receiver_ty.peel() {
            let mangled = mangled.clone();
            let class_args = args.clone();
            if let Some(read_ty) = self.class_field_read_ty(&mangled, &class_args, &name) {
                return Ok((
                    TypedExprKind::FieldAccess {
                        receiver: typed_receiver,
                        name,
                    },
                    read_ty,
                ));
            }
            // Statics are checked only after instance members, matching
            // `lookup_chain_field` and what dispatch actually does: a class may
            // declare a static and an instance method of the same name, and an
            // instance receiver resolves to the instance one. Reporting the
            // static first would point `c.m` at a different member than `c.m()`
            // just called.
            //
            // A miss on an instance field is phrased the same whether the field
            // is absent or private to another module (docs/classes.md §2-3).
            if !self.try_report_method_reference(name.span, &receiver_ty, &name.name)
                && !self.report_static_on_instance(&receiver_ty, &mangled, &name)
            {
                self.report_missing_field(name.span, &receiver_ty, &name.name);
            }
            return Ok((
                TypedExprKind::FieldAccess {
                    receiver: typed_receiver,
                    name,
                },
                Type::Error,
            ));
        }
        if matches!(receiver_ty.peel(), Type::InterfaceRef { .. })
            && let Some(index) = self.resolver().index_signature(&receiver_ty)
        {
            return Ok((
                TypedExprKind::FieldAccess {
                    receiver: typed_receiver,
                    name,
                },
                index.read_ty(),
            ));
        }
        if matches!(receiver_ty.peel(), Type::InterfaceRef { .. }) {
            if !self.try_report_method_reference(name.span, &receiver_ty, &name.name) {
                self.report_missing_field(name.span, &receiver_ty, &name.name);
            }
            return Ok((
                TypedExprKind::FieldAccess {
                    receiver: typed_receiver,
                    name,
                },
                Type::Error,
            ));
        }
        // field-access dispatch is structural — peel
        // through alias wrappers to find the underlying Object /
        // Union form. Error messages still use the un-peeled
        // `receiver_ty` so the alias name surfaces in diagnostics.
        let field_ty = match receiver_ty.peel() {
            Type::Object { fields, index } => {
                if let Some(field) = fields.get(&name.name) {
                    field.read_ty()
                } else if let Some(index) = index {
                    index.read_ty()
                } else {
                    // An object literal still resolves the prelude `Object`
                    // members, so the name can be a real method here too.
                    if !self.try_report_method_reference(name.span, &receiver_ty, &name.name) {
                        self.report_missing_object_field(name.span, &receiver_ty, &name.name);
                    }
                    Type::Error
                }
            }
            Type::Union(members) if members.iter().all(Self::is_field_bearing) => {
                let path = self.expr_to_reference_path(
                    self.typed_ast
                        .try_expr(typed_receiver)
                        .map_err(crate::typechecker::arena_failure)?,
                )?;
                self.union_field_read_ty(
                    name.span,
                    path.as_ref(),
                    &receiver_ty,
                    members,
                    &name.name,
                )
            }
            Type::Error => Type::Error,
            // field access on un-narrowed `unknown` is
            // rejected. The user must narrow via `typeof` /
            // `Array.isArray` / `=== null` / a user type guard
            // before reading fields. Keeping the call path inside
            // the match (not a fall-through to the catch-all) lets
            // us tailor the help to point at the narrowing
            // primitives rather than at `format_definition`, which
            // for `unknown` is just the literal `"unknown"`.
            Type::Unknown => {
                self.error_with_help(
                    span,
                    format!("cannot read field `{}` on `unknown`", name.name,),
                    vec![
                        "narrow first with `typeof x === \"…\"`, \
                         `Array.isArray(x)`, `x === null`, or a \
                         user-defined type guard before reading fields"
                            .to_string(),
                    ],
                );
                Type::Error
            }
            _ => {
                // A primitive's members are all methods, so the name usually
                // does exist — "non-object type" would send the reader looking
                // for a missing field instead of a missing call. Anchored at the
                // member, like the other method-reference sites; the non-object
                // report keeps the whole-expression span it always had.
                if !self.try_report_method_reference(name.span, &receiver_ty, &name.name) {
                    self.report_non_object_field_read(
                        span,
                        typed_receiver,
                        &receiver_ty,
                        &name.name,
                    )?;
                }
                Type::Error
            }
        };
        Ok((
            TypedExprKind::FieldAccess {
                receiver: typed_receiver,
                name,
            },
            field_ty,
        ))
    }

    /// `u.length` where `u` is a union of strings with arrays or tuples, which
    /// have no shared representation: `typeof u === "string"` picks the
    /// string's length or the array's, with `u` evaluated once.
    fn string_or_array_length(
        &mut self,
        typed_receiver: ExprId,
        arrays: Type,
        name: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let mut stmts = Vec::new();
        let held = self.hold_in_temp(typed_receiver, "length_receiver", &mut stmts)?;
        let is_string = self.push_synthetic_expr(
            TypedExprKind::TypeofTag {
                value: held,
                tag: crate::TypeofTagKind::String,
            },
            Type::Boolean,
            span,
        )?;
        let string_length = self.narrowed_length(held, Type::String, &name, span)?;
        let array_length = self.narrowed_length(held, arrays, &name, span)?;
        let result = self.push_synthetic_expr(
            TypedExprKind::Ternary {
                cond: is_string,
                then_: string_length,
                else_: array_length,
            },
            Type::Number,
            span,
        )?;
        Ok((TypedExprKind::Sequence { stmts, result }, Type::Number))
    }

    /// `receiver.name(args)` for the `method` `find_method` found on `recv_ty`.
    fn infer_found_method_call(
        &mut self,
        typed_receiver: ExprId,
        recv_ty: &Type,
        method: FoundMethod,
        call: MethodCallSite<'_>,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let MethodCallSite {
            name,
            type_args,
            args,
            expected,
            span,
        } = call;
        let (mut sig, interface_bindings, iface_mangled, _dispatch) = method;
        if sig.optional {
            self.error_with_help(
                name.span,
                format!("method `{}` may be undefined", name.name),
                vec![format!(
                    "call it with `?.()`: `receiver.{}?.(…)`",
                    name.name
                )],
            );
            self.walk_rejected_call_args(&args)?;
            return Ok((TypedExprKind::Undefined, Type::Error));
        }
        // `flat` un-nests `depth` array levels — a return type the
        // generic machinery can't express. Validate the literal depth
        // and override the resolved return type before dispatch.
        if name.name == "flat" && matches!(recv_ty.peel(), Type::Array(_)) {
            sig.ret = self.array_flat_return_type(recv_ty, &args)?;
        }
        // Anything with substitution work — interface generics
        // (`Array<T>`), method generics (`map<U>`), or both —
        // goes through the unified pipeline. Only the no-
        // generics-anywhere case (e.g. `console.log`,
        // `(42).toString()`) takes the trivial path.
        if interface_bindings.is_empty() && sig.generics.is_empty() {
            return self.infer_method_call(
                typed_receiver,
                iface_mangled,
                name,
                sig,
                type_args,
                args,
                span,
            );
        }
        let is_array = matches!(recv_ty.peel(), Type::Array(_));
        let method = name.name.clone();
        let call = self.infer_generic_method_call(
            typed_receiver,
            iface_mangled,
            name,
            sig,
            interface_bindings,
            type_args,
            args,
            expected,
            span,
        )?;
        if is_array {
            return self.narrow_by_callback_predicate(&method, call, span);
        }
        Ok(call)
    }

    /// `u.name(args)` where `u` is a union of strings with arrays or tuples,
    /// and both declare `name`: as tsc calls a union's method, each argument
    /// must fit both signatures. The two have no shared representation, so
    /// `typeof u === "string"` picks the string's call or the array's, with
    /// `u` and each argument evaluated once, before either.
    fn string_or_array_method_call(
        &mut self,
        typed_receiver: ExprId,
        methods: StringOrArrayMethods,
        call: MethodCallSite<'_>,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let StringOrArrayMethods {
            string_method,
            arrays,
            array_method,
        } = methods;
        let span = call.span;
        let mut stmts = Vec::new();
        let held = self.hold_in_temp(typed_receiver, "method_receiver", &mut stmts)?;
        let mut held_arguments = BTreeMap::new();
        for &arg in &call.args {
            // A literal keeps its type, which either signature may need:
            // `"a"` fits an `"a" | "b"` element where `string` wouldn't.
            let (typed_arg, _) = self.infer_expr_keeping_literals(arg, None, true)?;
            let held_arg = self.hold_in_temp(typed_arg, "method_argument", &mut stmts)?;
            held_arguments.insert(arg, held_arg);
        }
        let (string_call, string_ret, array_call, array_ret) =
            self.with_held_arguments(held_arguments, |this| {
                let (string_call, string_ret) =
                    this.narrowed_method_call(held, Type::String, string_method, call.clone())?;
                // The array's call reports what the string's already did
                // only once: a wrong argument count, say.
                let reported = this.diagnostics.len();
                let (array_call, array_ret) =
                    this.narrowed_method_call(held, arrays, array_method, call)?;
                this.drop_repeated_diagnostics(reported);
                Ok((string_call, string_ret, array_call, array_ret))
            })?;
        let is_string = self.push_synthetic_expr(
            TypedExprKind::TypeofTag {
                value: held,
                tag: crate::TypeofTagKind::String,
            },
            Type::Boolean,
            span,
        )?;
        let result_ty = Type::union(vec![string_ret, array_ret]);
        let result = self.push_synthetic_expr(
            TypedExprKind::Ternary {
                cond: is_string,
                then_: string_call,
                else_: array_call,
            },
            result_ty.clone(),
            span,
        )?;
        Ok((TypedExprKind::Sequence { stmts, result }, result_ty))
    }

    /// When `recv_ty` is a union of strings with arrays or tuples that both
    /// declare `name`, each side's method.
    fn string_or_array_methods(&self, recv_ty: &Type, name: &str) -> Option<StringOrArrayMethods> {
        let arrays = recv_ty.string_or_array_union_arrays()?;
        Some(StringOrArrayMethods {
            string_method: self.find_method(&Type::String, name)?,
            array_method: self.find_method(&arrays, name)?,
            arrays,
        })
    }

    /// Runs `infer` with `held` (source argument to its temporary) in
    /// [`Self::held_arguments`], removing them again whether or not it fails.
    fn with_held_arguments<T>(
        &mut self,
        held: BTreeMap<ExprId, ExprId>,
        infer: impl FnOnce(&mut Self) -> Result<T, CompilerFailure>,
    ) -> Result<T, CompilerFailure> {
        let sources = held.keys().copied().collect::<Vec<_>>();
        self.held_arguments.extend(held);
        let result = infer(self);
        for source in sources {
            self.held_arguments.remove(&source);
        }
        result
    }

    /// Drops each diagnostic from `since` on that repeats an earlier one.
    fn drop_repeated_diagnostics(&mut self, since: usize) {
        let later = self.diagnostics.split_off(since);
        for diagnostic in later {
            let repeats = self.diagnostics[..since]
                .iter()
                .any(|seen| seen.span == diagnostic.span && seen.message == diagnostic.message);
            if !repeats {
                self.diagnostics.push(diagnostic);
            }
        }
    }

    /// `(held as narrowed).name(args)`, for a `held` known to hold `narrowed`.
    fn narrowed_method_call(
        &mut self,
        held: ExprId,
        narrowed: Type,
        method: FoundMethod,
        call: MethodCallSite<'_>,
    ) -> Result<(ExprId, Type), CompilerFailure> {
        let span = call.span;
        let value = self.reread_temp(held)?;
        let receiver = self.push_synthetic_expr(
            TypedExprKind::Cast {
                value,
                target_ty: narrowed.clone(),
                check: None,
            },
            narrowed.clone(),
            span,
        )?;
        let (kind, ty) = self.infer_found_method_call(receiver, &narrowed, method, call)?;
        Ok((self.push_synthetic_expr(kind, ty.clone(), span)?, ty))
    }

    /// `(held as narrowed).length`, for a `held` known to hold `narrowed`.
    fn narrowed_length(
        &mut self,
        held: ExprId,
        narrowed: Type,
        name: &Ident,
        span: Span,
    ) -> Result<ExprId, CompilerFailure> {
        let Some((_, _, iface, _)) = self.lookup_interface_property(&narrowed, &name.name) else {
            return Err(super::inference_failure(&format!(
                "`{narrowed}` has no `length` property"
            )));
        };
        let value = self.reread_temp(held)?;
        let receiver = self.push_synthetic_expr(
            TypedExprKind::Cast {
                value,
                target_ty: narrowed.clone(),
                check: None,
            },
            narrowed,
            span,
        )?;
        self.push_synthetic_expr(
            TypedExprKind::InterfacePropertyAccess {
                receiver,
                iface,
                name: name.clone(),
            },
            Type::Number,
            span,
        )
    }

    pub(super) fn push_synthetic_expr(
        &mut self,
        kind: TypedExprKind,
        ty: Type,
        span: Span,
    ) -> Result<ExprId, CompilerFailure> {
        self.typed_ast
            .try_push_expr(TypedExpr { kind, span, ty })
            .map_err(crate::typechecker::arena_failure)
    }

    fn infer_index_access(
        &mut self,
        receiver: ExprId,
        index: ExprId,
        span: Span,
        expr_id: ExprId,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if let Some(field) = string_key_name(self.ast, index)? {
            return self.infer_field_access(receiver, field, span);
        }

        // detect when this IndexAccess was synthesised by the
        // destructuring lowering pass, so we can replace generic
        // tuple-index / non-indexable errors with destructure-specific
        // messages anchored on the user's pattern bracket.
        let pattern_origin = self.ast.pattern_origins.get(&expr_id).cloned();
        let (typed_receiver, receiver_ty) = self.infer_expr(receiver, None)?;
        if receiver_ty.is_structural_object() {
            let (typed_index, key_ty) = self.infer_object_key(index)?;
            let ty = self.object_index_read_type(
                &receiver_ty,
                &key_ty,
                self.ast.try_expr(index).map_err(super::arena_failure)?.span,
            );
            let kind = TypedExprKind::IndexAccess {
                receiver: typed_receiver,
                index: typed_index,
            };
            return self.narrowed_index_read(kind, ty);
        }
        // Peel: an array or tuple reached through an alias (`type Pair = [A, B]`)
        // is indexable on the same terms as the type it names.
        let elem_ty = match receiver_ty.peel() {
            Type::Array(elem) => (**elem).clone(),
            // tuple indexing must be a non-negative integer
            // literal that's in range. Out-of-range or non-literal
            // indices are compile-time errors — there's no dynamic
            // index path because each tuple slot has a distinct static
            // type.
            Type::Tuple(elements) => {
                let index_expr = self.ast.try_expr(index).map_err(super::arena_failure)?;
                let literal_idx: Option<usize> = match &index_expr.kind {
                    ExprKind::Number(n) if n.is_finite() && n.fract() == 0.0 && *n >= 0.0 => {
                        Some(*n as usize)
                    }
                    _ => None,
                };
                match literal_idx {
                    Some(idx) if idx < elements.len() => elements[idx].clone(),
                    Some(idx) => {
                        if let Some(origin) = &pattern_origin {
                            let message = format!(
                                "destructuring pattern has {} element{}, but right-hand side tuple has {} element{}",
                                origin.slot_arity,
                                if origin.slot_arity == 1 { "" } else { "s" },
                                elements.len(),
                                if elements.len() == 1 { "" } else { "s" },
                            );
                            // Every slot past the end reads out of range; the
                            // pattern is reported once.
                            let reported = self.diagnostics.iter().any(|diagnostic| {
                                diagnostic.span == origin.pattern_span
                                    && diagnostic.message == message
                            });
                            if !reported {
                                self.error(origin.pattern_span, message);
                            }
                        } else {
                            self.error(
                                index_expr.span,
                                format!(
                                    "tuple index {} out of bounds; tuple has {} element{}",
                                    idx,
                                    elements.len(),
                                    if elements.len() == 1 { "" } else { "s" },
                                ),
                            );
                        }
                        Type::Error
                    }
                    None => {
                        self.error(
                            index_expr.span,
                            format!(
                                "tuple index must be a non-negative integer literal; tuple has {} element{}",
                                elements.len(),
                                if elements.len() == 1 { "" } else { "s" },
                            ),
                        );
                        Type::Error
                    }
                }
            }
            // A union of arrays and tuples is one `$Array` at runtime, so a read
            // takes each member's element at the index and joins them. A tuple
            // member needs a literal index in its range, as a lone tuple does.
            Type::Union(members) if receiver_ty.is_array_like_union() => {
                self.array_like_union_element(members, index, pattern_origin.as_ref())?
            }
            // indexed read on Uint8Array returns the byte as
            // an unsigned number 0..=255. Indexed write isn't a parse
            // form at all (`arr[i] = v` is rejected by the parser as
            // "invalid assignment target"), so no separate check
            // needed here.
            Type::Uint8Array => Type::Number,
            Type::Error => Type::Error,
            // indexing into un-narrowed `unknown` is rejected.
            Type::Unknown => {
                if let Some(origin) = &pattern_origin {
                    self.error_with_help(
                        origin.pattern_span,
                        "cannot destructure a value of type `unknown`".to_string(),
                        vec![
                            "narrow first with `Array.isArray(x)` (or another \
                             type guard) before destructuring"
                                .to_string(),
                        ],
                    );
                } else {
                    self.error_with_help(
                        span,
                        "cannot index into `unknown`".to_string(),
                        vec![
                            "narrow first with `Array.isArray(x)` (or another \
                             type guard) before indexing"
                                .to_string(),
                        ],
                    );
                }
                Type::Error
            }
            // objects/interfaces *are* indexable, just by a string literal
            // (which routes to property access above) — a dynamic index here
            // is the real error. Distinguish it from genuinely non-indexable
            // receivers (`number`, etc.), which keep the message below.
            _ if pattern_origin.is_none() && receiver_ty.is_structural_object() => {
                self.error_with_help(
                    span,
                    "objects can only be indexed by a string literal".to_string(),
                    vec![
                        "use `obj[\"fieldName\"]` for a known field, or \
                         `Map<string, V>` if you need dynamic string keys"
                            .to_string(),
                    ],
                );
                // the index isn't a number here, so skip the trailing
                // `Some(&Type::Number)` inference that would add a spurious
                // "expected number" secondary error.
                let (typed_index, _) = self.infer_expr(index, None)?;
                return Ok((
                    TypedExprKind::IndexAccess {
                        receiver: typed_receiver,
                        index: typed_index,
                    },
                    Type::Error,
                ));
            }
            _ => {
                if let Some(origin) = &pattern_origin {
                    self.error_with_help(
                        origin.pattern_span,
                        format!(
                            "cannot destructure a value of type `{receiver_ty}`; expected a tuple or array"
                        ),
                        self.definition_help(&receiver_ty),
                    );
                } else {
                    let help = self.definition_help(&receiver_ty);
                    // Only an indexable non-null form makes the narrowing the fix.
                    let culprit = self.nullish_culprit(&[(typed_receiver, &receiver_ty)], |t| {
                        matches!(
                            t.peel(),
                            Type::Array(_) | Type::Tuple(_) | Type::String | Type::Uint8Array
                        )
                    });
                    self.error_with_narrowing_hint(
                        span,
                        format!("cannot index into non-array type `{receiver_ty}`"),
                        help,
                        culprit,
                    )?;
                }
                Type::Error
            }
        };
        let (typed_index, _) = self.infer_expr(index, Some(&Type::Number))?;
        let kind = TypedExprKind::IndexAccess {
            receiver: typed_receiver,
            index: typed_index,
        };
        self.narrowed_index_read(kind, elem_ty)
    }

    /// An index read, or the narrowed view of it when a guard narrowed it.
    fn narrowed_index_read(
        &self,
        kind: TypedExprKind,
        read_ty: Type,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        if let Some(path) = self.kind_to_reference_path(&kind)?
            && let Some(read) = self.narrowed_read(path)
        {
            return Ok(read);
        }
        Ok((kind, read_ty))
    }

    /// The element a read at `index` gives from a union of arrays and tuples: the
    /// union of each member's element there. An array member gives its element at
    /// any index; a tuple member needs a non-negative integer literal within its
    /// arity, since its positions have distinct types and no runtime length check
    /// guards a shorter variant.
    fn array_like_union_element(
        &mut self,
        members: &[Type],
        index: ExprId,
        pattern_origin: Option<&crate::PatternOrigin>,
    ) -> Result<Type, CompilerFailure> {
        let index_expr = self.ast.try_expr(index).map_err(super::arena_failure)?;
        let index_span = index_expr.span;
        let literal_idx: Option<usize> = match &index_expr.kind {
            ExprKind::Number(n) if n.is_finite() && n.fract() == 0.0 && *n >= 0.0 => {
                Some(*n as usize)
            }
            _ => None,
        };
        let mut elements: Vec<Type> = Vec::with_capacity(members.len());
        let mut min_tuple_arity: Option<usize> = None;
        let mut tuple_lacks_index = false;
        for member in members {
            match member.peel() {
                Type::Array(element) => elements.push((**element).clone()),
                Type::Tuple(positions) => {
                    min_tuple_arity =
                        Some(min_tuple_arity.map_or(positions.len(), |m| m.min(positions.len())));
                    match literal_idx.and_then(|idx| positions.get(idx)) {
                        Some(element) => elements.push(element.clone()),
                        None => tuple_lacks_index = true,
                    }
                }
                _ => {
                    return Err(super::inference_failure(
                        "array-like union member is neither an array nor a tuple",
                    ));
                }
            }
        }
        let Some(min_arity) = min_tuple_arity else {
            return Ok(Type::union(elements));
        };
        let Some(idx) = literal_idx else {
            self.error(
                index_span,
                "tuple index must be a non-negative integer literal".to_string(),
            );
            return Ok(Type::Error);
        };
        if !tuple_lacks_index {
            return Ok(Type::union(elements));
        }
        self.report_union_tuple_index_out_of_bounds(idx, min_arity, index_span, pattern_origin);
        Ok(Type::Error)
    }

    fn report_union_tuple_index_out_of_bounds(
        &mut self,
        idx: usize,
        min_arity: usize,
        index_span: Span,
        pattern_origin: Option<&crate::PatternOrigin>,
    ) {
        let plural = if min_arity == 1 { "" } else { "s" };
        if let Some(origin) = pattern_origin {
            let slot_plural = if origin.slot_arity == 1 { "" } else { "s" };
            self.error(
                origin.pattern_span,
                format!(
                    "destructuring pattern has {} element{slot_plural}, but a tuple in the right-hand side union has only {min_arity} element{plural}",
                    origin.slot_arity,
                ),
            );
        } else {
            self.error(
                index_span,
                format!(
                    "index {idx} is out of bounds for a tuple in the union (the shortest has {min_arity} element{plural})",
                ),
            );
        }
    }

    /// Infer data fields before method bodies so receiver types do not depend on
    /// member order. Cached expressions still execute in their original source order.
    pub(super) fn infer_object_receiver(
        &mut self,
        members: &[crate::ObjectLiteralMember],
        expected: Option<&std::collections::BTreeMap<String, crate::ObjectField>>,
    ) -> Result<(Type, InferredObjectFields), CompilerFailure> {
        let mut fields = expected.cloned().unwrap_or_default();
        let mut inferred = std::collections::BTreeMap::new();
        let mut method_sources = std::collections::BTreeMap::new();
        let mut has_method = false;
        if expected.is_none() {
            for member in members {
                if let crate::ObjectLiteralMember::Field(field) = member
                    && matches!(
                        self.ast
                            .try_expr(field.value)
                            .map_err(super::arena_failure)?
                            .kind,
                        ExprKind::FunctionExpression { .. }
                    )
                {
                    has_method = true;
                    break;
                }
            }
        }
        if expected.is_some() || !has_method {
            return Ok((
                Type::Object {
                    index: None,
                    fields,
                },
                inferred,
            ));
        }
        for member in members {
            let (value, name) = match member {
                crate::ObjectLiteralMember::Field(field) => (field.value, Some(&field.name.name)),
                crate::ObjectLiteralMember::Spread { value, .. }
                | crate::ObjectLiteralMember::Computed { value, .. } => (*value, None),
            };
            let signature = match self.ast.try_expr(value).map_err(super::arena_failure)?.kind {
                ExprKind::FunctionExpression { function, .. } => {
                    Some(self.function_expression_signature(function, None)?)
                }
                ExprKind::Arrow { .. } => Some(self.function_expression_signature(value, None)?),
                _ => None,
            };
            if let Some(ty) = signature {
                if let Some(name) = name {
                    fields.insert(name.clone(), crate::ObjectField::required(ty));
                    method_sources.insert(name.clone(), value);
                }
                continue;
            }
            let errors_before = self.error_count();
            let hint = name.and_then(|name| override_field_signature(name));
            let (id, ty) = self.infer_expr(value, hint.as_ref())?;
            inferred.insert(value, (id, ty.clone(), self.error_count() > errors_before));
            if let Some(name) = name {
                method_sources.remove(name);
                fields.insert(name.clone(), crate::ObjectField::required(ty));
            } else if let Some(SpreadFields { fields: spread, .. }) = self.spread_source_fields(
                id,
                &ty,
                self.ast.try_expr(value).map_err(super::arena_failure)?.span,
            )? {
                for name in spread.keys() {
                    method_sources.remove(name);
                }
                for (name, field) in spread {
                    let merged = merge_spread_field_type(fields.remove(&name), field);
                    fields.insert(name, merged);
                }
            }
        }
        self.infer_receiver_methods(members, &method_sources, &mut fields, &mut inferred)?;
        Ok((
            Type::Object {
                index: None,
                fields,
            },
            inferred,
        ))
    }

    fn infer_receiver_methods(
        &mut self,
        members: &[crate::ObjectLiteralMember],
        method_sources: &std::collections::BTreeMap<String, ExprId>,
        fields: &mut std::collections::BTreeMap<String, crate::ObjectField>,
        inferred: &mut InferredObjectFields,
    ) -> Result<(), CompilerFailure> {
        let mut pending: Vec<(String, ExprId)> = members
            .iter()
            .map(|member| {
                let crate::ObjectLiteralMember::Field(field) = member else {
                    return Ok::<_, CompilerFailure>(None);
                };
                Ok(matches!(
                    self.ast
                        .try_expr(field.value)
                        .map_err(super::arena_failure)?
                        .kind,
                    ExprKind::FunctionExpression { .. } | ExprKind::Arrow { .. }
                )
                .then(|| (field.name.name.clone(), field.value)))
            })
            .filter_map(Result::transpose)
            .collect::<Result<_, _>>()?;
        while !pending.is_empty() {
            let unresolved = pending.iter().filter_map(|(name, value)| {
                if method_sources.get(name) != Some(value) { return None; }
                matches!(fields.get(name).map(|field| field.ty.peel()), Some(Type::Function { ret, .. }) if **ret == Type::Unknown)
                    .then_some(name.as_str())
            }).collect::<std::collections::HashSet<_>>();
            let mut index = 0;
            for (candidate, (_, value)) in pending.iter().enumerate() {
                if self
                    .receiver_dependencies(*value)?
                    .iter()
                    .all(|name| !unresolved.contains(name.as_str()))
                {
                    index = candidate;
                    break;
                }
            }
            let (name, value) = pending.remove(index);
            let previous_hint = self.object_this_hint.replace(Type::Object {
                index: None,
                fields: fields.clone(),
            });
            let errors_before = self.error_count();
            let hint = override_field_signature(&name);
            let (id, ty) = self.infer_expr(value, hint.as_ref())?;
            self.object_this_hint = previous_hint;
            inferred.insert(value, (id, ty.clone(), self.error_count() > errors_before));
            if method_sources.get(&name) == Some(&value) {
                fields.insert(name, crate::ObjectField::required(ty));
            }
        }

        Ok(())
    }

    /// Only reads of this object's receiver constrain the order in which method
    /// returns are inferred. Nested ordinary functions establish another receiver.
    fn receiver_dependencies(&self, value: ExprId) -> Result<Vec<String>, CompilerFailure> {
        if !matches!(
            self.ast.try_expr(value).map_err(super::arena_failure)?.kind,
            ExprKind::FunctionExpression { .. }
        ) {
            return Ok(Vec::new());
        }
        let span = self.ast.try_expr(value).map_err(super::arena_failure)?.span;
        let nested = self
            .ast
            .source_expressions()
            .iter()
            .filter(|expr| {
                expr.span.start > span.start
                    && expr.span.end <= span.end
                    && matches!(expr.kind, ExprKind::FunctionExpression { .. })
            })
            .map(|expr| expr.span)
            .collect::<Vec<_>>();
        let aliases = self.receiver_aliases(span, &nested)?;
        self.ast
            .expr_ids()
            .map_err(super::arena_failure)?
            .map(|id| {
                let expr = self.ast.try_expr(id).map_err(super::arena_failure)?;
                if expr.span.start < span.start || expr.span.end > span.end {
                    return Ok::<_, CompilerFailure>(None);
                }
                let (receiver, name) = match &expr.kind {
                    ExprKind::FieldAccess { receiver, name } => (*receiver, name.name.clone()),
                    ExprKind::IndexAccess { receiver, index } => {
                        let ExprKind::String(name) = &self
                            .ast
                            .try_expr(*index)
                            .map_err(super::arena_failure)?
                            .kind
                        else {
                            return Ok(None);
                        };
                        (*receiver, name.clone())
                    }
                    ExprKind::OptionalChain { base, parts } => {
                        let name = match match parts.first() {
                            Some(part) => part,
                            None => return Ok(None),
                        } {
                            crate::ChainPart::Field { name, .. } => name.name.clone(),
                            crate::ChainPart::Index { idx, .. } => {
                                let ExprKind::String(name) =
                                    &self.ast.try_expr(*idx).map_err(super::arena_failure)?.kind
                                else {
                                    return Ok(None);
                                };
                                name.clone()
                            }
                            _ => return Ok(None),
                        };
                        (*base, name)
                    }
                    _ => return Ok(None),
                };
                let own_this = !nested
                    .iter()
                    .any(|nested| expr.span.start >= nested.start && expr.span.end <= nested.end);
                Ok(self
                    .is_receiver_reference(receiver, &aliases, own_this)?
                    .then_some(name))
            })
            .filter_map(Result::transpose)
            .collect::<Result<_, _>>()
    }

    fn receiver_aliases(
        &self,
        span: Span,
        nested: &[Span],
    ) -> Result<std::collections::HashSet<String>, CompilerFailure> {
        let mut aliases = std::collections::HashSet::new();
        loop {
            let before = aliases.len();
            for statement in self.ast.source_statements() {
                if statement.span.start < span.start || statement.span.end > span.end {
                    continue;
                }
                let own_this = !nested.iter().any(|nested| {
                    statement.span.start >= nested.start && statement.span.end <= nested.end
                });
                if let crate::StmtKind::Let { name, value, .. }
                | crate::StmtKind::Const { name, value, .. } = &statement.kind
                    && self.is_receiver_reference(*value, &aliases, own_this)?
                {
                    aliases.insert(name.name.clone());
                }
            }
            if aliases.len() == before {
                break;
            }
        }
        Ok(aliases)
    }

    fn is_receiver_reference(
        &self,
        mut value: ExprId,
        aliases: &std::collections::HashSet<String>,
        own_this: bool,
    ) -> Result<bool, CompilerFailure> {
        loop {
            match &self.ast.try_expr(value).map_err(super::arena_failure)?.kind {
                ExprKind::This => return Ok(own_this),
                ExprKind::Identifier(name) => return Ok(aliases.contains(&name.name)),
                ExprKind::Paren(inner)
                | ExprKind::As { expr: inner, .. }
                | ExprKind::PostfixUnary {
                    op: crate::PostfixOp::NonNullAssert,
                    operand: inner,
                } => value = *inner,
                _ => return Ok(false),
            }
        }
    }

    fn infer_function_expression(
        &mut self,
        name: Option<Ident>,
        function: ExprId,
        this_type: Option<TypeAnnotation>,
        expected: Option<&Type>,
        keeps_returned_literals: bool,
    ) -> Result<(ExprId, Type), CompilerFailure> {
        let signature = self.function_expression_signature(function, expected)?;
        self.scopes.push();
        if let Some(name) = &name {
            self.scopes
                .insert(name.name.clone(), signature, true, name.span);
        }
        let previous_hint = self.object_this_hint.take();
        // With neither a `this` annotation nor an object literal to bind it,
        // `this` has no receiver to name, so a use is rejected as it is
        // outside a class (tsc: implicitly `any`).
        let receiver = this_type
            .as_ref()
            .map(|ty| self.resolve_type(ty))
            .transpose()?
            .or_else(|| previous_hint.clone());
        let previous_this = std::mem::replace(&mut self.function_this, receiver.clone());
        let previous_class = self.current_class.take();
        let previous_static = self.current_static.take();
        self.next_function_keeps_returned_literals = keeps_returned_literals;
        let (id, ty) = self.infer_expr(function, expected)?;
        self.function_this = previous_this;
        self.object_this_hint = previous_hint;
        self.current_class = previous_class;
        self.current_static = previous_static;
        self.scopes.pop();
        self.typed_ast
            .closure_this
            .insert(id, receiver.unwrap_or(Type::Unknown));
        if let Some(name) = name {
            self.typed_ast.closure_names.insert(id, name);
        }
        Ok((id, ty))
    }

    fn function_expression_signature(
        &mut self,
        function: ExprId,
        expected: Option<&Type>,
    ) -> Result<Type, CompilerFailure> {
        let ExprKind::Arrow {
            params,
            return_type,
            type_predicate,
            ..
        } = self
            .ast
            .try_expr(function)
            .map_err(super::arena_failure)?
            .kind
            .clone()
        else {
            return Err(super::inference_failure(
                "function expression wraps its function body",
            ));
        };
        self.declared_function_type(
            &params,
            return_type.as_ref(),
            type_predicate.as_ref(),
            expected,
        )
    }

    /// The type a function's own declaration gives it: its annotated parameter
    /// and return types, with any it leaves out taken from `expected`.
    pub(super) fn declared_function_type(
        &mut self,
        params: &[ParamDecl],
        return_type: Option<&TypeAnnotation>,
        type_predicate: Option<&crate::TypePredicateAnnotation>,
        expected: Option<&Type>,
    ) -> Result<Type, CompilerFailure> {
        self.check_parameter_arity(params)?;
        let hint = expected.and_then(|ty| match ty.peel() {
            Type::Function { params, ret, .. } => Some((params, ret)),
            _ => None,
        });
        let param_types: Vec<Type> = params
            .iter()
            .enumerate()
            .map(|(index, param)| {
                let resolved = param
                    .ty
                    .as_ref()
                    .map(|ty| self.resolve_type(ty))
                    .transpose()?
                    .or_else(|| hint.and_then(|(params, _)| params.get(index).cloned()))
                    .unwrap_or(Type::Error);
                Ok::<_, CompilerFailure>(crate::ObjectField::widen_optional(
                    param.is_omittable(),
                    resolved,
                ))
            })
            .collect::<Result<_, _>>()?;
        let predicate = type_predicate
            .as_ref()
            .map(|predicate| {
                let signature_params = params
                    .iter()
                    .zip(&param_types)
                    .map(|(param, ty)| crate::Param::new(param.name.name.clone(), ty.clone()))
                    .collect::<Vec<_>>();
                self.resolve_type_predicate(predicate, &signature_params)
            })
            .transpose()?
            .flatten();
        let ret = return_type
            .map(|ty| self.resolve_type(ty))
            .transpose()?
            .or_else(|| hint.map(|(_, ret)| (**ret).clone()))
            .unwrap_or(Type::Unknown);
        Ok(Type::Function {
            params: param_types,
            ret: Box::new(if type_predicate.is_some() {
                Type::Boolean
            } else {
                ret
            }),
            predicate: predicate.map(Box::new),
            has_rest: params.last().is_some_and(|param| param.rest),
            optional: params
                .iter()
                .rev()
                .skip_while(|p| p.rest)
                .take_while(|p| p.is_omittable())
                .count(),
        })
    }

    /// arrow function inference. Two-mode:
    /// * **Hint mode** — `expected` is `Some(Type::Function { … })` with
    ///   the same arity or more. The hint fills in any unannotated params and
    ///   provides the body's `expected` return-type hint. Annotated
    ///   params still typecheck against the hint and produce a
    ///   diagnostic on mismatch.
    /// * **No-hint mode** — every param needs an annotation (else
    ///   diagnostic). Expression-body return type comes from the body
    ///   itself; block-body return type is unified across all `return`
    ///   paths via the `inferred_returns` collector frame this method
    ///   pushes/pops. Block returns that no one return type covers
    ///   produce a diagnostic.
    ///
    /// Also returns whether the arrow's own errors already explain a mismatch
    /// with `expected`: with a function hint its parameters line up with, a
    /// mismatch can only be a parameter or a returned value, and each is
    /// reported where it is written. Without such a hint, the caller still
    /// reports the whole type.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn infer_arrow(
        &mut self,
        params: Vec<ParamDecl>,
        return_ty_ann: Option<TypeAnnotation>,
        type_predicate: Option<crate::TypePredicateAnnotation>,
        body: ArrowBody,
        expected: Option<&Type>,
        keeps_returned_literals: bool,
        span: Span,
    ) -> Result<(TypedExprKind, Type, bool), CompilerFailure> {
        let errors_before = self.error_count();
        self.check_parameter_arity(&params)?;
        // Arrow parameters never reach `resolve_params`, so the duplicate check
        // has to be repeated here rather than inherited.
        self.report_duplicate_params(params.iter().map(|p| &p.name));
        // Take a hint from `expected` when it's a function type whose
        // parameters the arrow's line up with: the arrow's take the hint's
        // leading types, and any past the hint's are reported, which is
        // clearer than asking each to be annotated. Only a rest parameter
        // needs an exact arity, and a hint with one of its own. We clone out
        // into owned data so we can continue mutating `self` without
        // borrow-checker complaints.
        // Peel aliases, and look through a `T | null`-style union to its
        // sole function member so an optional callback param (e.g. a
        // nullable `sort` comparator) still gives the arrow its contextual
        // parameter types.
        let arrow_rest = params.last().is_some_and(|p| p.rest);
        // A rest arrow standing for a fixed-arity function takes no hint: its
        // rest parameter would be compared with a single argument's type. It
        // is checked as a whole function instead.
        let lines_up = |hint_params: &[Type], hint_rest: bool| {
            (hint_params.len() == params.len() && arrow_rest == hint_rest)
                || !(arrow_rest || hint_rest)
        };
        let leading =
            |hint_params: &[Type]| hint_params[..params.len().min(hint_params.len())].to_vec();
        let hint_owned: Option<(Vec<Type>, Type)> = match expected.map(crate::types::Type::peel) {
            Some(Type::Function {
                params: hp,
                ret: hr,
                has_rest,
                ..
            }) if lines_up(hp, *has_rest) => Some((leading(hp), (**hr).clone())),
            Some(Type::Union(members)) => {
                let functions: Vec<_> = members
                    .iter()
                    .filter_map(|member| match member.peel() {
                        Type::Function {
                            params: hp,
                            ret,
                            has_rest,
                            ..
                        } if lines_up(hp, *has_rest) => Some((leading(hp), ret)),
                        _ => None,
                    })
                    .collect();
                functions.first().and_then(|(params, _)| {
                    functions.iter().all(|(other, _)| other == params).then(|| {
                        (
                            params.clone(),
                            Type::union(
                                functions.iter().map(|(_, ret)| (***ret).clone()).collect(),
                            ),
                        )
                    })
                })
            }
            _ => None,
        };

        self.scopes.push();
        let mut typed_params: Vec<TypedParam> = Vec::with_capacity(params.len());
        let mut params_reported = false;
        for (i, p) in params.iter().enumerate() {
            let ann_ty = p.ty.as_ref().map(|t| self.resolve_type(t)).transpose()?;
            let ty = match (&ann_ty, hint_owned.as_ref()) {
                (Some(t), Some((hp, _))) => {
                    // Parameters are **contravariant**: the call site
                    // will pass a value of type `hp[i]` into a slot
                    // declared as `t`, so we need `hp[i] ≤ t`. (Return
                    // type below is covariant — `user_ret ≤ hint_ret`.)
                    // `assignable` today is structural equality, so
                    // both directions agree; encoding the right
                    // variance here keeps the rule sound when
                    // structural subtyping / `unknown` land.
                    //
                    // When the hint param contains an unresolved
                    // generic (`(T) => U` from a generic call site),
                    // skip the check — the user's annotation is the
                    // source of truth for the closure body, and the
                    // call site's `TypeParamSubstitution::unify`
                    // walks the resulting closure type to bind T/U.
                    let own_ty = crate::ObjectField::widen_optional(p.is_omittable(), t.clone());
                    let (hint_param, own_param) = if p.rest {
                        (
                            hp.get(i).map(Type::rest_array_ignoring_readonly),
                            t.rest_array_ignoring_readonly(),
                        )
                    } else {
                        (hp.get(i), &own_ty)
                    };
                    if let Some(h) = hint_param
                        && !assignable(h, own_param, self.resolver())
                    {
                        self.error(
                            p.name.span,
                            format!("parameter `{}`: expected `{}`, got `{}`", p.name.name, h, t),
                        );
                        params_reported = true;
                    }
                    t.clone()
                }
                (Some(t), None) => t.clone(),
                (None, Some((hp, _))) => {
                    if let Some(h) = hp.get(i) {
                        h.clone()
                    } else {
                        self.error_with_help(
                            p.name.span,
                            format!("parameter `{}` is never passed an argument", p.name.name),
                            vec![format!(
                                "the expected function type takes {} parameter(s)",
                                hp.len()
                            )],
                        );
                        params_reported = true;
                        Type::Error
                    }
                }
                (None, None) if p.default.is_some() => {
                    let default = p.default.ok_or_else(|| {
                        super::inference_failure("default parameter lost its initializer")
                    })?;
                    self.infer_expr(default, None)?.1.widen_literal()
                }
                (None, None) => {
                    self.error_with_help(
                        p.name.span,
                        format!("parameter `{}` requires a type annotation", p.name.name),
                        vec!["(x: T, y: U) => …".to_string()],
                    );
                    Type::Error
                }
            };
            self.record_authored_parameter_type(
                p.name.span,
                &crate::ObjectField::widen_optional(p.optional, ty.clone()),
            );
            self.scopes
                .insert(p.name.name.clone(), ty.clone(), false, p.name.span);
            typed_params.push(TypedParam {
                name: p.name.clone(),
                optional: p.is_omittable(),
                ty: crate::ObjectField::widen_optional(p.is_omittable(), ty),
                boxed: false,
                // arrow rest flag rides from ParamDecl.rest
                // (set by `parse_arrow_param_list` once that arm lands).
                rest: p.rest,
                default: p.is_omittable().then_some(crate::DefaultValue::Undefined),
            });
        }

        self.scopes.pop();
        // Decide the return-type hint. With an annotation: it always
        // wins (and must be assignable to the contextual hint when
        // present). Without an annotation but with a hint: use the
        // hint. Otherwise: pure inference (no hint), and we collect
        // returns for block bodies.
        //
        // track whether the hint came from the explicit
        // return-type annotation (`(): T => …`) or from a contextual
        // hint at the call site. Only the explicit annotation widens
        // the closure's *outer* type — a contextual hint with a
        // `TypeVar` left by a generic call (`arr.map(x => x * 2)`)
        // must NOT replace the body's inferred return type, since
        // the generic-arg unification reads the body type to bind
        // its `U`.
        let predicate = type_predicate
            .as_ref()
            .map(|pred| {
                let params = typed_params
                    .iter()
                    .map(|p| crate::Param::new(p.name.name.clone(), p.ty.clone()))
                    .collect::<Vec<_>>();
                self.resolve_type_predicate(pred, &params)
            })
            .transpose()?
            .flatten();
        let mut annotated_ret: Option<Type> = None;
        let ret_hint: Option<Type> = match (&return_ty_ann, hint_owned.as_ref()) {
            _ if type_predicate.is_some() => {
                annotated_ret = Some(Type::Boolean);
                Some(Type::Boolean)
            }
            (Some(ann), Some((_, hr))) => {
                let t = self.resolve_type(ann)?;
                // After a parameter that doesn't fit, the hint's return is
                // moot: the whole function is already reported.
                // Skip when the hint return contains an unresolved
                // generic — same logic as the param contravariance
                // check above. The closure's annotation is the truth;
                // the call site's unify binds the var.
                if !params_reported
                    && !hr.is_void()
                    && !type_contains_type_var(hr)
                    && !assignable(&t, hr, self.resolver())
                {
                    self.error(ann.span, format!("return type: expected `{hr}`, got `{t}`"));
                }
                annotated_ret = Some(t.clone());
                Some(t)
            }
            (Some(ann), None) => {
                let t = self.resolve_type(ann)?;
                annotated_ret = Some(t.clone());
                Some(t)
            }
            (None, Some((_, hr)))
                if params_reported || matches!(hr.peel(), Type::TypeVar(_) | Type::Void) =>
            {
                None
            }
            (None, Some((_, hr))) => Some(hr.clone()),
            (None, None) => None,
        };

        // Push scope, bind params.
        self.scopes.push();
        let input_types = typed_params
            .iter()
            .map(|p| p.ty.clone())
            .collect::<Vec<_>>();
        let default_prologue = self.infer_parameter_defaults(&params, &input_types)?;
        // Fresh narrowing stack for the body, seeded with the `const`-rooted
        // narrowings that legally cross the boundary. Params must already be in
        // scope so a shadowed root is rejected. `pending_joins` is deliberately
        // left alone: a `break` inside the body snapshots an empty range over
        // the fresh, shorter stack.
        let immediately_invoked = self.immediately_invoked.take() == Some(span);
        let returns_before_end =
            immediately_invoked && super::iife::returns_before_end(self.ast, &body)?;
        let narrow_seed = self.enter_closure_narrow_boundary(span, immediately_invoked)?;
        // The body's own `return`s end its flow, not the enclosing one's.
        let prev_reachable = self.enter_body_reachability();
        // Nor can its `break`/`continue` reach a loop or switch outside it.
        let prev_loop_depth = std::mem::replace(&mut self.loop_depth, 0);
        let prev_switch_depth = std::mem::replace(&mut self.switch_depth, 0);
        let prev_nested = std::mem::replace(&mut self.in_nested_function, true);
        let prev_predicate = std::mem::replace(
            &mut self.current_type_predicate,
            predicate
                .as_ref()
                .map(|pred| {
                    let parameter =
                        typed_params
                            .get(pred.parameter_index as usize)
                            .ok_or_else(|| {
                                super::inference_failure(
                                    "closure predicate parameter index is invalid",
                                )
                                .with_span(span)
                            })?;
                    Ok::<_, CompilerFailure>((pred.clone(), parameter.name.name.clone()))
                })
                .transpose()?,
        );

        // Save / set return-type frames. Stack-based so nested arrows
        // restore correctly.
        let prev_return = std::mem::replace(&mut self.current_return, ret_hint.clone());
        let prev_keeps_returned_literals = std::mem::replace(
            &mut self.returns_keep_literals,
            keeps_returned_literals && annotated_ret.is_none(),
        );
        let prev_collect = if annotated_ret.is_none() {
            self.inferred_returns.replace(Vec::new())
        } else {
            // Annotated body uses `current_return` for checking; clear
            // the collector frame to avoid attributing inner-arrow
            // returns to an outer collector.
            self.inferred_returns.take()
        };

        let (typed_body, body_ret) = match body {
            ArrowBody::Expr(e) => {
                let (id, t) = self.infer_returned_value(e, ret_hint.as_ref())?;
                self.validate_type_predicate_return(id, span)?;
                // Re-emit the seeded regions inside the body, over a fresh read
                // of the `const` — the closure then captures the ordinary
                // binding and re-checks the cast per call.
                let id = self.wrap_narrow_exprs(id, &narrow_seed, span)?;
                (ClosureBody::Expr(id), t)
            }
            ArrowBody::Block(b) => {
                let id = self.infer_stmt(b)?.ok_or_else(|| {
                    super::inference_failure("arrow block body is a Block, never a type-only decl")
                })?;
                let id = self.wrap_narrow_regions(id, &narrow_seed, span)?;
                let mut collected = self.inferred_returns.take().unwrap_or_default();
                // Falling off the end returns `undefined`, as a bare `return;` does.
                if self.reachable && !collected.is_empty() {
                    collected.push((Type::Undefined, span));
                }
                let context_takes_undefined = ret_hint.as_ref().is_some_and(|hint| {
                    !hint.is_void()
                        && assignable(&Type::Undefined, hint, self.resolver())
                        && !matches!(hint.peel(), Type::Unknown)
                });
                let returns_into_unknown = ret_hint
                    .as_ref()
                    .is_some_and(|hint| matches!(hint.peel(), Type::Unknown));
                let t = if let Some(t) = &annotated_ret {
                    t.clone()
                } else if returns_into_unknown && !collected.is_empty() {
                    // Any return fits an `unknown` context, so the returns need
                    // not agree and the body may fall off the end, as an
                    // annotated `unknown` body may. A body with no `return`
                    // stays `void`.
                    Type::Unknown
                } else if collected.is_empty() && !self.reachable {
                    // No `return`, and the end of the body can't be reached: the
                    // closure only throws, so it never returns, as tsc infers.
                    Type::Never
                } else if collected.is_empty() && context_takes_undefined {
                    // `const done: () => undefined = () => {}`, as in TypeScript 5.1.
                    Type::Undefined
                } else {
                    self.unify_returns(&self.returned_types(collected))
                };
                (ClosureBody::Block(id), t)
            }
        };

        if immediately_invoked {
            self.invoked_body_exit = Some(self.capture_invoked_body_exit(returns_before_end));
        }
        let typed_body = if default_prologue.is_empty() {
            typed_body
        } else {
            let body = match typed_body {
                ClosureBody::Block(body) => body,
                ClosureBody::Expr(value) => self
                    .typed_ast
                    .try_push_stmt(crate::TypedStmt {
                        kind: crate::TypedStmtKind::Return(Some(value)),
                        span,
                    })
                    .map_err(super::arena_failure)?,
            };
            ClosureBody::Block(self.prepend_parameter_defaults(default_prologue, body)?)
        };
        // Restore frames.
        self.exit_closure_narrow_boundary()?;
        self.restore_reachability(prev_reachable);
        self.loop_depth = prev_loop_depth;
        self.switch_depth = prev_switch_depth;
        self.in_nested_function = prev_nested;
        self.current_type_predicate = prev_predicate;
        self.inferred_returns = prev_collect;
        self.current_return = prev_return;
        self.returns_keep_literals = prev_keeps_returned_literals;
        self.scopes.pop();

        // when the arrow has an explicit return-type
        // annotation (`(): T | null => null`), use it as the
        // closure's effective return type — both for `expr.ty.ret`
        // (consulted by call-site cast emission) and for the typed
        // AST's `return_type` field (codegen's closure-body return
        // boxing). The body's inferred type stays as the literal /
        // expression's narrow type for validation but doesn't widen
        // the closure's outer surface. Contextual hints (without an
        // explicit annotation) DO NOT widen — the body's actual
        // type must flow out so generic-arg unification at the call
        // site can bind type variables from it.
        //
        // One exception: `never` occupies a value slot, so a closure returning
        // it cannot lower into a `void` funcref signature, which has no result
        // at all. `never` is assignable to everything, so adopting the hint is
        // unobservable to the typechecker — and only a `void` hint is safe to
        // adopt, since a hint still holding a `TypeVar` has to bind against the
        // body's own type. `contextual_ret` is read off `hint_owned` because
        // `ret_hint` holds the annotation whenever there is one.
        let contextual_ret_is_void = hint_owned.as_ref().is_some_and(|(_, hr)| hr.is_void());
        let declared_ret = annotated_ret.unwrap_or_else(|| body_ret.clone());
        let effective_ret = if contextual_ret_is_void && matches!(declared_ret.peel(), Type::Never)
        {
            Type::Void
        } else {
            declared_ret
        };
        let arrow_ty = Type::Function {
            params: typed_params.iter().map(|p| p.ty.clone()).collect(),
            ret: Box::new(effective_ret.clone()),
            predicate: predicate.map(Box::new),
            // arrows can declare rest params via
            // `(...xs: T[]) => …`; the parser lowers that into a
            // `TypedParam` with `rest: true` at the trailing slot.
            has_rest: typed_params.last().is_some_and(|p| p.rest),
            optional: typed_params
                .iter()
                .rev()
                .skip_while(|p| p.rest)
                .take_while(|p| p.optional)
                .count(),
        };
        Ok((
            TypedExprKind::Closure {
                runtime_generics: self
                    .body_instantiations
                    .iter()
                    .flat_map(|scope| scope.keys().cloned())
                    .collect::<BTreeSet<_>>()
                    .into_iter()
                    .collect(),
                params: typed_params,
                return_type: effective_ret,
                body: typed_body,
                // Filled in by the capture pass after the
                // typed AST is fully built. The inferer doesn't have a
                // function-boundary view of references, so it just
                // emits the empty vec here.
                captured: Vec::new(),
            },
            arrow_ty,
            hint_owned.is_some() && self.error_count() > errors_before,
        ))
    }

    /// The types of a block body's returns to unify. Literal types kept for a
    /// function literal passed as the sole candidate of a type parameter that
    /// is the call's result (see `returns_keep_literals`) form their union
    /// when every return is a literal, as tsc infers (`() => { if (b) return
    /// 1; return 2; }` returns `1 | 2`), and widen otherwise when no one of
    /// them covers the rest.
    fn returned_types(&self, collected: Vec<(Type, Span)>) -> Vec<(Type, Span)> {
        if !self.returns_keep_literals {
            return collected;
        }
        let covered = collected.iter().any(|(candidate, _)| {
            collected
                .iter()
                .all(|(other, _)| assignable(other, candidate, self.resolver()))
        });
        if covered {
            return collected;
        }
        if let Some((_, span)) = collected.first().cloned()
            && collected.iter().all(|(ty, _)| ty.literal_base().is_some())
        {
            let union = Type::union(collected.into_iter().map(|(ty, _)| ty).collect());
            return vec![(union, span)];
        }
        collected
            .into_iter()
            .map(|(ty, span)| (ty.widen_literal(), span))
            .collect()
    }

    /// Reduce the `(Type, Span)` entries collected during a block-body
    /// arrow's walk to a single return type. Empty → `Void`. Otherwise the
    /// return every other one is `assignable` to, in whichever order they
    /// appear: each returned value has to fit the closure's type. None such →
    /// a diagnostic, plus `Type::Error` to keep downstream silent.
    fn unify_returns(&mut self, collected: &[(Type, Span)]) -> Type {
        if collected.is_empty() {
            return Type::Void;
        }
        if let Some(joined) = self.join_nullish_returns(collected) {
            return joined;
        }
        let widest = collected.iter().find(|(candidate, _)| {
            collected
                .iter()
                .all(|(other, _)| assignable(other, candidate, self.resolver()))
        });
        if let Some((widest, _)) = widest {
            return widest.clone();
        }
        self.report_conflicting_return(collected);
        Type::Error
    }

    /// `return 1; … return;` infers `number | undefined`, as in TypeScript: the
    /// nullish returns join the one type the others agree on. A bare `return;`
    /// returns `undefined`. `None` when no nullish return mixes with a value.
    fn join_nullish_returns(&mut self, collected: &[(Type, Span)]) -> Option<Type> {
        let (nullish, values): (Vec<_>, Vec<_>) = collected
            .iter()
            .partition(|(ty, _)| matches!(ty.peel(), Type::Undefined | Type::Void | Type::Null));
        if nullish.is_empty() {
            return None;
        }
        let absent = nullish.iter().map(|(ty, _)| match ty.peel() {
            Type::Null => Type::Null,
            _ => Type::Undefined,
        });
        if values.is_empty() {
            // `return;` with `return null;` is `null | undefined`; one kind alone
            // keeps its own spelling (a body of bare returns stays `void`).
            let kinds: BTreeSet<_> = absent.map(|ty| matches!(ty, Type::Null)).collect();
            return (kinds.len() > 1).then(|| Type::union(vec![Type::Null, Type::Undefined]));
        }
        let absent: Vec<Type> = absent.collect();
        let values: Vec<(Type, Span)> = values.into_iter().cloned().collect();
        let value = self.unify_returns(&values);
        if matches!(value, Type::Error) {
            return Some(Type::Error);
        }
        let mut members = vec![value];
        members.extend(absent);
        Some(Type::union(members))
    }

    /// Report the first return that fits neither way with the widest of the
    /// returns before it. Called only when no return covers them all.
    fn report_conflicting_return(&mut self, collected: &[(Type, Span)]) {
        let Some(((first, first_span), rest)) = collected.split_first() else {
            return;
        };
        let mut widest_so_far = first;
        for (other, span) in rest {
            if assignable(other, widest_so_far, self.resolver()) {
                continue;
            }
            if assignable(widest_so_far, other, self.resolver()) {
                widest_so_far = other;
                continue;
            }
            let returns_nothing = [other, widest_so_far]
                .iter()
                .any(|ty| matches!(ty.peel(), Type::Void));
            let fix = if returns_nothing {
                "return a value on every path or on none"
            } else {
                "annotate the closure's return type, or return one type on every path"
            };
            self.error(
                *span,
                format!(
                    "return type `{other}` conflicts with earlier return `{widest_so_far}`; {fix}"
                ),
            );
            return;
        }
        // Each return fit the widest of those before it, one way or the
        // other, yet no return covers them all. `assignable` is not transitive
        // across an all-optional object type, so this is reachable. The closure
        // has no type; say so rather than leave `Type::Error` undiagnosed.
        self.error(
            *first_span,
            "cannot infer one return type for this closure; annotate its return type".to_string(),
        );
    }

    // Statement walker (`infer_stmt`, `infer_assign`) moved to
    // `super::stmt`.

    // ====================================================================
    // ternary, nullish coalescing,
    // optional chaining.
    // ====================================================================

    /// postfix `x++` / `x--` / `obj.f++` / `arr[i]++`.
    /// Dispatches on operand shape; rejects non-mutable / non-numeric
    /// targets with the same diagnostic style as `infer_assign`.
    /// Operand kinds other than `Identifier` / `FieldAccess` /
    /// `IndexAccess` are rejected with "requires an assignable
    /// target".
    fn infer_postfix_unary(
        &mut self,
        op: crate::PostfixOp,
        operand: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let op_symbol = match op {
            crate::PostfixOp::Inc => "++",
            crate::PostfixOp::Dec => "--",
            crate::PostfixOp::NonNullAssert => return self.infer_non_null_assert(operand),
        };
        let operand_kind = self
            .ast
            .try_expr(operand)
            .map_err(super::arena_failure)?
            .kind
            .clone();
        Ok(match operand_kind {
            ExprKind::Identifier(ident) => self.infer_postfix_ident(op, op_symbol, ident, span)?,
            ExprKind::FieldAccess { receiver, name } => {
                self.infer_postfix_field(op, op_symbol, receiver, name, span)?
            }
            ExprKind::IndexAccess { receiver, index } => {
                self.infer_postfix_index(op, op_symbol, receiver, index, span)?
            }
            _ => {
                let operand_span = self
                    .ast
                    .try_expr(operand)
                    .map_err(super::arena_failure)?
                    .span;
                self.error_with_help(
                    operand_span,
                    format!("postfix `{op_symbol}` requires an assignable target"),
                    vec!["operand must be an identifier, `obj.field`, or `arr[i]`".to_string()],
                );
                // Still infer the operand so any nested type errors surface.
                let (_, _) = self.infer_expr(operand, None)?;
                (
                    TypedExprKind::PostfixUnary {
                        op,
                        target: crate::PostfixTarget::Local {
                            ident: Ident {
                                name: String::new(),
                                span,
                            },
                            boxed: false,
                            target_ty: Type::Error,
                        },
                    },
                    Type::Error,
                )
            }
        })
    }

    fn infer_non_null_assert(
        &mut self,
        operand: ExprId,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (mut value, mut value_ty) = self.infer_expr(operand, None)?;
        // Only a reference right under the `!` reads at its declared type, as
        // in TypeScript: `(x)!` keeps the narrowing.
        let parenthesized = matches!(
            self.ast
                .try_expr(operand)
                .map_err(super::arena_failure)?
                .kind,
            ExprKind::Paren(_)
        );
        if !parenthesized && let Some(path) = self.nullish_narrowed_path(value, &value_ty)? {
            // As in TypeScript: a reference narrowed to `null` or `undefined`
            // reads at its declared type under `!`, which then throws at run
            // time.
            let outer = self.declared_read.replace(path);
            let reread = self.infer_expr(operand, None);
            self.declared_read = outer;
            (value, value_ty) = reread?;
        }
        let result_ty = non_null_assert_type(&value_ty);
        Ok((TypedExprKind::NonNullAssert { value }, result_ty))
    }

    /// The path of `value` when a narrowing left it only `null` or
    /// `undefined` and its declared type holds more.
    fn nullish_narrowed_path(
        &self,
        value: ExprId,
        value_ty: &Type,
    ) -> Result<Option<narrowing::ReferencePath>, CompilerFailure> {
        if !is_nullish_only(value_ty) {
            return Ok(None);
        }
        let typed = self
            .typed_ast
            .try_expr(value)
            .map_err(crate::typechecker::arena_failure)?;
        let Some(path) = self.expr_to_reference_path(typed)? else {
            return Ok(None);
        };
        let declared_holds_more = self
            .declared_path_ty(&path)
            .is_some_and(|declared| !is_nullish_only(&declared));
        Ok(declared_holds_more.then_some(path))
    }

    /// Whether `++`/`--` may write its result back to a slot of `target`. A
    /// `never` slot takes it, as in tsc: it holds no value unless an alias
    /// filled a `never[]`, and then the result is the number it would be.
    fn postfix_write_fits(&self, result: &Type, target: &Type) -> bool {
        matches!(target.peel(), Type::Never) || assignable(result, target, self.resolver())
    }

    fn infer_postfix_ident(
        &mut self,
        op: crate::PostfixOp,
        op_symbol: &'static str,
        target: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), crate::compiler_error::CompilerFailure> {
        // Function-local first, then top-level (mirrors `infer_assign`).
        if let Some(entry) = self.visible_local(&target.name).cloned() {
            if entry.is_const {
                self.report_const_local_write(&target, &entry);
            }
            let path = narrowing::ReferencePath::root(narrowing::BindingId::Local {
                name: target.name.clone(),
                decl_scope: entry.decl_scope,
            });
            let operand_ty = self
                .lookup_narrowed_view(&path)
                .map_or_else(|| entry.ty.clone(), |view| view.narrowed_ty.clone());
            if !takes_postfix(&operand_ty) {
                self.error(
                    target.span,
                    format!(
                        "postfix `{op_symbol}` expects `number` or `bigint`, found `{operand_ty}`",
                    ),
                );
            }
            // the increment writes back a value of the same
            // numeric kind as the operand — `BigInt` for bigint
            // operands (so `1n + 1n: bigint` round-trips), otherwise
            // widened `Number` (so a `NumberLiteral`/literal-union
            // slot like `1 | 2 | 3` doesn't restrict the result).
            let result_ty = postfix_result_ty(&operand_ty);
            // For non-error declared types that aren't assignable from
            // the result, mirror `infer_assign`'s rejection.
            let fits = self.postfix_write_fits(&result_ty, &entry.ty);
            if !matches!(entry.ty, Type::Error) && !fits {
                self.error(
                    span,
                    super::diagnostics::mismatch_message(&entry.ty, &result_ty),
                );
            }
            // A rejected write leaves the declared type, as in TypeScript, and
            // so does a write to a `never` binding, which tsc keeps `never`.
            if !fits {
                self.invalidate_for_reassignment(path, target.span);
            } else if !matches!(entry.ty, Type::Error | Type::Never) {
                // Re-install assignment narrowing: result reads see the
                // post-increment type.
                self.install_assignment_narrowing(
                    path,
                    target.clone(),
                    result_ty.clone(),
                    target.span,
                )?;
            }
            return Ok((
                TypedExprKind::PostfixUnary {
                    op,
                    target: crate::PostfixTarget::Local {
                        ident: target,
                        boxed: false,
                        target_ty: entry.ty,
                    },
                },
                result_ty,
            ));
        }
        let visible = self.top_symbol_visible(&target.name, target.span)?;
        let global = self.top_symbols.get(&target.name).filter(|_| visible);
        Ok(if let Some(entry) = global {
            let kind_clone = entry.kind.clone();
            let prev_span = entry.declaration_span;
            let mangled = entry.mangled_name.clone();
            match kind_clone {
                ValueKind::Let { ty, .. } => {
                    self.postfix_on_global(op, op_symbol, target, mangled, ty, span)?
                }
                ValueKind::Const { ty, .. } => {
                    self.diagnostics.push(Diagnostic {
                        severity: Severity::Error,
                        span: target.span,
                        message: format!("cannot assign to const binding `{}`", target.name),
                        help: vec![format!(
                            "declare with `let` if reassignment is required: `let {} = …;`",
                            target.name
                        )],
                        notes: vec![(prev_span, "declared as `const` here".to_string())],
                    });
                    (
                        TypedExprKind::PostfixUnary {
                            op,
                            target: crate::PostfixTarget::Global {
                                name: target,
                                mangled,
                                target_ty: ty,
                            },
                        },
                        Type::Number,
                    )
                }
                ValueKind::Function { .. } => {
                    self.error_with_help(
                        target.span,
                        format!("cannot assign to function `{}`", target.name),
                        vec![
                            "top-level functions are immutable; declare a `let f = …` binding to reassign"
                                .to_string(),
                        ],
                    );
                    (
                        TypedExprKind::PostfixUnary {
                            op,
                            target: crate::PostfixTarget::Global {
                                name: target,
                                mangled,
                                target_ty: Type::Error,
                            },
                        },
                        Type::Error,
                    )
                }
            }
        } else {
            self.report_unresolved_identifier(&target.name, target.span);
            (
                TypedExprKind::PostfixUnary {
                    op,
                    target: crate::PostfixTarget::Local {
                        ident: target,
                        boxed: false,
                        target_ty: Type::Error,
                    },
                },
                Type::Error,
            )
        })
    }

    fn infer_postfix_field(
        &mut self,
        op: crate::PostfixOp,
        op_symbol: &'static str,
        receiver: ExprId,
        name: Ident,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // A bare class name is not a value, so `ClassName.field++` must resolve
        // before the receiver is typed — same intercept the assignment forms use,
        // so all three write forms share one set of diagnostics.
        match self.resolve_static_field_write(receiver, &name)? {
            StaticWrite::NotClassName => {}
            StaticWrite::Rejected { .. } => return Ok((TypedExprKind::Null, Type::Error)),
            StaticWrite::Resolved { mangled, ty } => {
                return self.postfix_on_global(op, op_symbol, name, mangled, ty, span);
            }
        }
        let recv_span = self
            .ast
            .try_expr(receiver)
            .map_err(super::arena_failure)?
            .span;
        let rw_op = super::diagnostics::RwOp::Postfix(op);
        let (typed_receiver, receiver_ty) = self.infer_expr(receiver, None)?;
        let target_ty: Type = if let Type::ClassRef { mangled, args, .. } = receiver_ty.peel() {
            let mangled = mangled.clone();
            let class_args = args.clone();
            self.class_postfix_target(&mangled, &class_args, receiver, &receiver_ty, &name, rw_op)?
        } else if self.try_report_method_assignment(name.span, &receiver_ty, &name.name) {
            Type::Error
        } else if let Some((prop_sig, _, _, _)) = self.find_property(&receiver_ty, &name.name) {
            if prop_sig.readonly {
                self.error(
                    name.span,
                    format!(
                        "cannot assign to readonly property `{}` on `{}`",
                        name.name, receiver_ty,
                    ),
                );
            }
            if self.try_report_nullable_rw_target(
                recv_span,
                &receiver_ty,
                &name,
                &prop_sig.ty,
                prop_sig.optional,
                rw_op,
            ) {
                Type::Error
            } else {
                prop_sig.ty
            }
        } else if matches!(receiver_ty, Type::Error) {
            Type::Error
        } else if let Some(fields) = self.assignment_target_fields(&receiver_ty) {
            if let Some(field) = fields.get(&name.name).cloned().or_else(|| {
                self.resolver()
                    .index_signature(&receiver_ty)
                    .map(|index| crate::ObjectField {
                        ty: *index.value,
                        optional: true,
                        readonly: index.readonly,
                        method: false,
                    })
            }) {
                if field.readonly {
                    self.error(
                        name.span,
                        format!(
                            "cannot assign to readonly property `{}` on `{}`",
                            name.name, receiver_ty,
                        ),
                    );
                }
                if self.try_report_nullable_rw_target(
                    recv_span,
                    &receiver_ty,
                    &name,
                    &field.ty,
                    field.optional,
                    rw_op,
                ) {
                    Type::Error
                } else {
                    field.ty.clone()
                }
            } else {
                let help = self.definition_help(&receiver_ty);
                self.error_with_help(
                    name.span,
                    format!("no field `{}` on type `{}`", name.name, receiver_ty),
                    help,
                );
                Type::Error
            }
        } else {
            let recv_path = self.expr_to_reference_path(
                self.typed_ast
                    .try_expr(typed_receiver)
                    .map_err(crate::typechecker::arena_failure)?,
            )?;
            self.report_unassignable_field_target(
                recv_span,
                &name,
                &receiver_ty,
                recv_path.as_ref(),
                Some(rw_op),
            );
            Type::Error
        };
        if !takes_postfix(&target_ty) {
            self.error(
                name.span,
                format!("postfix `{op_symbol}` expects `number` or `bigint`, found `{target_ty}`",),
            );
        }
        let result_ty = postfix_result_ty(&target_ty);
        if !matches!(target_ty, Type::Error) && !self.postfix_write_fits(&result_ty, &target_ty) {
            self.error(
                name.span,
                super::diagnostics::mismatch_message(&target_ty, &result_ty),
            );
        }
        if let Some(mut path) = self.expr_to_reference_path(
            self.typed_ast
                .try_expr(typed_receiver)
                .map_err(crate::typechecker::arena_failure)?,
        )? {
            path.chain
                .push(narrowing::PathElem::Field(name.name.clone()));
            self.invalidate_for_write(path, name.span);
        }
        Ok((
            TypedExprKind::PostfixUnary {
                op,
                target: crate::PostfixTarget::Field {
                    receiver: typed_receiver,
                    name,
                    target_ty: target_ty.clone(),
                },
            },
            if matches!(target_ty, Type::Error) {
                Type::Error
            } else {
                result_ty
            },
        ))
    }

    /// `g++` on a module global — shared by a module `let` and by a writable
    /// static field, which is the same global under a mangled key.
    fn postfix_on_global(
        &mut self,
        op: crate::PostfixOp,
        op_symbol: &'static str,
        name: Ident,
        mangled: crate::MangledName,
        ty: Type,
        span: Span,
    ) -> Result<(TypedExprKind, Type), crate::compiler_error::CompilerFailure> {
        let path = narrowing::ReferencePath::root(narrowing::BindingId::Global(mangled.clone()));
        let operand_ty = self
            .lookup_narrowed_view(&path)
            .map_or_else(|| ty.clone(), |view| view.narrowed_ty.clone());
        if !takes_postfix(&operand_ty) {
            self.error(
                    name.span,
                    format!(
                        "postfix `{op_symbol}` expects `number` or `bigint`, found `{operand_ty}`",
                    ),
                );
        }
        let result_ty = postfix_result_ty(&operand_ty);
        if !matches!(ty, Type::Error) && !self.postfix_write_fits(&result_ty, &ty) {
            self.error(span, super::diagnostics::mismatch_message(&ty, &result_ty));
        }
        self.renarrow_global_after_write(&name, &mangled, &ty, result_ty.clone())?;
        Ok((
            TypedExprKind::PostfixUnary {
                op,
                target: crate::PostfixTarget::Global {
                    name,
                    mangled,
                    target_ty: ty,
                },
            },
            result_ty,
        ))
    }

    /// The slot type `x.f++` reads and writes back on a class receiver.
    /// `Type::Error` (after reporting) when the target can't take a postfix.
    fn class_postfix_target(
        &mut self,
        mangled: &crate::MangledName,
        class_args: &[Type],
        receiver: ExprId,
        receiver_ty: &Type,
        name: &Ident,
        rw_op: super::diagnostics::RwOp,
    ) -> Result<Type, CompilerFailure> {
        // An accessor property has no data slot. Expression-position postfix
        // reads and writes that slot directly, with nowhere to hand its computed
        // value to a setter call; statement-position postfix desugars to an
        // assignment and could dispatch the setter, but the position isn't
        // visible here, so both are rejected together.
        if self.class_getter(mangled, class_args, &name.name).is_some()
            || self.class_setter(mangled, class_args, &name.name).is_some()
        {
            let delta = format!("{} 1", rw_op.sign());
            let op_symbol = rw_op.text();
            self.error_with_help(
                name.span,
                format!(
                    "postfix `{op_symbol}` is not supported on accessor property `{}`",
                    name.name,
                ),
                vec![format!(
                    "write `x.{n} = x.{n} {delta};` instead",
                    n = name.name
                )],
            );
            return Ok(Type::Error);
        }
        Ok(self
            .class_read_write_target(mangled, class_args, receiver, receiver_ty, name, rw_op)?
            .map_or(Type::Error, |rw| rw.read))
    }

    fn infer_postfix_index(
        &mut self,
        op: crate::PostfixOp,
        op_symbol: &'static str,
        receiver: ExprId,
        index: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let recv_span = self
            .ast
            .try_expr(receiver)
            .map_err(super::arena_failure)?
            .span;
        let (typed_receiver, receiver_ty) = self.infer_expr(receiver, None)?;
        let object = receiver_ty.is_structural_object();
        let (typed_index, key_ty) = if object {
            self.infer_object_key(index)?
        } else {
            self.infer_expr(index, Some(&Type::Number))?
        };
        let elem_ty = if object {
            self.object_index_write_type(
                &receiver_ty,
                &key_ty,
                self.ast.try_expr(index).map_err(super::arena_failure)?.span,
            )
        } else {
            self.indexed_write_elem_ty(&receiver_ty, recv_span, span)
        };
        let declared_read = if object {
            self.object_index_read_type(
                &receiver_ty,
                &key_ty,
                self.ast.try_expr(index).map_err(super::arena_failure)?.span,
            )
        } else {
            elem_ty.clone()
        };
        let read_ty = self.index_read_ty(typed_receiver, typed_index, &declared_read)?;
        if !takes_postfix(&read_ty) {
            self.error(
                span,
                format!("postfix `{op_symbol}` expects `number` or `bigint`, found `{read_ty}`",),
            );
        }
        let result_ty = postfix_result_ty(&read_ty);
        if !matches!(elem_ty, Type::Error) && !self.postfix_write_fits(&result_ty, &elem_ty) {
            self.error(
                span,
                super::diagnostics::mismatch_message(&elem_ty, &result_ty),
            );
        }
        self.invalidate_index_write(typed_receiver, typed_index, span)?;
        Ok((
            TypedExprKind::PostfixUnary {
                op,
                target: crate::PostfixTarget::Index {
                    receiver: typed_receiver,
                    index: typed_index,
                    elem_ty: read_ty,
                },
            },
            if matches!(elem_ty, Type::Error) {
                Type::Error
            } else {
                result_ty
            },
        ))
    }

    /// `cond ? then_: else_`. `cond` is type-checked against
    /// `Boolean`; predicate narrowings flow into the two branches the
    /// same way `if`/`&&`/`||` already do.
    fn infer_ternary(
        &mut self,
        cond: ExprId,
        then_: ExprId,
        else_: ExprId,
        expected: Option<&Type>,
        _span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (typed_cond, cond_ty) = self.infer_expr(cond, None)?;
        let cond_span = self.ast.try_expr(cond).map_err(super::arena_failure)?.span;
        self.check_condition_ty(&cond_ty, cond_span);

        let (true_env, false_env) = self.predicate_envs(typed_cond)?;

        let (typed_then, then_ty) = self.infer_conditional_operand(then_, &true_env, expected)?;
        let then_span = self.ast.try_expr(then_).map_err(super::arena_failure)?.span;
        let wrapped_then = self.wrap_narrow_exprs(typed_then, &true_env, then_span)?;

        let (typed_else, else_ty) = self.infer_conditional_operand(else_, &false_env, expected)?;
        let else_span = self.ast.try_expr(else_).map_err(super::arena_failure)?.span;
        let wrapped_else = self.wrap_narrow_exprs(typed_else, &false_env, else_span)?;

        let result_ty = self.ternary_result_type((then_, then_ty), (else_, else_ty), expected)?;
        Ok((
            TypedExprKind::Ternary {
                cond: typed_cond,
                then_: wrapped_then,
                else_: wrapped_else,
            },
            result_ty,
        ))
    }

    /// The type of a conditional whose branches have the given types.
    fn ternary_result_type(
        &self,
        (then_, then_ty): (ExprId, Type),
        (else_, else_ty): (ExprId, Type),
        expected: Option<&Type>,
    ) -> Result<Type, CompilerFailure> {
        // Fresh object literals join as an array literal's elements do:
        // `c ? { k: 1 } : { k: 2, m: 3 }` reads `m` from either.
        if expected.is_none()
            && let Some(normalizing) =
                object_normalization::conditional_normalization(self.ast, then_, else_)?
        {
            let reduced = self.without_fresh_subtypes(vec![then_ty, else_ty]);
            return Ok(object_normalization::normalized(&reduced, &normalizing));
        }
        if let Some(joined) = empty_literal_join(self.ast, (then_, &then_ty), (else_, &else_ty))? {
            return Ok(joined);
        }
        Ok(conditional_result_type(then_ty, else_ty, self.resolver()))
    }

    /// The type of `a || b` or `a ?? b` when `a` decides the result: `a`'s own,
    /// as in TypeScript, if `b` fits `a`'s base type. `b` is compiled though it
    /// never runs, so it must fit `a`'s representation.
    fn deciding_left_type(&self, lhs_ty: &Type, rhs_ty: &Type) -> Option<Type> {
        assignable(rhs_ty, &lhs_ty.widen_literal(), self.resolver()).then(|| lhs_ty.clone())
    }

    /// `a ?? b`. Result type is `union(strip_nullish(lhs), rhs)`.
    /// Emits a `Severity::Warning` when `lhs` is statically
    /// non-nullable (the `??` clause is unreachable).
    fn infer_nullish_coalesce(
        &mut self,
        lhs: ExprId,
        rhs: ExprId,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (typed_lhs, lhs_ty) = self.infer_expr_keeping_literals(lhs, None, true)?;
        // The right side runs only where the left is `null` or `undefined`.
        let rhs_env = self.nullish_operand_env(typed_lhs)?;
        // `tags ?? []` and `onDone ?? (() => {})` take their type from the
        // left operand, as in TypeScript; other operands keep their own.
        let fallback_hint = (cannot_be_typed_alone(self.ast, rhs)?
            && !matches!(
                lhs_ty.peel(),
                Type::Error | Type::Null | Type::Undefined | Type::Void
            ))
        .then(|| super::narrowing::strip_nullish(&lhs_ty));
        let (typed_rhs, rhs_ty) =
            self.infer_conditional_operand(rhs, &rhs_env, fallback_hint.as_ref())?;
        let rhs_span = self.ast.try_expr(rhs).map_err(super::arena_failure)?.span;
        let typed_rhs = self.wrap_narrow_exprs(typed_rhs, &rhs_env, rhs_span)?;

        // A poisoned operand has no knowable nullability, and naming it in the
        // message would print `<error>` at the user.
        let lhs_decides =
            !type_admits_nullish(&lhs_ty, self.resolver()) && !matches!(lhs_ty.peel(), Type::Error);
        if lhs_decides {
            self.diagnostics.push(crate::Diagnostic {
                severity: Severity::Warning,
                span,
                message: format!(
                    "`??` on non-nullable type `{lhs_ty}` — right side is unreachable",
                ),
                help: vec![],
                notes: vec![],
            });
        }

        // A left side that is *only* `null` or `undefined` always takes the
        // right, so the result is the right's type. Running it through
        // `strip_nullish` instead would yield `Error` — a poison type with no
        // diagnostic behind it, which reaches codegen and panics in
        // `value_type`.
        let result_ty = if matches!(lhs_ty.peel(), Type::Null | Type::Undefined) {
            rhs_ty
        } else if let Some(decided) = lhs_decides
            .then(|| self.deciding_left_type(&lhs_ty, &rhs_ty))
            .flatten()
        {
            decided
        } else {
            let present = super::narrowing::strip_nullish(&lhs_ty);
            match empty_literal_join(self.ast, (lhs, &present), (rhs, &rhs_ty))? {
                Some(joined) => joined,
                None => conditional_result_type(present, rhs_ty, self.resolver()),
            }
        };
        Ok((
            TypedExprKind::NullishCoalesce {
                lhs: typed_lhs,
                rhs: typed_rhs,
            },
            result_ty,
        ))
    }

    /// Infers the chain, then lifts a trailing `!` off it.
    ///
    /// A `!` in the middle of a chain asserts the step before it, and the chain
    /// re-adds its own `| null` afterwards. At the tail there is no later step
    /// to feed, and the only null left to remove is the one the short-circuit
    /// adds — which no step-level assertion can reach. So a trailing `!` becomes
    /// an assertion over the whole chain, which is also how TypeScript parses
    /// `a?.b!`.
    fn infer_optional_chain(
        &mut self,
        mut base: ExprId,
        mut parts: Vec<ChainPart>,
        _expected: Option<&Type>,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        // Keep a method's receiver attached when `?.()` starts after its name.
        // Method values cannot be extracted, but the field/call pair can use
        // ordinary method dispatch and preserve its receiver.
        if matches!(parts.first(), Some(ChainPart::Call { optional: true, .. })) {
            let base_span = self.ast.try_expr(base).map_err(super::arena_failure)?.span;
            if let ExprKind::FieldAccess { receiver, name } =
                string_key_callee_as_field(self.ast, base)?
            {
                parts.insert(
                    0,
                    ChainPart::Field {
                        name,
                        optional: false,
                        span: base_span,
                    },
                );
                base = receiver;
            }
        }
        // `parts[0]` is the `?.` that opened the chain, so it is never a
        // `NonNull`; the bound only keeps the remaining walk non-empty.
        let mut asserts_chain = false;
        while parts.len() > 1 && matches!(parts.last(), Some(ChainPart::NonNull { .. })) {
            parts.pop();
            asserts_chain = true;
        }
        let (kind, ty) = self.infer_chain_steps(base, parts, asserts_chain)?;
        if !asserts_chain {
            return Ok((kind, ty));
        }
        let value = self
            .typed_ast
            .try_push_expr(TypedExpr {
                kind,
                span,
                ty: ty.clone(),
            })
            .map_err(crate::typechecker::arena_failure)?;
        let result_ty = non_null_assert_type(&ty);
        Ok((TypedExprKind::NonNullAssert { value }, result_ty))
    }

    /// Walk the chain left-to-right: each step's receiver is the previous step's
    /// result, and only a `?.` step sees that receiver with `null` and
    /// `undefined` stripped — a plain step on a nullish receiver is rejected, as
    /// it would be outside a chain. Produces `tail_ty | undefined` overall when
    /// a step can short-circuit.
    ///
    /// For v1, supported part shapes: `Field` on `Type::Object` /
    /// `Type::InterfaceRef`; `Index` on `Type::Array`; `Call` on a
    /// closure-typed receiver; `Call` directly after a `Field` resolving to an
    /// interface method (lowered to `MethodCall`); `NonNull` anywhere.
    /// `asserts_tail`: a `!` follows the chain's last step.
    fn infer_chain_steps(
        &mut self,
        base: ExprId,
        parts: Vec<ChainPart>,
        asserts_tail: bool,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let (typed_base, base_ty) = self.infer_expr(base, None)?;
        // The namespace rejection subsumes the redundancy warning — a namespace
        // receiver is non-nullable too, and two diagnostics for one `?` is noise.
        if !self.reported_namespace_chain_base(base, &base_ty, &parts)? {
            self.warn_redundant_leading_optional(
                &base_ty,
                self.ast.try_expr(base).map_err(super::arena_failure)?.span,
                &parts,
            );
        }

        let mut receiver_ty = base_ty.clone();
        // The path the steps have walked so far, rooted at the base. Field-path
        // narrowings are keyed on it, so a step whose path a guard has already
        // proven reads at the narrowed type, the way the same `o.b.y` does
        // outside a chain. `None` once a step has no path form.
        let mut step_path = self.expr_to_reference_path(
            self.typed_ast
                .try_expr(typed_base)
                .map_err(crate::typechecker::arena_failure)?,
        )?;
        let mut typed_parts: Vec<TypedChainPart> = Vec::with_capacity(parts.len());
        // Set by a `Field` step that resolved to a method, consumed by the
        // `Call` step that lifts the pair into a `MethodCall`.
        let mut pending_method: Option<ChainMethod> = None;
        // Every step from the first `?.` on may be skipped, so a write in one
        // (`c?.m(x = 5)`) must not narrow what follows the chain; see
        // `infer_conditional_operand`.
        let mut short_circuit_span: Option<Span> = None;

        // A step right under a `!` reads at its declared type, as a reference
        // under a `!` outside a chain does.
        let asserted: Vec<bool> = (0..parts.len())
            .map(|index| match parts.get(index + 1) {
                Some(next) => matches!(next, ChainPart::NonNull { .. }),
                None => asserts_tail,
            })
            .collect();
        for (part, asserted) in parts.into_iter().zip(asserted) {
            // A `?.` whose receiver can't be `null` or `undefined` never
            // short-circuits, so it is the plain step and adds no
            // `| undefined`, as in tsc. A method's `?.()` can short-circuit
            // although its function type isn't nullish: the method may be
            // optional, or an interface alias may clear it.
            let may_skip_method_call = matches!(part, ChainPart::Call { .. })
                && pending_method.as_ref().is_some_and(|method| {
                    method.sig.optional
                        || self.class_method_has_mutable_payload(&method.receiver_ty, &method.name)
                });
            let part = if part.is_optional()
                && !may_skip_method_call
                && !type_admits_nullish(&receiver_ty, self.resolver())
            {
                part.as_plain_step()
            } else {
                part
            };
            if part.is_optional() && short_circuit_span.is_none() {
                short_circuit_span = Some(part.span());
                self.push_narrow_frame(super::narrowing::NarrowEnv::new());
            }
            // A method step is only legal as the callee of the `Call` that
            // follows it; anything else means the user wrote a bare method
            // reference, which is not a value here. Poisoning the receiver stops
            // *this* step from also reporting a missing member on the method's
            // function type.
            if !matches!(part, ChainPart::Call { .. })
                && let Some(dangling) = pending_method.take()
            {
                receiver_ty = self.reject_chain_method_reference(&dangling);
            }
            // Must run before the receiver guards below: `!` reads no member,
            // so it accepts the `null` and `unknown` receivers they reject —
            // exactly as the non-chain postfix `!` does.
            if let ChainPart::NonNull { span } = part {
                let result_ty = non_null_assert_type(&receiver_ty);
                receiver_ty = result_ty.clone();
                typed_parts.push(TypedChainPart::NonNull { result_ty, span });
                continue;
            }
            // `null`, `undefined` and `unknown` carry no member to dispatch on
            // and no Wasm lowering: `strip_nullish` of a nullish type yields
            // `Error`, and every member of `unknown` resolves to `unknown`.
            // Reject here, while the member name is still in hand.
            if matches!(
                receiver_ty.peel(),
                Type::Null | Type::Undefined | Type::Unknown
            ) {
                self.reject_undispatchable_chain_receiver(&receiver_ty, &part)?;
                break;
            }
            // Only `?.` short-circuits, so only `?.` may see the receiver with
            // `null` and `undefined` removed.
            if !part.is_optional() && type_admits_nullish(&receiver_ty, self.resolver()) {
                self.reject_nullable_chain_step(&receiver_ty, step_path.as_ref(), &part)?;
                break;
            }
            let effective_recv = super::narrowing::strip_nullish(&receiver_ty);
            // `infer_chain_part` may rewrite the previous part
            // (InterfaceProperty + Call → MethodCall), so it gets
            // `&mut typed_parts` rather than a borrow of the last
            // element. It returns the new part to push and the
            // resulting type.
            let (mut typed_part, next_ty) = self.infer_chain_part(
                &effective_recv,
                step_path.as_ref(),
                part,
                &mut typed_parts,
                &mut pending_method,
            )?;
            step_path = self.extend_chain_path(step_path, &typed_part)?;
            receiver_ty = self.narrow_step_result(
                step_path.as_ref(),
                &pending_method,
                asserted,
                &mut typed_part,
                next_ty,
            );
            typed_parts.push(typed_part);
        }
        if let Some(span) = short_circuit_span {
            let (_, assigned) = self.pop_narrow_frame_capture()?;
            self.merge_assigned_into_outer(assigned, span);
        }
        // A method named by the chain's last step never sees a `Call` at all.
        if let Some(dangling) = pending_method.take() {
            receiver_ty = self.reject_chain_method_reference(&dangling);
        }

        // A chain with no step left that can short-circuit has no `undefined`
        // branch to add.
        let final_ty = if short_circuit_span.is_some() {
            Type::union(vec![receiver_ty, Type::Undefined])
        } else {
            receiver_ty
        };
        Ok((
            TypedExprKind::OptionalChain {
                base: typed_base,
                parts: typed_parts,
            },
            final_ty,
        ))
    }

    /// A chain step that dispatches on the receiver — every kind but `!`, which
    /// `infer_chain_steps` handles itself because it reads no member. Mirrors
    /// the shape decisions `infer_field_access` /
    /// `infer_index_access` / `infer_call` make on the non-optional path.
    fn infer_chain_part(
        &mut self,
        receiver_ty: &Type,
        receiver_path: Option<&super::narrowing::ReferencePath>,
        part: ChainPart,
        typed_parts: &mut Vec<TypedChainPart>,
        pending_method: &mut Option<ChainMethod>,
    ) -> Result<(TypedChainPart, Type), CompilerFailure> {
        Ok(match string_key_as_field(self.ast, part)? {
            ChainPart::NonNull { .. } => {
                return Err(super::inference_failure(
                    "`!` steps never reach the member-dispatch path",
                ));
            }
            ChainPart::Field {
                name,
                optional,
                span,
            } => {
                if self.reject_unsupported_array_call(receiver_ty, &name) {
                    *pending_method = None;
                    let typed_part = TypedChainPart::Field {
                        name,
                        optional,
                        result_ty: Type::Error,
                        span,
                    };
                    return Ok((typed_part, Type::Error));
                }
                let resolved = self.lookup_chain_field(receiver_ty, receiver_path, &name, span);
                *pending_method = resolved.method;
                let result_ty = resolved.ty;
                let typed_part = if let Some(iface_name) = resolved.iface {
                    TypedChainPart::InterfaceProperty {
                        iface: iface_name,
                        name,
                        optional,
                        result_ty: result_ty.clone(),
                        span,
                    }
                } else {
                    TypedChainPart::Field {
                        name,
                        optional,
                        result_ty: result_ty.clone(),
                        span,
                    }
                };
                (typed_part, result_ty)
            }
            ChainPart::Index {
                idx,
                optional,
                span,
            } => {
                let (typed_idx, idx_ty) = if receiver_ty.is_structural_object() {
                    self.infer_object_key(idx)?
                } else {
                    self.infer_expr(idx, None)?
                };
                let idx_span = self.ast.try_expr(idx).map_err(super::arena_failure)?.span;
                if receiver_ty.is_structural_object() {
                    let ty = self.object_index_read_type(receiver_ty, &idx_ty, idx_span);
                    return Ok((
                        TypedChainPart::Index {
                            idx: typed_idx,
                            optional,
                            result_ty: ty.clone(),
                            span,
                        },
                        ty,
                    ));
                }
                if !matches!(
                    idx_ty.peel(),
                    Type::Number | Type::NumberLiteral(_) | Type::Error
                ) {
                    self.error(
                        idx_span,
                        format!("array index must be `number`, got `{idx_ty}`"),
                    );
                }
                let elem_ty = match receiver_ty.peel() {
                    Type::Array(elem) => *elem.clone(),
                    Type::Uint8Array => Type::Number,
                    Type::Tuple(elements) => {
                        match &self.ast.try_expr(idx).map_err(super::arena_failure)?.kind {
                            ExprKind::Number(n)
                                if n.is_finite() && n.fract() == 0.0 && *n >= 0.0 =>
                            {
                                elements.get(*n as usize).cloned().unwrap_or_else(|| {
                                    self.error(
                                        idx_span,
                                        format!(
                                            "tuple index {n} out of bounds; tuple has {} elements",
                                            elements.len()
                                        ),
                                    );
                                    Type::Error
                                })
                            }
                            _ => {
                                self.error(
                                    idx_span,
                                    "tuple index must be a non-negative integer literal".into(),
                                );
                                Type::Error
                            }
                        }
                    }
                    Type::Union(members) if receiver_ty.is_array_like_union() => {
                        self.array_like_union_element(members, idx, None)?
                    }
                    Type::Error => Type::Error,
                    Type::Unknown => Type::Unknown,
                    other => {
                        self.error(
                            span,
                            format!("cannot index into `{other}` (expected an array)"),
                        );
                        Type::Error
                    }
                };
                (
                    TypedChainPart::Index {
                        idx: typed_idx,
                        optional,
                        result_ty: elem_ty.clone(),
                        span,
                    },
                    elem_ty,
                )
            }
            ChainPart::Call {
                args,
                type_args: _,
                optional,
                span,
            } => {
                let resolved_method = pending_method.take();
                if let Some(method) = &resolved_method
                    && method.sig.optional
                    && !optional
                {
                    self.error_with_help(
                        method.span,
                        format!("method `{}` may be undefined", method.name),
                        vec![format!(
                            "call it with `?.()`: `receiver.{}?.(…)`",
                            method.name
                        )],
                    );
                }
                // The call form of a method-level-generic method: genuinely
                // unimplemented, unlike the bare reference `chain_method_field`
                // defers to us. Falls through rather than returning so the
                // arguments still typecheck; the `Error` field type keeps the
                // lift below from firing, so no second diagnostic follows.
                if let Some(m) = &resolved_method
                    && !m.sig.generics.is_empty()
                {
                    self.error(
                        m.span,
                        format!(
                            "optional method `{}` with method-level generics is not yet \
                             supported in chain position",
                            m.name,
                        ),
                    );
                }

                // when the preceding part is an
                // InterfaceProperty whose resolved type is a function,
                // lift the InterfaceProperty + Call pair into a single
                // `MethodCall` part. The prelude exposes a method
                // wrapper at `<iface>#<method>` (consumed by
                // `emit_method_call_with_receiver_on_stack`) but no
                // separate property-getter wrapper that would let the
                // two-step shape (property-load → call_ref) work for
                // methods.
                if let Some(TypedChainPart::InterfaceProperty {
                    result_ty: prop_result_ty,
                    ..
                }) = typed_parts.last()
                    && matches!(prop_result_ty.peel(), Type::Function { .. })
                {
                    let Some(TypedChainPart::InterfaceProperty {
                        iface,
                        name,
                        optional: prop_optional,
                        result_ty: fn_ty,
                        span: prop_span,
                    }) = typed_parts.pop()
                    else {
                        return Err(super::inference_failure(
                            "matched on InterfaceProperty above",
                        ));
                    };
                    let Type::Function {
                        params,
                        ret,
                        has_rest,
                        ..
                    } = fn_ty.peel()
                    else {
                        return Err(super::inference_failure(
                            "guarded by `matches!(.., Function)` above",
                        ));
                    };
                    let (param_tys, ret_ty, has_rest) =
                        (params.clone(), (**ret).clone(), *has_rest);
                    // Keep the full property/call span for method diagnostics.
                    let combined_span = Span {
                        file: prop_span.file,
                        start: prop_span.start.min(span.start),
                        end: prop_span.end.max(span.end),
                    };
                    // A method resolved through `find_method` binds against its
                    // full signature; a function-typed *property* has only the
                    // structural type to bind against.
                    let typed_args = match &resolved_method {
                        Some(m) => self.bind_param_call_args(
                            &m.params,
                            &ret_ty,
                            CallLift::Method {
                                receiver_ty: &m.receiver_ty,
                                name: &name.name,
                                sig: &m.sig,
                            },
                            &args,
                            combined_span,
                        )?,
                        None => self.bind_fn_type_call_args(
                            &param_tys,
                            &ret_ty,
                            has_rest,
                            CallLift::Anon { ty: &fn_ty },
                            &args,
                            combined_span,
                        )?,
                    };
                    if optional
                        && let Some(method) = &resolved_method
                        && self.class_method_has_mutable_payload(&method.receiver_ty, &method.name)
                    {
                        // An interface alias can replace a class method with
                        // undefined. Read the method value before the optional
                        // call so arguments are skipped, retaining its receiver.
                        typed_parts.push(TypedChainPart::Field {
                            name,
                            optional: prop_optional,
                            result_ty: crate::ObjectField::widen_optional(
                                method.sig.optional,
                                fn_ty,
                            ),
                            span: prop_span,
                        });
                        return Ok((
                            TypedChainPart::Call {
                                args: typed_args,
                                optional: true,
                                result_ty: ret_ty.clone(),
                                span,
                            },
                            ret_ty,
                        ));
                    }
                    return Ok((
                        TypedChainPart::MethodCall {
                            iface,
                            name,
                            args: typed_args,
                            optional: prop_optional,
                            result_ty: ret_ty.clone(),
                            span: combined_span,
                        },
                        ret_ty,
                    ));
                }

                // Closure-typed receiver: ordinary `Call` part.
                let (ret_ty, typed_args) = match receiver_ty.peel() {
                    Type::Function {
                        params,
                        ret,
                        has_rest,
                        ..
                    } => {
                        let (param_tys, ret_ty, has_rest) =
                            (params.clone(), (**ret).clone(), *has_rest);
                        let typed_args = self.bind_fn_type_call_args(
                            &param_tys,
                            &ret_ty,
                            has_rest,
                            CallLift::Anon { ty: receiver_ty },
                            &args,
                            span,
                        )?;
                        (ret_ty, typed_args)
                    }
                    other => {
                        let ret_ty = match other {
                            Type::Error => Type::Error,
                            Type::Unknown => Type::Unknown,
                            _ => {
                                self.error(
                                    span,
                                    format!("cannot call `{other}` (expected a function)"),
                                );
                                Type::Error
                            }
                        };
                        let typed_args = args
                            .iter()
                            .map(|&a| Ok::<_, CompilerFailure>(self.infer_expr(a, None)?.0))
                            .collect::<Result<_, _>>()?;
                        (ret_ty, typed_args)
                    }
                };
                (
                    TypedChainPart::Call {
                        args: typed_args,
                        optional,
                        result_ty: ret_ty.clone(),
                        span,
                    },
                    ret_ty,
                )
            }
        })
    }

    /// A static-dispatch interface is a namespace, not a value: its binding
    /// lowers to an inert typed null that every call site drops. A `?.` on it
    /// would see that null, short-circuit, and yield `null` where the member was
    /// asked for — so reject the form rather than compile that meaning.
    fn reported_namespace_chain_base(
        &mut self,
        base: ExprId,
        base_ty: &Type,
        parts: &[ChainPart],
    ) -> Result<bool, CompilerFailure> {
        let Some(first) = parts.first() else {
            return Ok(false);
        };
        if !first.is_optional() {
            return Ok(false);
        }
        let Type::InterfaceRef { mangled, name, .. } = base_ty.peel() else {
            return Ok(false);
        };
        let Some(sym) = self.resolver().lookup(mangled, name) else {
            return Ok(false);
        };
        if !matches!(
            &sym.kind,
            crate::TypeKind::Interface {
                dispatch: crate::Dispatch::Static,
                ..
            }
        ) {
            return Ok(false);
        }
        // The declared interface is `NumberConstructor` / `InstantConstructor`,
        // which is not a name in scope — so a fix naming it would not compile.
        // Quote the path the source wrote, and where there is none (a ternary,
        // a call result), name no replacement at all rather than a wrong one.
        let base_expr = self.ast.try_expr(base).map_err(super::arena_failure)?;
        let (subject, help) = match self.dotted_path(base)? {
            Some(written) => {
                let help = match namespace_fix_forms(&written, first)? {
                    Some((fixed, wrote)) => {
                        format!("a namespace is never null — write `{fixed}`, not `{wrote}`")
                    }
                    None => NAMESPACE_DROP_HELP.to_string(),
                };
                (format!("`{written}`"), help)
            }
            None => (
                "this expression".to_string(),
                NAMESPACE_DROP_HELP.to_string(),
            ),
        };
        self.error_with_help(
            base_expr.span,
            format!("{subject} is a namespace, not a value — `?.` has nothing to guard"),
            vec![help],
        );
        Ok(true)
    }

    /// The dotted name an expression spells (`Number`, `Temporal.Instant`), if
    /// it is one. A namespace is always reached by a path of plain identifiers,
    /// so anything else has no name to quote back at the user.
    fn dotted_path(&self, expr: ExprId) -> Result<Option<String>, CompilerFailure> {
        Ok(
            match &self.ast.try_expr(expr).map_err(super::arena_failure)?.kind {
                ExprKind::Identifier(ident) => Some(ident.name.clone()),
                ExprKind::FieldAccess { receiver, name } => Some(format!(
                    "{}.{}",
                    match self.dotted_path(*receiver)? {
                        Some(path) => path,
                        None => return Ok(None),
                    },
                    name.name
                )),
                // `(Number)?.x` is a shape an LLM writes; the parens are not part
                // of the name.
                ExprKind::Paren(inner) => self.dotted_path(*inner)?,
                _ => None,
            },
        )
    }

    /// A `?.` on a base that can never be null does nothing. Warn only for the
    /// *leading* `?.`, where the base's type is the user's own annotation —
    /// mid-chain the same shape comes from a member's declared type, which the
    /// user may not control.
    fn warn_redundant_leading_optional(
        &mut self,
        base_ty: &Type,
        base_span: Span,
        parts: &[ChainPart],
    ) {
        if parts.first().is_none_or(|p| !p.is_optional()) {
            return;
        }
        // A poisoned receiver has no knowable nullability, and naming it in the
        // message would print `<error>` at the user.
        if type_admits_nullish(base_ty, self.resolver()) || matches!(base_ty.peel(), Type::Error) {
            return;
        }
        self.diagnostics.push(crate::Diagnostic {
            severity: Severity::Warning,
            span: base_span,
            message: format!("optional chain on non-nullable receiver `{base_ty}` is redundant"),
            help: vec![],
            notes: vec![],
        });
    }

    /// Report a chain step whose receiver has no member to dispatch on.
    /// `unknown` gets the same "narrow first" help the non-chain field-access
    /// path gives, since narrowing away `null` — whether by `?.` or a guard —
    /// leaves the dynamic type just as unknown.
    fn reject_undispatchable_chain_receiver(
        &mut self,
        receiver_ty: &Type,
        part: &ChainPart,
    ) -> Result<(), CompilerFailure> {
        let ChainStepPhrasing { action, span, .. } = chain_step_phrasing(part)?;
        if matches!(receiver_ty.peel(), Type::Unknown) {
            self.error_with_help(
                span,
                format!("cannot {action} a value of type `unknown`"),
                vec![
                    "narrow first with `typeof x === \"…\"`, `Array.isArray(x)`, \
                     or a user-defined type guard — a null check alone leaves \
                     the type `unknown`"
                        .to_string(),
                ],
            );
            return Ok(());
        }
        let shown = match receiver_ty.peel() {
            Type::Undefined | Type::Void => "undefined",
            _ => "null",
        };
        self.error(
            span,
            format!(
                "cannot {action} a value of type `{shown}` — the receiver is always \
                 {shown}, so give it a type that can hold a value"
            ),
        );
        Ok(())
    }

    /// Report a plain `.`/`[]`/`()` step whose receiver can be null. The earlier
    /// `?.` short-circuits its own step only; every step after it is an ordinary
    /// access and needs its own null handling.
    /// A step whose receiver still admits `null`. `receiver_path` is that
    /// receiver's path, when it has one: a step is admitted on the strength of a
    /// narrowing, so the *absence* of one is often the whole reason this fires,
    /// and the hint that names what killed it is the actionable half. Without it
    /// the `?.` suggestion silences a dropped narrowing rather than fixing it.
    fn reject_nullable_chain_step(
        &mut self,
        receiver_ty: &Type,
        receiver_path: Option<&super::narrowing::ReferencePath>,
        part: &ChainPart,
    ) -> Result<(), CompilerFailure> {
        let ChainStepPhrasing {
            action,
            optional_form,
            span,
        } = chain_step_phrasing(part)?;
        let mut help = vec![format!(
            "continue the chain with `{optional_form}`, or assert non-null with `!`"
        )];
        let mut notes = Vec::new();
        if let Some((extra_help, extra_notes)) =
            receiver_path.and_then(|p| self.narrowing_hint_for_path(p))
        {
            help.extend(extra_help);
            notes.extend(extra_notes);
        }
        self.error_with_help_and_notes(
            span,
            format!("cannot {action} a value of type `{receiver_ty}`"),
            help,
            notes,
        );
        Ok(())
    }

    /// A chain step named a method but no `Call` consumed it. Left admitted,
    /// the step lowers to an argument-less invocation of the method wrapper.
    ///
    /// Returns the type the chain continues with: poisoned, so the step that
    /// follows doesn't also report a miss on the method's function type, and a
    /// trailing reference doesn't hand that type to the binding.
    fn reject_chain_method_reference(&mut self, method: &ChainMethod) -> Type {
        self.report_method_reference(method.span, &method.receiver_ty, &method.name, &method.sig);
        Type::Error
    }

    /// `s.field` on a union whose every member carries fields — object types,
    /// interfaces, classes, or a mix. Accepts iff every member has `field`; the
    /// result is the canonical union of each member's field type. The members may
    /// lay the field out at different slots, so there is no static index — the
    /// read goes through the runtime field-name scan over
    /// `$ObjectShape.field_names`, which class instances carry too (their
    /// struct's header slots 0-2 are the `$ObjectShape` prefix).
    ///
    /// Reports the first member that cannot back the field and returns
    /// `Type::Error`. `receiver_path` anchors the "what killed the narrowing"
    /// hint; `None` omits it.
    fn union_field_read_ty(
        &mut self,
        span: Span,
        receiver_path: Option<&super::narrowing::ReferencePath>,
        receiver_ty: &Type,
        members: &[Type],
        name: &str,
    ) -> Type {
        let mut per_member_tys: Vec<Type> = Vec::with_capacity(members.len());
        for m in members {
            match self.union_member_field_read_ty(m, name) {
                Ok(ty) => per_member_tys.push(ty),
                Err(miss) => {
                    let missing = m.clone();
                    self.report_union_field_miss(
                        span,
                        receiver_path,
                        receiver_ty,
                        &missing,
                        name,
                        miss,
                    );
                    return Type::Error;
                }
            }
        }
        Type::union(per_member_tys)
    }

    /// Look up a field on an optional-chain receiver. The resolution carries
    /// the field's type, (for interface receivers) the owner's mangled name so
    /// the typed chain part can be tagged `InterfaceProperty` vs `Field`, and
    /// (for methods) the signature a following `Call` binds its arguments to.
    fn lookup_chain_field(
        &mut self,
        receiver_ty: &Type,
        receiver_path: Option<&super::narrowing::ReferencePath>,
        name: &Ident,
        span: Span,
    ) -> ChainField {
        if name.name == "length"
            && let Some(length_ty) = tuple_receiver_length_type(receiver_ty)
        {
            return ChainField::property(length_ty, crate::mangle::prelude("Array"));
        }
        match receiver_ty.peel() {
            // An object literal carries the prelude `Object` interface's members
            // (`toJson`, …) beside its own fields, so a miss on the field map is
            // not yet a miss on the receiver.
            Type::Object { fields, index } => {
                if let Some(f) = fields.get(&name.name) {
                    let ty = if f.optional {
                        Type::union(vec![f.ty.clone(), Type::Undefined])
                    } else {
                        f.ty.clone()
                    };
                    return ChainField::plain(ty);
                }
                if let Some(index) = index {
                    return ChainField::plain(index.read_ty());
                }
                if let Some(found) = self.chain_method_lookup(receiver_ty, name, span) {
                    return found;
                }
                self.report_missing_object_field(span, receiver_ty, &name.name);
                ChainField::plain(Type::Error)
            }
            Type::Error => ChainField::plain(Type::Error),
            Type::Unknown => ChainField::plain(Type::Unknown),
            // A union reads the same way it does off a chain; `union_field_read_ty`
            // owns the rule, and this arm exists so `u?.v` and `u.v` agree.
            Type::Union(members) if members.iter().all(Self::is_field_bearing) => {
                let ty =
                    self.union_field_read_ty(span, receiver_path, receiver_ty, members, &name.name);
                ChainField::plain(ty)
            }
            // Class receivers resolve against the class field map before the
            // interface/method attempts below — `lookup_interface_property`
            // rejects a class outright and `find_method` only covers methods,
            // so without this a `?.` on a class field reports it as missing.
            // Same authority as `infer_property_access`, so the same fields are
            // visible (inherited, generic-substituted, module-scoped privacy).
            Type::ClassRef { mangled, args, .. } => {
                let mangled = mangled.clone();
                let class_args = args.clone();
                if let Some(read_ty) = self.class_field_read_ty(&mangled, &class_args, name) {
                    return ChainField::plain(read_ty);
                }
                // Statics after instance members, for the reason
                // `infer_property_access`'s `ClassRef` arm spells out.
                if let Some(found) = self.chain_method_lookup(receiver_ty, name, span) {
                    return found;
                }
                if self.report_static_on_instance(receiver_ty, &mangled, name) {
                    return ChainField::plain(Type::Error);
                }
                self.report_missing_field(span, receiver_ty, &name.name);
                ChainField::plain(Type::Error)
            }
            // interface receivers — mirror
            // `InterfacePropertyAccess`'s `find_property` lookup. Returns
            // the iface mangled name so the chain part lifts to
            // `InterfaceProperty`. If the name doesn't resolve as a
            // property, try `find_method` so chains like `s?.toUpperCase()`
            // get a function-typed `InterfaceProperty` step that
            // [`infer_chain_part`]'s `Call` branch can lift to
            // `MethodCall`.
            _ => {
                if let Some((prop_sig, bindings, iface_mangled, dispatch)) =
                    self.lookup_interface_property(receiver_ty, &name.name)
                {
                    let resolved_ty = if bindings.is_empty() {
                        prop_sig.ty
                    } else {
                        super::generic::substitute_or_record(
                            &prop_sig.ty,
                            &bindings,
                            &self.type_limits,
                        )
                    };
                    if dispatch == crate::Dispatch::VTable {
                        let read_ty = if prop_sig.optional {
                            Type::union(vec![resolved_ty, Type::Undefined])
                        } else {
                            resolved_ty
                        };
                        return ChainField::plain(read_ty);
                    }
                    return ChainField::property(resolved_ty, iface_mangled);
                }
                if let Some(found) = self.chain_method_lookup(receiver_ty, name, span) {
                    return found;
                }
                if let Some(index) = self.resolver().index_signature(receiver_ty) {
                    return ChainField::plain(index.read_ty());
                }
                self.report_missing_field(span, receiver_ty, &name.name);
                ChainField::plain(Type::Error)
            }
        }
    }

    /// The name resolved as a method on `receiver_ty`, in the form a chain step
    /// takes. Every receiver kind tries this after its own member map, so a
    /// method never reports as a missing field.
    fn chain_method_lookup(
        &mut self,
        receiver_ty: &Type,
        name: &Ident,
        span: Span,
    ) -> Option<ChainField> {
        let (method_sig, bindings, iface_mangled, _dispatch) =
            self.find_method(receiver_ty, &name.name)?;
        Some(self.chain_method_field(
            receiver_ty,
            method_sig,
            &bindings,
            iface_mangled,
            name,
            span,
        ))
    }

    /// A step whose path a guard has already narrowed yields the narrowed type,
    /// admitting what the same `receiver.field` admits outside a chain. Rewrites
    /// the step in place so the next step's receiver follows. `result_path` is
    /// the path *including* this step — the referent being read.
    ///
    /// The two paths can still disagree on the *value*: outside a chain the read
    /// is rewritten to the guard's shadow local, while a step re-reads the slot.
    /// Where a narrowing has gone stale — a call, a loop back edge — the shadow
    /// holds what the guard saw and the step sees what is there now.
    ///
    /// A method step is skipped: its function type is not something the narrowing
    /// store keys, and rewriting it would strand the `Call` step that consumes it.
    ///
    /// Literal index steps consume the same path narrowing as ordinary element
    /// reads. Computed indices have no reference path and remain conservative.
    ///
    /// A step a `!` follows (`asserted`) keeps its declared type where a guard
    /// left it only `null` or `undefined`, as a reference under `!` does
    /// outside a chain.
    fn narrow_step_result(
        &self,
        result_path: Option<&super::narrowing::ReferencePath>,
        pending_method: &Option<ChainMethod>,
        asserted: bool,
        part: &mut TypedChainPart,
        step_ty: Type,
    ) -> Type {
        if pending_method.is_some() {
            return step_ty;
        }
        let Some(view) = result_path.and_then(|p| self.lookup_narrowed_view(p)) else {
            return step_ty;
        };
        if asserted && is_nullish_only(&view.narrowed_ty) {
            return step_ty;
        }
        let narrowed = view.narrowed_ty.clone();
        part.set_result_ty(narrowed.clone());
        narrowed
    }

    /// Extends the chain's reference path by one step, keying the field-path
    /// narrowings a step may read at.
    ///
    /// A call has no path form at all, and a computed index has none we can key
    /// a narrowing on; both drop the path, so the steps after them read their
    /// declared types. A literal index extends the path.
    ///
    /// `!` steps never reach here; [`infer_chain_steps`] handles them before it
    /// dispatches. Its arm records the rule the exhaustive match needs anyway:
    /// `!` asserts the referent, it does not move to a new one.
    fn extend_chain_path(
        &self,
        path: Option<super::narrowing::ReferencePath>,
        part: &TypedChainPart,
    ) -> Result<Option<super::narrowing::ReferencePath>, crate::compiler_error::CompilerFailure>
    {
        let Some(mut path) = path else {
            return Ok(None);
        };
        Ok(match part {
            TypedChainPart::Field { name, .. } | TypedChainPart::InterfaceProperty { name, .. } => {
                path.chain
                    .push(super::narrowing::PathElem::Field(name.name.clone()));
                Some(path)
            }
            TypedChainPart::Index { idx, .. } => {
                let Some(element) = self.index_path_elem(*idx)? else {
                    return Ok(None);
                };
                path.chain.push(element);
                Some(path)
            }
            TypedChainPart::NonNull { .. } => Some(path),
            TypedChainPart::Call { .. } | TypedChainPart::MethodCall { .. } => None,
        })
    }

    /// A method resolved in chain position: its function type plus the owner's
    /// mangled name, so [`infer_chain_part`]'s `Call` branch can lift the step
    /// to a `MethodCall`, plus the substituted signature so that branch can
    /// bind the call's arguments to it.
    ///
    /// A method with method-level generics gets an `Error` field type and no
    /// owner, and carries its `ChainMethod` anyway: which diagnostic it earns
    /// depends on whether a `Call` follows, which only the driver knows. A bare
    /// reference is permanently illegal and takes
    /// [`reject_chain_method_reference`]; the call form is the one that is
    /// merely unimplemented, and the `Call` branch reports it.
    fn chain_method_field(
        &mut self,
        receiver_ty: &Type,
        method_sig: crate::MethodSig,
        bindings: &std::collections::BTreeMap<String, Type>,
        owner_mangled: crate::MangledName,
        name: &Ident,
        span: Span,
    ) -> ChainField {
        let params: Vec<crate::Param> = method_sig
            .params
            .iter()
            .map(|p| crate::Param {
                ty: super::generic::substitute_or_record(&p.ty, bindings, &self.type_limits),
                ..p.clone()
            })
            .collect();
        // The `Error` field type is load-bearing beyond poisoning the step: it
        // also keeps the `Call` branch off the `InterfaceProperty` lift, which
        // cannot represent an un-bound method-level generic.
        let (ty, iface) = if method_sig.generics.is_empty() {
            let ret =
                super::generic::substitute_or_record(&method_sig.ret, bindings, &self.type_limits);
            let has_rest = params.last().is_some_and(|p| p.rest);
            let fn_ty = Type::Function {
                params: params.iter().map(callable_parameter_type).collect(),
                ret: Box::new(ret),
                predicate: None,
                has_rest,
                optional: crate::package_declaration::optional_parameter_count(&params),
            };
            (fn_ty, Some(owner_mangled))
        } else {
            (Type::Error, None)
        };
        ChainField {
            ty,
            iface,
            method: Some(ChainMethod {
                receiver_ty: receiver_ty.clone(),
                sig: method_sig,
                params,
                name: name.name.clone(),
                span,
            }),
        }
    }

    /// Whether `x as T` would compile for an `x` of type `source`, asked exactly
    /// as [`infer_as`](Self::infer_as) asks it — so a diagnostic offering a cast
    /// can neither name a target the cast rejects nor withhold one it accepts.
    ///
    /// Both halves matter. A proven upcast emits no runtime test, so it does not
    /// need a runtime-verifiable target: a method-bearing or recursive interface
    /// is an illegal *check* target and still a legal cast from a source already
    /// assignable to it. Otherwise the target is reduced to its structural shape
    /// and put to the same predicate `infer_as` uses.
    pub(super) fn is_legal_cast_target(&self, source: &Type, target: &Type) -> bool {
        let shape = self.reduce_interfaces_to_shapes(target);
        if super::assignable::assignable(source, &shape, self.resolver()) {
            return true;
        }
        unsupported_cast_target_reason(&shape, self.resolver(), &mut Vec::new()).is_none()
    }

    /// typecheck `x as T`. Resolves the target, infers the operand, validates the static
    /// relationship, and decides the runtime check:
    ///
    /// - Relatedness: one assignable direction must hold, also considering the source
    ///   with literals widened as TypeScript does. Interfaces use their structural shape.
    /// - `as` is the language's runtime-validation boundary. When the source is **not** a
    ///   static subtype of the target (`unknown`, downcasts), emit a deep structural check
    ///   (`Cast.check = Some(shape)`); codegen verifies fields/elements/literals and throws
    ///   on mismatch. A statically-proven upcast carries `check = None` (repr-only narrow).
    ///
    /// `check`'s shape has all interfaces reduced to their structural data form, so codegen
    /// walks plain object/array/primitive types and never needs interface knowledge.
    fn infer_as(
        &mut self,
        inner: ExprId,
        ty: TypeAnnotation,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let target_ty = self.resolve_type(&ty)?;
        // An empty `[]` has no element type of its own, so it takes the target's
        // array element type, as under an annotation, also as a ternary branch or
        // nested in an array literal. Other operands infer unhinted: a hint is
        // enforced (an object literal rejects fields the target lacks), while a
        // cast only needs one type assignable to the other.
        let operand_hint = if holds_empty_array_literal(self.ast, inner)? {
            empty_array_cast_hint(&target_ty)
        } else {
            None
        };
        let (inner_id, inner_ty) = self.infer_expr(inner, operand_hint)?;
        // Error escape — already in error state; produce a Cast so
        // downstream passes see a sensible node, but don't emit more
        // diagnostics on top.
        if matches!(target_ty.peel(), Type::Error) || matches!(inner_ty.peel(), Type::Error) {
            return Ok((
                TypedExprKind::Cast {
                    value: inner_id,
                    target_ty: target_ty.clone(),
                    check: None,
                },
                target_ty,
            ));
        }
        // `assignable` is nominal for `InterfaceRef`; relate (and later check) against the
        // interface's structural data shape so `unknown`/structurally-compatible sources pass.
        let shape = self.reduce_interfaces_to_shapes(&target_ty);
        let inner_to_target = assignable(&inner_ty, &shape, self.resolver());
        let target_to_inner = assignable(&shape, &inner_ty, self.resolver());
        let target_to_widened =
            assignable(&shape, &widen_assertion_source(&inner_ty), self.resolver());
        if !inner_to_target
            && !target_to_inner
            && !target_to_widened
            && !self.union_members_overlap(&inner_ty, &shape)
        {
            let blockers = optional_vs_required_blockers(&inner_ty, &shape, self.resolver());
            if let Some(first) = blockers.first() {
                let (subj, verb) = if blockers.len() == 1 {
                    ("field", "is")
                } else {
                    ("fields", "are")
                };
                let list = blockers
                    .iter()
                    .map(|f| format!("`{f}`"))
                    .collect::<Vec<_>>()
                    .join(", ");
                self.error_with_help(
                    span,
                    format!(
                        "cannot cast `{inner_ty}` to `{target_ty}`: {subj} {list} {verb} \
                         optional on the source but required on the target"
                    ),
                    vec![format!(
                        "you don't need a cast — use the value directly and narrow the \
                         optional field before access, e.g. `if (x.{first} !== null)` or \
                         `x.{first}!`"
                    )],
                );
                return Ok((TypedExprKind::Null, Type::Error));
            }
            self.error_with_help(
                span,
                format!(
                    "cannot cast `{inner_ty}` to `{target_ty}`: no assignable direction \
                     between these types"
                ),
                vec![format!(
                    "re-check the target — a typed value is usually usable directly. For a \
                     deliberate dynamic reinterpretation, cast through `unknown`: \
                     `x as unknown as {target_ty}`"
                )],
            );
            return Ok((TypedExprKind::Null, Type::Error));
        }
        // Deep check only when the source isn't a proven subtype of the target.
        // A proven upcast emits no runtime test, so it doesn't need the target
        // to be runtime-verifiable — `m as Map<K, V>` on an `m` that already is
        // one must compile even though a `Map` can't be structurally checked.
        let check = if inner_to_target {
            None
        } else {
            let shape = self.reduce_enums_to_members(&shape);
            if let Some(reason) =
                unsupported_cast_target_reason(&shape, self.resolver(), &mut Vec::new())
            {
                self.error_with_help(
                    span,
                    format!("`as` to `{target_ty}` is not yet supported: {reason}"),
                    vec![
                        "supported targets: primitives (`number`, `string`, `boolean`, \
                         `null`), `bigint`, arrays, tuples, `Uint8Array`, object shapes \
                         (`{ a: T }`), interfaces, closures, `unknown`, and unions of these"
                            .to_string(),
                    ],
                );
                return Ok((TypedExprKind::Null, Type::Error));
            }
            Some(Box::new(shape))
        };
        Ok((
            TypedExprKind::Cast {
                value: inner_id,
                target_ty: target_ty.clone(),
                check,
            },
            target_ty,
        ))
    }

    /// Whether some member of `source` and some member of `target` pass one of the
    /// assertion directions [`infer_as`](Self::infer_as) asks of the whole types.
    /// This is tsc's comparability for a union on either side, at the top level
    /// only (a union inside a field or an element still needs a whole-type match):
    /// `str as S[] | S` is accepted for `type S = "a" | "b"` because `string`
    /// overlaps `S`, and `(number | boolean) as string | number` because `number`
    /// overlaps `number`.
    fn union_members_overlap(&self, source: &Type, target: &Type) -> bool {
        if !matches!(source.peel(), Type::Union(_)) && !matches!(target.peel(), Type::Union(_)) {
            return false;
        }
        // An already-reported error inside the source (an empty `[]` with no
        // element type) relates to anything, so it can't show an overlap.
        if has_error_component(source) {
            return false;
        }
        let resolver = self.resolver();
        let target_members = narrowing::union_members(target);
        narrowing::union_members(source)
            .into_iter()
            .any(|source_member| {
                let widened = widen_assertion_source(source_member);
                target_members.iter().any(|target_member| {
                    assignable(source_member, target_member, resolver)
                        || assignable(target_member, source_member, resolver)
                        || assignable(target_member, &widened, resolver)
                })
            })
    }

    /// `x instanceof Foo` — a runtime class test. `Foo` must name a class (interfaces aren't
    /// runtime types in v1), and `x`'s static type must be related to `Foo` by subtyping in
    /// either direction; an unrelated pair is an always-false test and a hard error. Lowers
    /// to the nominal vtable-identity walk (`emit_nominal_instance_test`) — shape can't
    /// carry the answer, same-shape classes canonicalize together — and feeds the
    /// narrowing engine.
    fn infer_instanceof(
        &mut self,
        value: ExprId,
        ty: TypeAnnotation,
        span: Span,
    ) -> Result<(TypedExprKind, Type), CompilerFailure> {
        let class_ty = self.resolve_runtime_class_test(&ty)?;
        let (value_id, value_ty) = self.infer_expr(value, None)?;

        // Already in an error state (unknown type name or bad operand) — produce a node so
        // downstream passes stay happy, but don't pile on diagnostics.
        if matches!(class_ty.peel(), Type::Error) || matches!(value_ty.peel(), Type::Error) {
            return Ok((
                TypedExprKind::InstanceOf {
                    value: value_id,
                    class: class_ty,
                },
                Type::Boolean,
            ));
        }

        // `Uint8Array` keeps its own type variant rather than becoming a class
        // the way Map/Set did — the variant carries byte-array semantics across
        // a dozen typechecker sites. It still tests soundly: `$Uint8Array` is
        // canonically unique, so codegen reaches it with the structural
        // `ref.test` that `is`/`as` already use.
        if !matches!(class_ty.peel(), Type::ClassRef { .. } | Type::Uint8Array) {
            self.error_with_help(
                ty.span,
                format!(
                    "`instanceof` requires a class on the right-hand side, but `{class_ty}` is not a class",
                ),
                vec![
                    "interfaces aren't runtime types in v1 — test against a class".to_string(),
                ],
            );
            return Ok((
                TypedExprKind::InstanceOf {
                    value: value_id,
                    class: Type::Error,
                },
                Type::Boolean,
            ));
        }

        let class_ty = self.refine_class_test_target(&class_ty, &value_ty);
        // Relatedness is per-member on both sides: `x: Box<number> | string`
        // can still be a `Sub<number>`, and the test may narrow to any of
        // several instantiations. Requiring every pairing would wrongly call
        // that always-false.
        //
        // A target parameter the operand didn't determine probes as a
        // wildcard rather than as `unknown`: `Shaped` (an interface) can hold
        // some `Box<T>`, and `unknown` would compare against the interface's
        // concrete member types and say otherwise. A genuinely impossible
        // pair — `Box<number>` against `StrBox extends Box<string>` — has no
        // undetermined parameters and is still caught.
        let probes: Vec<Type> = class_members(&class_ty)
            .iter()
            .map(wildcard_undetermined_args)
            .collect();
        let related = class_members(&value_ty).iter().any(|m| {
            probes
                .iter()
                .any(|t| assignable(m, t, self.resolver()) || assignable(t, m, self.resolver()))
        });
        if !related && !super::narrowing::has_erased_member(&value_ty) {
            self.error_with_help(
                span,
                format!(
                    "`{value_ty} instanceof {class_ty}` is always false: the types are not related",
                ),
                vec![format!(
                    "`{value_ty}` can never be an instance of `{class_ty}` — widen to \
                     `unknown` first if a dynamic test is intended",
                )],
            );
            return Ok((
                TypedExprKind::InstanceOf {
                    value: value_id,
                    class: Type::Error,
                },
                Type::Boolean,
            ));
        }

        Ok((
            TypedExprKind::InstanceOf {
                value: value_id,
                class: class_ty,
            },
            Type::Boolean,
        ))
    }

    /// Resolve an annotation used as a **runtime class test** — the RHS of
    /// `instanceof`, or a `catch` clause's type. The runtime check is the
    /// nominal vtable-identity walk, which cannot see type arguments, so a
    /// generic class is written bare and narrows at `unknown` args (the
    /// `Array.isArray` precedent).
    ///
    /// Explicit arguments are rejected however they are spelled: directly,
    /// through a namespace, or behind an alias. Accepting them would narrow a
    /// value to an instantiation the test never checked.
    pub(super) fn resolve_runtime_class_test(
        &mut self,
        ty: &TypeAnnotation,
    ) -> Result<Type, CompilerFailure> {
        // The bare form is resolved first because `resolve_class_reference`
        // would reject its arity before this function saw it.
        if let Some((package, name, mangled, arity)) = self.bare_generic_class_target(ty) {
            return Ok(Type::class_ref(
                package,
                name,
                mangled,
                vec![Type::Unknown; arity],
            ));
        }
        let resolved = self.resolve_type(ty)?;
        let Type::ClassRef { args, .. } = resolved.peel() else {
            return Ok(resolved);
        };
        if args.iter().all(|a| matches!(a, Type::Unknown)) {
            return Ok(resolved);
        }
        // Report the spelling the source used — the class's own name may not
        // even be in scope here (`ns.Box`), and behind an alias it never
        // appears on the line at all.
        let Type::ClassRef { name, .. } = resolved.peel() else {
            return Ok(resolved);
        };
        let class_name = name.clone();
        let spelled = self
            .annotation_type_name(ty)
            .unwrap_or_else(|| class_name.clone());
        // `ns.Box` is already the testable spelling; an alias is not, so point
        // at the class it names.
        let bare = if spelled == class_name || spelled.ends_with(&format!(".{class_name}")) {
            spelled.clone()
        } else {
            class_name
        };
        let erased = args
            .iter()
            .map(|_| "unknown")
            .collect::<Vec<_>>()
            .join(", ");
        let help = if bare == spelled {
            format!(
                "type arguments are erased at runtime — test the class itself: \
                 `{bare}` (the value narrows to `{bare}<{erased}>`)"
            )
        } else {
            format!(
                "`{spelled}` names one instantiation, and type arguments are erased at \
                 runtime — test the class itself: `{bare}` (the value narrows to \
                 `{bare}<{erased}>`)"
            )
        };
        self.error_with_help(
            ty.span,
            format!("`{spelled}` cannot be tested at a specific instantiation"),
            vec![help],
        );
        Ok(Type::Error)
    }

    /// Bind a runtime class test's erased type arguments from the operand.
    ///
    /// `x instanceof Sub` resolves `Sub` at `unknown` args because the runtime
    /// walk carries none. When `x` is already a `Box<number>` and `Sub<T>`
    /// extends `Box<T>`, though, a successful test proves `Sub<number>` — so
    /// solve the target's parameters against the operand rather than narrowing
    /// to an unrelated `Sub<unknown>`, which relates to nothing and drops the
    /// narrowing entirely.
    fn refine_class_test_target(&self, target: &Type, operand: &Type) -> Type {
        let Type::ClassRef { args, .. } = target.peel() else {
            return target.clone();
        };
        if args.is_empty() || !args.iter().all(|a| matches!(a, Type::Unknown)) {
            return target.clone();
        }
        // Only refine when every union member the target could descend from
        // agrees on the instantiation. Picking one of several would claim
        // something the runtime tag never proved — and because same-shape
        // classes canonicalize to one WasmGC type, reading a value at the
        // wrong type would not even trap. Disagreement leaves the arguments
        // erased, which stays sound and narrows to `unknown` members.
        let members = class_members(operand);
        let refined: Vec<Type> = members
            .iter()
            .filter_map(|m| self.solve_class_test_target(target, m))
            .collect();
        match refined.split_first() {
            Some((first, rest)) if rest.iter().all(|r| r == first) => first.clone(),
            _ => target.clone(),
        }
    }

    /// Solve `target`'s type parameters so that its `extends` chain reaches
    /// `operand`'s class at `operand`'s arguments. `None` when `operand` is not
    /// a class the target descends from.
    fn solve_class_test_target(&self, target: &Type, operand: &Type) -> Option<Type> {
        use crate::typechecker::type_param_substitution::TypeParamSubstitution;

        let Type::ClassRef {
            mangled: target_mangled,
            package,
            name,
            ..
        } = target.peel()
        else {
            return None;
        };
        let Type::ClassRef {
            mangled: operand_mangled,
            args: operand_args,
            ..
        } = operand.peel()
        else {
            return None;
        };
        let crate::TypeKind::Class { generics, .. } = &self
            .lookup_structural_type(target_mangled, name)
            .map(|s| &s.kind)?
        else {
            return None;
        };
        let identity: Vec<Type> = generics.iter().map(|g| Type::TypeVar(g.clone())).collect();
        // The args the target's own parameters take on where its chain reaches
        // the operand's class — `[T]` for `Sub<T> extends Box<T>`.
        let at_operand =
            self.resolver()
                .class_args_at_ancestor(target_mangled, &identity, operand_mangled)?;
        let mut sub = TypeParamSubstitution::new();
        for (from_target, actual) in at_operand.iter().zip(operand_args) {
            let _ = sub.unify(from_target, actual, self.resolver());
        }
        let solved: Vec<Type> = identity
            .iter()
            .map(|t| {
                let applied = sub.apply_or_record(t, &self.type_limits);
                // A parameter the operand doesn't constrain stays erased.
                if type_contains_type_var(&applied) {
                    Type::Unknown
                } else {
                    applied
                }
            })
            .collect();
        Some(Type::class_ref(
            package.clone(),
            name.clone(),
            target_mangled.clone(),
            solved,
        ))
    }

    /// How the source spelled a type annotation's name: `Box`, or the dotted
    /// `ns.Box`. Type arguments are a separate part of the annotation and are
    /// not included.
    pub(super) fn annotation_type_name(&self, annot: &TypeAnnotation) -> Option<String> {
        match &annot.kind {
            crate::TypeAnnotationKind::Name { name, .. } => Some(name.name.clone()),
            crate::TypeAnnotationKind::Qualified { path, .. } => Some(
                path.iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<&str>>()
                    .join("."),
            ),
            _ => None,
        }
    }

    /// A bare (argument-less) mention of a generic class, spelled either
    /// directly or through a namespace import. `None` for anything else,
    /// including an alias — an alias names an instantiation, so it must go
    /// through the normal resolver and be rejected there.
    fn bare_generic_class_target(
        &mut self,
        ty: &TypeAnnotation,
    ) -> Option<(crate::Package, String, crate::MangledName, usize)> {
        let generic_class = |sym: &crate::TypeSymbol| match &sym.kind {
            crate::TypeKind::Class { generics, .. } if !generics.is_empty() => {
                Some((sym.mangled_name.clone(), generics.len()))
            }
            _ => None,
        };
        match &ty.kind {
            crate::TypeAnnotationKind::Name { name, args } if args.is_empty() => {
                let text = name.name.clone();
                // A type parameter shadows a class of the same name, exactly as
                // it does in `resolve_type`.
                if self.lookup_body_gp(&text).is_some() || self.is_generic_in_scope(&text) {
                    return None;
                }
                let (mangled, arity) = self.lookup_named_type(&text).and_then(generic_class)?;
                let package = self.type_package(&text);
                Some((package, text, mangled, arity))
            }
            crate::TypeAnnotationKind::Qualified { path, args } if args.is_empty() => {
                let (root_name, rest) = path.split_first()?;
                let root = root_name.name.as_str();
                let ns = self.namespace_bindings.get(root)?;
                let member = rest
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<&str>>()
                    .join(".");
                let package = crate::Package(ns.members.package_name().to_string());
                let (mangled, arity) = ns.members.type_symbol(&member).and_then(generic_class)?;
                let display: String = path
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<&str>>()
                    .join(".");
                Some((package, display, mangled, arity))
            }
            _ => None,
        }
    }

    /// Recursively replace every **data-only** `InterfaceRef` in `ty` with its structural
    /// shape (`Type::Object` of the interface's properties). Method-bearing interfaces
    /// (`Map`, `Iterator`, …) are nominal — a structural check can't verify their vtable —
    /// so they stay `InterfaceRef` and relate nominally instead. Recurses through object
    /// fields, arrays, tuples, and unions. `seen` guards against recursive/mutually-recursive
    /// interfaces: a re-encountered interface is left as `InterfaceRef`. Leftover
    /// `InterfaceRef`s are rejected by `unsupported_cast_target_reason` when a runtime
    /// check is actually needed.
    pub(super) fn reduce_interfaces_to_shapes(&self, ty: &Type) -> Type {
        let mut budget = self.type_limits.budget();
        self.type_limits.type_or_error(self.reduce_interfaces_rec(
            ty,
            &mut Vec::new(),
            1,
            &mut budget,
        ))
    }

    /// [`reduce_interfaces_to_shapes`](Self::reduce_interfaces_to_shapes) for
    /// the node at `depth` of the result. Expanding a reference inlines the
    /// interface, so a chain of interfaces becomes a type as deep as the chain;
    /// it builds under `budget` like any substitution.
    fn reduce_interfaces_rec(
        &self,
        ty: &Type,
        seen: &mut Vec<String>,
        depth: u32,
        budget: &mut TypeBudget<'_>,
    ) -> Result<Type, TypeTooLarge> {
        let child = depth.saturating_add(1);
        match ty.peel_preserving_readonly() {
            Type::InterfaceRef {
                mangled,
                name,
                args,
                ..
            } => {
                let data_shape = if seen.iter().any(|n| n == name) {
                    None
                } else {
                    self.interface_data_shape(mangled, name, args)
                };
                let Some(fields) = data_shape else {
                    budget.charge_copy(ty.peel(), depth)?;
                    return Ok(ty.peel().clone());
                };
                budget.charge(depth)?;
                seen.push(name.clone());
                let reduced = fields
                    .into_iter()
                    .map(|(k, f)| {
                        Ok((
                            k,
                            crate::ObjectField {
                                ty: self.reduce_interfaces_rec(&f.ty, seen, child, budget)?,
                                optional: f.optional,
                                readonly: f.readonly,
                                method: f.method,
                            },
                        ))
                    })
                    .collect::<Result<_, TypeTooLarge>>()?;
                let index = self
                    .resolver()
                    .index_signature(ty)
                    .map(|i| {
                        i.try_map_value(|value| {
                            self.reduce_interfaces_rec(value, seen, child, budget)
                        })
                    })
                    .transpose()?;
                seen.pop();
                Ok(Type::Object {
                    index,
                    fields: reduced,
                })
            }
            peeled @ (Type::Object { .. }
            | Type::Array(_)
            | Type::Readonly(_)
            | Type::Tuple(_)
            | Type::Union(_)) => {
                budget.charge(depth)?;
                map_children(peeled, |inner| {
                    self.reduce_interfaces_rec(inner, seen, child, budget)
                })
            }
            other => {
                budget.charge_copy(other, depth)?;
                Ok(other.clone())
            }
        }
    }

    /// Replace every enum in a cast's runtime check with the union of its
    /// variant values: a value is one of the enum's members exactly when it
    /// equals one of them. Relatedness is decided before this, against the
    /// enum itself, because a member literal is not assignable to its enum.
    fn reduce_enums_to_members(&self, ty: &Type) -> Type {
        let peeled = ty.peel_preserving_readonly();
        if let Some(members) = self.enum_runtime_members(peeled) {
            return members;
        }
        if !matches!(
            peeled,
            Type::Object { .. }
                | Type::Array(_)
                | Type::Readonly(_)
                | Type::Tuple(_)
                | Type::Union(_)
        ) {
            return ty.clone();
        }
        crate::type_size::map_children_infallible(peeled, |inner| {
            self.reduce_enums_to_members(inner)
        })
    }

    /// regex literal inference. Runs the JS→regex-crate
    /// translator (`runtime::prelude::regex::engine::translate_js_pattern`) and the
    /// underlying `RegexBuilder::new` call at compile time so
    /// unsupported features (lookarounds, backreferences) and
    /// malformed patterns surface as `Diagnostic`s with source
    /// caret, not runtime traps — matches AGENTS.md "LLM-native
    /// errors" §1 + §3 (always show source context; name the fix).
    ///
    /// On success the type currently resolves to `Type::Error` as a
    /// placeholder; PR 4 wires the `RegExp` prelude
    /// interface and codegen lowering, at which point this returns
    /// `Type::Named("RegExp")` and a `TypedExprKind::Regex` variant.
    fn infer_regex(&mut self, source: String, flags: String, span: Span) -> (TypedExprKind, Type) {
        // validator (translator + `RegexBuilder::new`) runs
        // at compile time, so lookarounds / backreferences /
        // malformed patterns surface as `Diagnostic`s with source
        // caret + a self-contained `help:` block explaining the
        // Submilli subset and the rewrite path. Per AGENTS.md
        // "LLM-native errors" §1 + §3: the help is enough for an
        // LLM to fix the regex in one shot without any external
        // reference.
        match crate::runtime::prelude::regex::engine::build_regex(&source, &flags) {
            Ok(_) => (
                TypedExprKind::Regex { source, flags },
                Type::prelude_interface("RegExp", Vec::new()),
            ),
            Err(e) => {
                let help = regex_error_help(&e);
                self.error_with_help(span, e.to_string(), help);
                (TypedExprKind::Null, Type::Error)
            }
        }
    }
}

/// return `Some(reason)` when `target_ty` is a cast target
/// the runtime emission can't yet discriminate against, or
/// `None` when the cast is emittable. Peels aliases. Recurses into
/// unions — every member must be supported.
/// per-variant help for regex-translation errors. Built so
/// an LLM (the primary consumer of compile diagnostics — see
/// AGENTS.md "LLM-native errors") can fix the regex in one shot
/// without any external documentation reference.
///
/// Each variant returns a multi-line `help:` block that:
/// - states the constraint
/// - gives a concrete rewrite example where one exists
/// - lists the supported feature set so the fix doesn't drift into
///   another unsupported corner
fn regex_error_help(e: &crate::runtime::prelude::regex::engine::TranslateError) -> Vec<String> {
    use crate::runtime::prelude::regex::engine::TranslateError as E;
    match e {
        E::Lookahead => vec![
            "the Submilli regex engine uses linear-time matching (Rust `regex` crate) \
             and does not support lookahead. Rewrite by capturing the following text \
             explicitly and checking it after the match — e.g. instead of \
             `\\d+(?=px)`, use `(\\d+)px` and read capture group 1."
                .to_string(),
            "supported regex features: literal characters, character classes \
             (`[a-z]`, `[^...]`), `\\d`/`\\w`/`\\s` (ASCII without `u` flag, Unicode \
             with), anchors (`^`, `$`, `\\b`), alternation (`a|b`), quantifiers \
             (`*`, `+`, `?`, `{n,m}`), non-capturing groups (`(?:...)`), named \
             capture groups (`(?<name>...)`), and flags `g`/`i`/`m`/`s`/`u`/`y`."
                .to_string(),
        ],
        E::Lookbehind => vec![
            "the Submilli regex engine uses linear-time matching (Rust `regex` crate) \
             and does not support lookbehind. Rewrite to match the prefix as part of \
             the pattern with a capture group, then use only the capture — e.g. \
             instead of `(?<=\\$)\\d+`, use `\\$(\\d+)` and read capture group 1."
                .to_string(),
            "supported regex features: literal characters, character classes \
             (`[a-z]`, `[^...]`), `\\d`/`\\w`/`\\s` (ASCII without `u` flag, Unicode \
             with), anchors (`^`, `$`, `\\b`), alternation (`a|b`), quantifiers \
             (`*`, `+`, `?`, `{n,m}`), non-capturing groups (`(?:...)`), named \
             capture groups (`(?<name>...)`), and flags `g`/`i`/`m`/`s`/`u`/`y`."
                .to_string(),
        ],
        E::Backreference => vec![
            "the Submilli regex engine does not support backreferences (`\\1`, \
             `\\k<name>`) — they would force exponential-time matching. Restructure \
             the pattern so it does not need to re-match the same captured text, or \
             do the equality check in code after running `exec` (compare \
             `m.groups[0]` with `m.groups[1]` etc.)."
                .to_string(),
            "supported regex features: literal characters, character classes, \
             `\\d`/`\\w`/`\\s`, anchors (`^`, `$`, `\\b`), alternation, quantifiers, \
             non-capturing groups (`(?:...)`), named capture groups (`(?<name>...)`), \
             and flags `g`/`i`/`m`/`s`/`u`/`y`."
                .to_string(),
        ],
        E::InvalidFlag(c) => vec![
            format!(
                "valid flags: `g` (global / stateful `lastIndex`), `i` \
                 (case-insensitive), `m` (multiline — `^`/`$` match line boundaries), \
                 `s` (dot-all — `.` matches newlines), `u` (Unicode — \
                 `\\d`/`\\w`/`\\s` are Unicode classes), `y` (sticky — anchor at \
                 `lastIndex`). `{c}` is none of these.",
            ),
            "note: Submilli does not support the ES2022 `d` (hasIndices) flag.".to_string(),
        ],
        E::DuplicateFlag(c) => vec![format!(
            "remove the duplicate `{c}` — each flag may appear at most once."
        )],
        E::InvalidPattern(_) => vec![
            "the message above is from the underlying regex engine (Rust `regex` \
             crate, linear-time). Common causes: unbalanced parens, malformed \
             quantifier, unterminated character class."
                .to_string(),
            "supported regex features: literal characters, character classes \
             (`[a-z]`, `[^...]`), `\\d`/`\\w`/`\\s` (ASCII without `u` flag, Unicode \
             with), anchors (`^`, `$`, `\\b`), alternation (`a|b`), quantifiers \
             (`*`, `+`, `?`, `{n,m}`), non-capturing groups (`(?:...)`), named \
             capture groups (`(?<name>...)`), and flags `g`/`i`/`m`/`s`/`u`/`y`. \
             Lookarounds and backreferences are NOT supported."
                .to_string(),
        ],
    }
}

/// Explains a rejected `as` whose two types are *almost* related: the source would satisfy
/// the target but for fields that are optional on the source and required on the target
/// (the common "`x as Subset`" over an MCP result with `foo?` fields). Returns those field
/// names so the diagnostic can say "narrow, don't cast". Empty when optionality isn't the
/// sole blocker — a missing field or an incompatible field type makes the two genuinely
/// unrelated, and the generic message applies. Peels matching array layers so `T[] as U[]`
/// is judged by its element types.
fn optional_vs_required_blockers(
    source: &Type,
    target: &Type,
    types: super::assignable::TypeResolver,
) -> Vec<String> {
    let (mut s, mut t) = (source, target);
    while let (Type::Array(se), Type::Array(te)) = (s, t) {
        s = &**se;
        t = &**te;
    }
    let (
        Type::Object {
            fields: s_fields, ..
        },
        Type::Object {
            fields: t_fields, ..
        },
    ) = (s, t)
    else {
        return Vec::new();
    };
    let mut blockers = Vec::new();
    for (name, t_field) in t_fields {
        let Some(s_field) = s_fields.get(name) else {
            return Vec::new();
        };
        if !assignable(&s_field.ty, &t_field.ty, types) {
            return Vec::new();
        }
        if s_field.optional && !t_field.optional {
            blockers.push(name.clone());
        }
    }
    blockers
}

/// Recurses the (interface-reduced) cast-target shape so the compile-time gate matches
/// exactly what `emit_structural_test` can verify at runtime. A leftover `InterfaceRef`
/// here means an interface `reduce_interfaces_to_shapes` could not expand: either
/// method-bearing (nominal) or recursive/mutually-recursive.
fn unsupported_cast_target_reason(
    target_ty: &Type,
    types: super::assignable::TypeResolver,
    seen: &mut Vec<Type>,
) -> Option<&'static str> {
    let peeled = target_ty.peel();
    match peeled {
        Type::Number
        | Type::NumberLiteral(_)
        | Type::BigInt
        | Type::String
        | Type::StringLiteral(_)
        | Type::Boolean
        | Type::BooleanLiteral(_)
        | Type::Null
        | Type::Undefined
        | Type::Void
        | Type::Uint8Array
        | Type::Function { .. }
        | Type::Unknown => None,
        Type::BigIntLiteral(_) => Some(
            "bigint literal types aren't supported as `as` targets — cast to `bigint` \
             and compare the value",
        ),
        Type::Object { fields, index } => fields
            .values()
            .map(|f| &f.ty)
            .chain(index.iter().map(|i| i.value.as_ref()))
            .find_map(|ty| unsupported_cast_target_reason(ty, types, seen)),
        Type::Array(elem) => unsupported_cast_target_reason(elem, types, seen),
        Type::Tuple(elems) => elems
            .iter()
            .find_map(|e| unsupported_cast_target_reason(e, types, seen)),
        Type::Union(members) => members
            .iter()
            .find_map(|m| unsupported_cast_target_reason(m, types, seen)),
        Type::InterfaceRef { mangled, name, .. } => {
            if types.interface_has_methods(mangled, name) {
                Some(
                    "interfaces with methods are nominal — a plain structural check \
                     can't verify their vtable at runtime",
                )
            } else {
                Some("recursive interface types aren't supported as `as` targets")
            }
        }
        Type::ClassRef { .. } => Some("class types aren't yet supported as `as` targets"),
        // A recursion back-edge: expand the alias and check its body once.
        // `seen` breaks the cycle so a re-encounter is assumed supported,
        // matching the per-alias recursive validator codegen emits.
        Type::AliasRef { .. } => {
            if seen.iter().any(|s| s == peeled) {
                return None;
            }
            seen.push(peeled.clone());
            let expanded = assignable::expand_alias_ref(peeled, types);
            if matches!(expanded, Type::AliasRef { .. }) {
                return Some("recursive type targets need a recursive structural check at runtime");
            }
            unsupported_cast_target_reason(&expanded, types, seen)
        }
        // Infer reduces an enum to its variant values before asking, so one
        // left here sits behind a recursive alias it doesn't expand.
        Type::NumberEnum { .. } | Type::StringEnum { .. } => {
            Some("enum targets need a per-variant value check at runtime")
        }
        Type::TypeVar(_) | Type::GenericParam { .. } => {
            Some("generic type parameters are erased at runtime")
        }
        Type::Never => Some("`never` has no runtime values"),
        Type::Error => None,
        Type::Alias { ty: underlying, .. }
        | Type::Refined { ty: underlying, .. }
        | Type::Readonly(underlying) => unsupported_cast_target_reason(underlying, types, seen),
    }
}

/// Render `variants: \`E.A\`, \`E.B\`, …` for an unknown-variant
/// diagnostic. Returns an empty help block when the enum has no
/// variants (which only happens on a malformed decl that already
/// emitted its own diagnostic).
pub(super) fn enum_variant_help<'a>(
    enum_name: &str,
    variant_names: impl Iterator<Item = &'a String>,
) -> Vec<String> {
    let list: Vec<String> = variant_names
        .map(|v| format!("`{enum_name}.{v}`"))
        .collect();
    if list.is_empty() {
        Vec::new()
    } else {
        vec![format!("variants: {}", list.join(", "))]
    }
}

/// The member a string-literal key names: `o["content-type"]` reads field
/// `content-type` wherever `o.name` would read `name`. `None` for any other key.
pub(super) fn string_key_name(
    ast: &crate::Ast,
    key: ExprId,
) -> Result<Option<Ident>, CompilerFailure> {
    let key = ast.try_expr(key).map_err(super::arena_failure)?;
    let ExprKind::String(name) = &key.kind else {
        return Ok(None);
    };
    Ok(Some(Ident {
        name: name.clone(),
        span: key.span,
    }))
}

/// `o["m"](…)` calls method `m`, exactly as `o.m(…)` does: every call path in
/// `infer_call` dispatches on a `FieldAccess` callee.
fn string_key_callee_as_field(
    ast: &crate::Ast,
    callee: ExprId,
) -> Result<ExprKind, CompilerFailure> {
    let kind = ast
        .try_expr(callee)
        .map_err(super::arena_failure)?
        .kind
        .clone();
    if let ExprKind::IndexAccess { receiver, index } = kind
        && let Some(name) = string_key_name(ast, index)?
    {
        return Ok(ExprKind::FieldAccess { receiver, name });
    }
    Ok(kind)
}

/// `o?.["content-type"]` reads a field, exactly as `o["content-type"]` does.
fn string_key_as_field(ast: &crate::Ast, part: ChainPart) -> Result<ChainPart, CompilerFailure> {
    if let ChainPart::Index {
        idx,
        optional,
        span,
    } = part
        && let Some(name) = string_key_name(ast, idx)?
    {
        return Ok(ChainPart::Field {
            name,
            optional,
            span,
        });
    }
    Ok(part)
}

/// The type of an expression that evaluates to one of two operands. `void`
/// has no value to join with the other operand's, so an expression that may
/// produce it is `void` as a whole: usable for its effects, and refused
/// wherever a value is needed.
fn conditional_result_type(
    left: Type,
    right: Type,
    types: super::assignable::TypeResolver<'_>,
) -> Type {
    branch_result_type(left, right, types)
}

fn branch_result_type(left: Type, right: Type, types: super::assignable::TypeResolver<'_>) -> Type {
    if matches!(left.peel(), Type::Object { .. })
        && matches!(right.peel(), Type::Object { .. })
        && left.peel() != right.peel()
    {
        Type::union(vec![left, right])
    } else if assignable(&left, &right, types) {
        right
    } else if assignable(&right, &left, types) {
        left
    } else {
        Type::union(vec![left, right])
    }
}

/// An empty object literal reads as none of an all-optional object's fields,
/// so it joins with that object as the object itself, as in tsc: `t ? {} : opts`
/// is `opts`. Only a literal: a value typed `{}` may hold any object, with
/// fields of other types.
fn empty_literal_join(
    ast: &crate::Ast,
    left: (ExprId, &Type),
    right: (ExprId, &Type),
) -> Result<Option<Type>, CompilerFailure> {
    for ((literal, _), (_, other)) in [(left, right), (right, left)] {
        if is_empty_object_literal(ast, literal)? && has_only_optional_fields(other) {
            return Ok(Some(other.clone()));
        }
    }
    Ok(None)
}

/// Whether `ty` is the type of an array that holds no element at any depth:
/// `never[]`, `never[][]`, as an empty literal is typed.
fn holds_no_element(ty: &Type) -> bool {
    match ty.peel() {
        Type::Array(element) => matches!(element.peel(), Type::Never) || holds_no_element(element),
        _ => false,
    }
}

fn is_empty_object_literal(ast: &crate::Ast, expr: ExprId) -> Result<bool, CompilerFailure> {
    let id = peel_parens(ast, expr)?;
    Ok(matches!(
        &ast.try_expr(id).map_err(super::arena_failure)?.kind,
        ExprKind::ObjectLiteral { members } if members.is_empty()
    ))
}

fn has_only_optional_fields(ty: &Type) -> bool {
    matches!(
        ty.peel(),
        Type::Object { fields, index: None } if fields.values().all(|field| field.optional)
    )
}

/// The hint an empty array literal cast to `ty` takes its element type from: `ty`
/// itself when it is an array or a union of arrays, which an array literal is
/// typed against as under an annotation. Otherwise a union's first array member,
/// which the empty literal then satisfies as it would any other.
fn empty_array_cast_hint(ty: &Type) -> Option<&Type> {
    match ty.peel() {
        Type::Array(_) => Some(ty),
        Type::Union(members) if !members.iter().any(|m| matches!(m.peel(), Type::Tuple(_))) => {
            members
                .iter()
                .any(|member| matches!(member.peel(), Type::Array(_)))
                .then_some(ty)
        }
        Type::Union(members) => members
            .iter()
            .find(|member| matches!(member.peel(), Type::Array(_))),
        _ => None,
    }
}

/// How a mismatch message names the elements a later one failed to match.
fn matched_elements(running_is_first: bool) -> &'static str {
    if running_is_first {
        "matching first element"
    } else {
        "matching the elements before it"
    }
}

#[derive(Clone, Copy)]
struct ElementJoin {
    /// Whether a later element may widen the element type to its own, or by
    /// the `null`/`undefined` it adds.
    widens: bool,
    /// Whether elements that don't fit one another join as a union, which
    /// the literal reduces and normalizes once every element is typed.
    joins_as_union: bool,
}

/// A method `find_method` found: its signature, the receiver's type arguments,
/// its interface and its dispatch.
type FoundMethod = (
    MethodSig,
    BTreeMap<String, Type>,
    crate::MangledName,
    crate::Dispatch,
);

/// The methods a union of strings with arrays or tuples (`arrays`, their
/// union) calls for one name, on each side.
struct StringOrArrayMethods {
    string_method: FoundMethod,
    arrays: Type,
    array_method: FoundMethod,
}

/// A method call's parts after its callee: what dispatch needs once the
/// receiver is typed.
#[derive(Clone)]
struct MethodCallSite<'a> {
    name: Ident,
    type_args: Option<Vec<TypeAnnotation>>,
    args: Vec<ExprId>,
    expected: Option<&'a Type>,
    span: Span,
}

#[derive(Clone, Copy)]
struct ElementMismatch {
    hint_pins_element_ty: bool,
    running_is_first: bool,
    already_errored: bool,
}

/// The expression inside any parentheses around `expr`.
pub(super) fn peel_parens(ast: &crate::Ast, mut expr: ExprId) -> Result<ExprId, CompilerFailure> {
    loop {
        match &ast.try_expr(expr).map_err(super::arena_failure)?.kind {
            ExprKind::Paren(inner) => expr = *inner,
            _ => return Ok(expr),
        }
    }
}

/// Whether `expr` is an empty `[]`, or holds one as a ternary branch or an
/// array literal's element, where it would take its type from `expr`'s hint.
fn holds_empty_array_literal(ast: &crate::Ast, expr: ExprId) -> Result<bool, CompilerFailure> {
    let id = peel_parens(ast, expr)?;
    Ok(
        match &ast.try_expr(id).map_err(super::arena_failure)?.kind {
            ExprKind::ArrayLiteral { elements } if elements.is_empty() => true,
            ExprKind::ArrayLiteral { elements } => {
                for element in elements {
                    if holds_empty_array_literal(ast, element.value())? {
                        return Ok(true);
                    }
                }
                false
            }
            ExprKind::Ternary { then_, else_, .. } => {
                holds_empty_array_literal(ast, *then_)? || holds_empty_array_literal(ast, *else_)?
            }
            _ => false,
        },
    )
}

/// The type `!` yields for an operand of `value_ty`. An operand that is only
/// `null` or `undefined` never survives the assertion, so the result is
/// `never` rather than `strip_nullish`'s poisoned `Error`.
fn non_null_assert_type(value_ty: &Type) -> Type {
    if is_nullish_only(value_ty) {
        Type::Never
    } else {
        super::narrowing::strip_nullish(value_ty)
    }
}

/// Whether every value of `ty` is `null` or `undefined`, so it gives an array
/// literal's element type no shape of its own.
fn is_nullish_only(ty: &Type) -> bool {
    ty.all_members(&|member| matches!(member, Type::Null | Type::Undefined | Type::Void))
}

/// Whether `id` has no type of its own without context: an arrow, whose
/// parameters need one, or `[]`, whose elements do.
pub(super) fn cannot_be_typed_alone(ast: &crate::Ast, id: ExprId) -> Result<bool, CompilerFailure> {
    Ok(
        match &ast.try_expr(id).map_err(super::arena_failure)?.kind {
            ExprKind::Paren(inner) => cannot_be_typed_alone(ast, *inner)?,
            ExprKind::Arrow { .. } => true,
            ExprKind::ArrayLiteral { elements } => elements.is_empty(),
            _ => false,
        },
    )
}

/// Whether `id` is a literal form that takes its type from context when it
/// has one: an arrow, an object literal or an array literal.
fn is_context_typed_literal(ast: &crate::Ast, id: ExprId) -> Result<bool, CompilerFailure> {
    Ok(
        match &ast.try_expr(id).map_err(super::arena_failure)?.kind {
            ExprKind::Paren(inner) => is_context_typed_literal(ast, *inner)?,
            ExprKind::Arrow { .. }
            | ExprKind::ObjectLiteral { .. }
            | ExprKind::ArrayLiteral { .. } => true,
            _ => false,
        },
    )
}

/// The literal type of a number, with `-0` read as `0`: they are one value
/// under `===`.
pub(super) fn number_literal_type(value: f64) -> Type {
    let canonical = if value == 0.0 { 0.0 } else { value };
    Type::NumberLiteral(crate::types::LiteralF64(canonical))
}

/// The string a template spells, when every substitution has a constant text.
fn spelled_template(parts: &[String], substitutions: Vec<Option<String>>) -> Option<String> {
    let mut substitutions = substitutions.into_iter();
    let mut text = String::new();
    for part in parts {
        crate::literal_units::push_literal_text(&mut text, part);
        if let Some(substitution) = substitutions.next() {
            crate::literal_units::push_literal_text(&mut text, &substitution?);
        }
    }
    Some(text)
}

pub(super) fn literal_comparison_type(
    ast: &crate::TypedAst,
    expr: &TypedExpr,
) -> Result<Type, crate::compiler_error::CompilerFailure> {
    Ok(match &expr.kind {
        TypedExprKind::String(value) => Type::StringLiteral(value.clone()),
        TypedExprKind::Number(value) => Type::NumberLiteral(crate::types::LiteralF64(*value)),
        TypedExprKind::Boolean(value) => Type::BooleanLiteral(*value),
        TypedExprKind::BigInt(digits) => crate::types::bigint_literal_type(digits),
        TypedExprKind::Unary {
            op: op @ (UnOp::Neg | UnOp::Pos),
            operand,
        } => {
            let negative = matches!(op, UnOp::Neg);
            match &ast
                .try_expr(*operand)
                .map_err(crate::typechecker::arena_failure)?
                .kind
            {
                TypedExprKind::Number(value) => {
                    number_literal_type(if negative { -value } else { *value })
                }
                TypedExprKind::BigInt(digits) if negative => {
                    Type::BigIntLiteral(crate::types::negate_bigint_digits(digits))
                }
                _ => expr.ty.clone(),
            }
        }
        _ => expr.ty.clone(),
    })
}

fn tuple_receiver_length_type(receiver: &Type) -> Option<Type> {
    match receiver.peel() {
        Type::Tuple(tuple) => Some(tuple_length_type(tuple)),
        Type::Union(members) => members
            .iter()
            .map(|member| match member.peel() {
                Type::Tuple(tuple) => Some(tuple_length_type(tuple)),
                _ => None,
            })
            .collect::<Option<Vec<_>>>()
            .map(Type::union),
        _ => None,
    }
}

fn tuple_length_type(tuple: &crate::types::TupleType) -> Type {
    Type::union(
        (tuple.required_len()..=tuple.len())
            .map(|length| Type::NumberLiteral(crate::types::LiteralF64(length as f64)))
            .collect(),
    )
}

fn tuple_position_hint(tuple: &crate::types::TupleType, first: usize, last: usize) -> Option<Type> {
    let hints: Vec<_> = tuple
        .iter()
        .enumerate()
        .filter(|(index, _)| *index >= first && *index <= last)
        .map(|(_, ty)| ty.clone())
        .collect();
    (!hints.is_empty()).then(|| Type::union(hints))
}

/// Optional elements in an earlier spread shift each following element left.
/// Keep the possible types at each position and the minimum/maximum lengths.
fn append_tuple_literal_types(
    prefix: crate::types::TupleType,
    suffix: &crate::types::TupleType,
    limits: &crate::type_size::TypeLimits,
) -> Result<crate::types::TupleType, TypeTooLarge> {
    let length = prefix
        .len()
        .checked_add(suffix.len())
        .ok_or(TypeTooLarge::Nodes)?;
    if u64::try_from(length).map_err(|_| TypeTooLarge::Nodes)?
        >= crate::compiler_limits::MAX_TYPE_NODES
    {
        return Err(TypeTooLarge::Nodes);
    }
    let required = prefix
        .required_len()
        .checked_add(suffix.required_len())
        .ok_or(TypeTooLarge::Nodes)?;
    let mut budget = limits.budget();
    budget.charge(1)?;
    let mut elements = Vec::with_capacity(length);
    for index in 0..length {
        let mut candidates = Vec::new();
        if let Some(ty) = prefix.get(index) {
            budget.charge_copy(ty, 3)?;
            candidates.push(ty.clone());
        }
        for offset in prefix.required_len()..=prefix.len() {
            if !limits.spend_work(1) {
                return Err(TypeTooLarge::Work);
            }
            if let Some(ty) = index.checked_sub(offset).and_then(|i| suffix.get(i)) {
                budget.charge_copy(ty, 3)?;
                candidates.push(ty.clone());
            }
        }
        budget.charge(2)?;
        let ty = Type::union(candidates);
        elements.push(crate::ObjectField::widen_optional(index >= required, ty));
    }
    Ok(crate::types::TupleType {
        elements,
        optional: length.saturating_sub(required),
    })
}

pub(super) fn callable_parameter_type(param: &crate::Param) -> Type {
    crate::ObjectField::widen_optional(param.is_omittable(), param.ty.clone())
}

pub(super) fn required_parameter_count(params: &[crate::Param]) -> usize {
    params
        .iter()
        .rposition(|p| !p.rest && !p.is_omittable())
        .map_or(0, |index| index + 1)
}

/// The pairs `+` is defined for, and the result. The single source of truth for both
/// the `+` arm and the narrowing hint it emits: a hint may only claim a guard is the
/// fix when the guarded pair is one this accepts.
pub(super) fn plus_result(lt: &Type, rt: &Type) -> Option<Type> {
    match never_operand_result(lt, rt, NeverPartners::NumericOrString) {
        NeverOperand::Accepted(result) => return Some(result),
        NeverOperand::Rejected => return None,
        NeverOperand::Absent => {}
    }
    match (lt.primitive_behavior(), rt.primitive_behavior()) {
        // A literal operand behaves as its base and yields the base, never a
        // literal: `1 + 1` is `number`, not `2`. Same rule as `ordering_accepts`.
        (Type::Number | Type::NumberLiteral(_), Type::Number | Type::NumberLiteral(_)) => {
            Some(Type::Number)
        }
        (Type::String | Type::StringLiteral(_), Type::String | Type::StringLiteral(_)) => {
            Some(Type::String)
        }
        // A `never` operand is in code that doesn't run, as TypeScript reads
        // `"bad: " + x` after every member of `x` was ruled out.
        (Type::String | Type::StringLiteral(_), Type::Never)
        | (Type::Never, Type::String | Type::StringLiteral(_)) => Some(Type::String),
        // Mixed `number` ↔ `bigint` is rejected, so no widening arm here.
        (Type::BigInt, Type::BigInt) => Some(Type::BigInt),
        _ => None,
    }
}

/// [`plus_result`] for `-`, `*`, `/`, `%`, `**` — same role, no string arm.
pub(super) fn arithmetic_result(lt: &Type, rt: &Type) -> Option<Type> {
    match never_operand_result(lt, rt, NeverPartners::NumericOnly) {
        NeverOperand::Accepted(result) => return Some(result),
        NeverOperand::Rejected => return None,
        NeverOperand::Absent => {}
    }
    match (lt.primitive_behavior(), rt.primitive_behavior()) {
        (Type::Number | Type::NumberLiteral(_), Type::Number | Type::NumberLiteral(_)) => {
            Some(Type::Number)
        }
        (Type::BigInt, Type::BigInt) => Some(Type::BigInt),
        _ => None,
    }
}

/// [`plus_result`] for `<`, `>`, `<=`, `>=`, which always yield `boolean` — strings
/// compare lexicographically, and literal types order as their widened base.
fn ordering_accepts(lt: &Type, rt: &Type) -> bool {
    // A `never` operand orders against numbers and bigints only: tsc rejects
    // `never < string`, unlike `never + string`.
    match never_operand_result(lt, rt, NeverPartners::NumericOnly) {
        NeverOperand::Accepted(_) => return true,
        NeverOperand::Rejected => return false,
        NeverOperand::Absent => {}
    }
    matches!(
        (lt.primitive_behavior(), rt.primitive_behavior()),
        (
            Type::Number | Type::NumberLiteral(_),
            Type::Number | Type::NumberLiteral(_)
        ) | (Type::BigInt, Type::BigInt)
            | (
                Type::String | Type::StringLiteral(_),
                Type::String | Type::StringLiteral(_),
            )
    )
}

/// [`plus_result`] for unary `-` / `+`. `unknown` is absent because the call site
/// answers it with its own "narrow first" diagnostic before asking this.
fn unary_arith_result(op: UnOp, ty: &Type) -> Option<Type> {
    if matches!(op, UnOp::BitNot) {
        return bitnot_result(ty);
    }
    match ty.primitive_behavior() {
        Type::BigInt | Type::BigIntLiteral(_) => Some(Type::BigInt),
        Type::Number | Type::NumberLiteral(_) | Type::Never | Type::Error => Some(Type::Number),
        // `+s` is JS's explicit string→number coercion and the one TS keeps; it
        // lowers to the same parse `Number(s)` does (`NaN` when the text isn't a
        // number). Unary `-` on a string stays rejected: it reads as arithmetic,
        // not a conversion.
        t if matches!(op, UnOp::Pos) && t.is_string_shaped() => Some(Type::Number),
        _ => None,
    }
}

/// What a binary operator makes of a `never` operand.
enum NeverOperand {
    /// Neither operand is `never`; the operator's ordinary rules apply.
    Absent,
    Accepted(Type),
    Rejected,
}

/// Which partners of a `never` operand an operator accepts besides numbers and
/// bigints.
#[derive(Clone, Copy)]
enum NeverPartners {
    NumericOnly,
    /// `+`, which also concatenates.
    NumericOrString,
}

/// A `never` value can't exist, so the operator is accepted whenever some operand type
/// would be, and its result comes from the other operand as tsc's does: `never + string`
/// is `string`, `never - bigint` is `bigint`, and `never` with `never` is `number`.
fn never_operand_result(lt: &Type, rt: &Type, partners: NeverPartners) -> NeverOperand {
    let other = match (lt.peel(), rt.peel()) {
        (Type::Never, _) => rt,
        (_, Type::Never) => lt,
        _ => return NeverOperand::Absent,
    };
    match (other.primitive_behavior(), partners) {
        (Type::Never | Type::Number | Type::NumberLiteral(_), _) => {
            NeverOperand::Accepted(Type::Number)
        }
        (Type::BigInt, _) => NeverOperand::Accepted(Type::BigInt),
        (Type::String | Type::StringLiteral(_), NeverPartners::NumericOrString) => {
            NeverOperand::Accepted(Type::String)
        }
        _ => NeverOperand::Rejected,
    }
}

fn bitnot_result(ty: &Type) -> Option<Type> {
    match ty.peel() {
        Type::Unknown | Type::Null | Type::Undefined | Type::Void => None,
        Type::BigInt | Type::BigIntLiteral(_) => Some(Type::BigInt),
        Type::Never => Some(Type::Number),
        Type::Union(members) => {
            let results: Option<Vec<_>> = members.iter().map(bitnot_result).collect();
            results.map(Type::union)
        }
        _ => Some(Type::Number),
    }
}

/// Whether every value of `ty` is falsy: `null`, `undefined`, `false`, `0`,
/// `""`. tsc spreads such a value as `{}`, as JavaScript copies nothing from it.
fn is_definitely_falsy(ty: &Type) -> bool {
    match ty.peel() {
        Type::Null | Type::Undefined | Type::BooleanLiteral(false) => true,
        Type::NumberLiteral(value) => value.0 == 0.0,
        Type::StringLiteral(value) => value.is_empty(),
        _ => false,
    }
}

/// Interpolations that convert at run time, as JavaScript's ToString does: a
/// value that may be `null` or `undefined`, or whose type is known only then.
/// A `toString` call would throw on the nullish ones.
fn interpolates_at_run_time(ty: &Type) -> bool {
    match ty.peel() {
        Type::Null | Type::Unknown | Type::TypeVar(_) | Type::GenericParam { .. } => true,
        Type::Union(members) => members.iter().any(|member| {
            matches!(member.peel(), Type::Undefined | Type::Void)
                || interpolates_at_run_time(member)
        }),
        _ => false,
    }
}

/// Types whose values reach a `toString` — the receivers `String(x)` and `${x}` accept.
fn has_to_string(ty: &Type) -> bool {
    if let Type::Union(members) = ty.peel() {
        return members.iter().all(has_to_string);
    }
    matches!(
        ty,
        Type::String
            | Type::Undefined
            | Type::Void
            | Type::StringLiteral(_)
            | Type::Number
            | Type::NumberLiteral(_)
            | Type::BigInt
            | Type::BigIntLiteral(_)
            | Type::Boolean
            | Type::BooleanLiteral(_)
            | Type::Array(_)
            // A tuple is an array at runtime, and answers `toString` as one.
            | Type::Tuple(_)
            | Type::Object { .. }
            // Class instances answer `toString` through vtable slot 0
            // (a user method fills it, else "[object Object]").
            | Type::ClassRef { .. }
            // An interface value is an object, whose vtable answers `toString`
            // whether the interface declares it as a method, a function-typed
            // property, or not at all.
            | Type::InterfaceRef { .. }
            | Type::TypeVar(_)
            | Type::GenericParam { .. }
            | Type::Unknown
            | Type::Error
    )
}

type ObjectFields = BTreeMap<String, crate::ObjectField>;

/// The fields a spread copies. `by_name`: the source has no one layout, so each
/// field is found by name at run time.
pub(super) struct SpreadFields {
    pub(super) fields: ObjectFields,
    pub(super) by_name: bool,
}

/// A spread's field, merged over what an earlier member wrote to the same name.
///
/// An optional field may be absent, and then the earlier value stays: `{ a: 1,
/// ...{} }` keeps `a: 1`. So the field holds either value, and is optional only
/// if the earlier one was. Omitted optional slots count as absent, matching `in`.
///
/// The earlier values form a boxed chain, one fallback link per optional spread
/// that overrides an earlier value, which later phases walk recursively.
fn merge_spread_field(
    earlier: Option<(crate::ObjectField, crate::TypedObjectFieldSource)>,
    field: crate::ObjectField,
    origin: crate::TypedObjectFieldSource,
) -> Result<(crate::ObjectField, crate::TypedObjectFieldSource), CompilerFailure> {
    let keeps_earlier = field.optional;
    let Some((earlier_field, earlier_origin)) = earlier.filter(|_| keeps_earlier) else {
        return Ok((field, origin));
    };
    if overriding_spreads(&earlier_origin) >= crate::compiler_limits::MAX_SPREAD_FALLBACK_CHAIN {
        return Err(CompilerFailure::Limit {
            stage: crate::compiler_error::CompilerStage::Infer,
            span: None,
            message: format!(
                "an object literal overrides one field with more than {} optional spreads",
                crate::compiler_limits::MAX_SPREAD_FALLBACK_CHAIN
            ),
            help: vec!["merge the spread sources into intermediate objects".into()],
        });
    }
    let mut origin = origin;
    if let crate::TypedObjectFieldSource::Spread { fallback, .. } = &mut origin {
        *fallback = Some(Box::new(earlier_origin));
    }
    Ok((merge_spread_field_type(Some(earlier_field), field), origin))
}

/// Optional spreads in `origin`'s chain that override an earlier value: its
/// fallback links, whatever supplied the first value.
fn overriding_spreads(origin: &crate::TypedObjectFieldSource) -> u32 {
    let mut overrides = 0u32;
    let mut next = origin;
    while let crate::TypedObjectFieldSource::Spread {
        fallback: Some(fallback),
        ..
    } = next
    {
        overrides = overrides.saturating_add(1);
        next = fallback;
    }
    overrides
}

fn merge_spread_field_type(
    earlier: Option<crate::ObjectField>,
    field: crate::ObjectField,
) -> crate::ObjectField {
    let Some(earlier) = earlier.filter(|_| field.optional) else {
        return field;
    };
    crate::ObjectField {
        ty: Type::union(vec![earlier.ty, field.ty]),
        optional: earlier.optional,
        readonly: false,
        method: false,
    }
}

fn collect_union_members(ty: &Type, out: &mut Vec<Type>) {
    match ty.peel() {
        Type::Union(members) => {
            for member in members {
                collect_union_members(member, out);
            }
        }
        other => out.push(other.clone()),
    }
}

/// One object type a spread's source may be, with its string index
/// signature's value type when it has one.
#[derive(PartialEq)]
struct SpreadAlternative {
    fields: ObjectFields,
    index_value: Option<Type>,
}

/// The fields of a spread whose source is one of several object types: every
/// field any of them has, optional where some lack it or have it optional. An
/// alternative with an index signature can hold a field it doesn't name, so
/// that field may also hold the index signature's value type.
fn merge_spread_alternatives(alternatives: &[SpreadAlternative]) -> ObjectFields {
    let names: std::collections::BTreeSet<&String> = alternatives
        .iter()
        .flat_map(|alternative| alternative.fields.keys())
        .collect();
    names
        .into_iter()
        .map(|name| {
            let present: Vec<&crate::ObjectField> = alternatives
                .iter()
                .filter_map(|alternative| alternative.fields.get(name))
                .collect();
            let optional =
                present.len() < alternatives.len() || present.iter().any(|field| field.optional);
            let index_values = alternatives
                .iter()
                .filter(|alternative| !alternative.fields.contains_key(name))
                .filter_map(|alternative| alternative.index_value.clone());
            let ty = Type::union(
                present
                    .iter()
                    .map(|field| field.ty.clone())
                    .chain(index_values)
                    .collect(),
            );
            (
                name.clone(),
                crate::ObjectField {
                    ty,
                    optional,
                    readonly: false,
                    method: false,
                },
            )
        })
        .collect()
}

/// TypeScript compares assertion targets against the source's widened literals.
/// This only relaxes acceptance: the original source still determines whether
/// the cast needs a runtime check.
fn widen_assertion_source(source: &Type) -> Type {
    match source.peel() {
        Type::Union(members) => Type::union(members.iter().map(widen_assertion_source).collect()),
        source => source.widen_literal(),
    }
}

/// The placeholder for a name that doesn't resolve to a value. `Type::Error`
/// suppresses downstream cascades, so the reference kind doesn't matter.
fn unresolved_ref(ident: Ident) -> (TypedExprKind, Type) {
    (
        TypedExprKind::LocalRef {
            ident,
            boxed: false,
        },
        Type::Error,
    )
}

#[cfg(test)]
mod tests {
    use super::super::test_support::{
        nth_decl_value_ty, nth_expr_stmt_ty, run, run_clean, run_with_packages,
    };
    use crate::{ClosureBody, Type, TypedAst, TypedExprKind, TypedParam, TypedStmtKind};

    #[test]
    fn optional_class_method_calls_keep_receiver_and_call_guards() {
        for method_optional in [false, true] {
            for receiver_optional in [false, true] {
                let method_mark = if method_optional { "?" } else { "" };
                let receiver_mark = if receiver_optional { "?" } else { "" };
                let receiver_type = if receiver_optional {
                    "Box | null"
                } else {
                    "Box"
                };
                let source = format!(
                    "class Box {{ read{method_mark}(): number {{ return 8; }} }}
                     function invoke(box: {receiver_type}): number | undefined {{
                       return box{receiver_mark}.read?.();
                     }}"
                );
                let (typed, diagnostics) = run(&source);
                assert!(diagnostics.is_empty(), "{diagnostics:?}");
                let parts = typed
                    .expr_ids()
                    .unwrap()
                    .find_map(|id| match &typed.try_expr(id).unwrap().kind {
                        TypedExprKind::OptionalChain { parts, .. } => Some(parts),
                        _ => None,
                    })
                    .expect("optional class method chain");
                let [
                    crate::TypedChainPart::Field {
                        optional,
                        result_ty,
                        ..
                    },
                    crate::TypedChainPart::Call { optional: true, .. },
                ] = parts.as_slice()
                else {
                    panic!("expected field read followed by optional call: {parts:?}");
                };
                assert_eq!(*optional, receiver_optional);
                let includes_undefined = matches!(result_ty, Type::Union(members)
                    if members.contains(&Type::Undefined));
                assert_eq!(includes_undefined, method_optional);
            }
        }
    }

    #[test]
    fn optional_universal_methods_keep_vtable_dispatch() {
        for receiver_type in ["Error", "Empty"] {
            let source = format!(
                "class Empty {{}}
                 function invoke(value: {receiver_type} | null): string | undefined {{
                   return value?.toString?.();
                 }}"
            );
            let (typed, diagnostics) = run(&source);
            assert!(diagnostics.is_empty(), "{diagnostics:?}");
            let parts = typed
                .expr_ids()
                .unwrap()
                .find_map(|id| match &typed.try_expr(id).unwrap().kind {
                    TypedExprKind::OptionalChain { parts, .. } => Some(parts),
                    _ => None,
                })
                .expect("optional universal method chain");
            assert!(matches!(
                parts.as_slice(),
                [crate::TypedChainPart::MethodCall { optional: true, .. }]
            ));
        }
    }

    #[test]
    fn this_outside_class_reports_once_per_occurrence() {
        for body in ["return this.x;", "const x = this.x;", "this.x;"] {
            let (_, diagnostics) = run(&format!("function main(): void {{ {body} }}"));
            let count = diagnostics
                .iter()
                .filter(|d| {
                    d.message
                        .contains("`this` is only valid inside a class method or constructor body")
                })
                .count();
            assert_eq!(count, 1, "{body}: {diagnostics:?}");
        }
    }

    /// Typecheck `source` against the real `submilli:session` declaration.
    fn run_with_session(source: &str) -> (TypedAst, Vec<crate::Diagnostic>) {
        let session = crate::stdlib::session::declaration::package_declaration();
        run_with_packages(source, &[&session])
    }

    /// Every `session.get` call in `ta`, as (has a structural `check`, the
    /// inner call's `return_cast`).
    fn session_get_shapes(ta: &TypedAst) -> Vec<(bool, Option<Type>)> {
        let mut out = Vec::new();
        for i in 0..ta.exprs_len() {
            let expr = ta.try_expr(crate::ExprId(i as u32)).unwrap();
            let TypedExprKind::Cast { value, check, .. } = &expr.kind else {
                continue;
            };
            let TypedExprKind::GenericCall {
                mangled,
                return_cast,
                ..
            } = &ta.try_expr(*value).unwrap().kind
            else {
                continue;
            };
            if crate::stdlib::session::declaration::is_checked_get(mangled) {
                out.push((check.is_some(), return_cast.clone()));
            }
        }
        out
    }

    /// The soundness invariant of the checked read: a `get<T>` must lower to a
    /// `Cast` that carries a structural check, and the call it wraps must NOT
    /// carry a `return_cast` — that is a `ref.cast`, a representation-only
    /// narrow that verifies nothing and traps uncatchably on a stored `null`.
    #[test]
    fn typed_session_get_is_a_checked_cast_and_never_a_return_cast() {
        let src = "import session from \"submilli:session\"; \
                   interface P { step: number; } \
                   function main(): void { const p = session.get<P>(\"k\"); }";
        let (ta, diags) = run_with_session(src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");

        let shapes = session_get_shapes(&ta);
        assert_eq!(shapes.len(), 1, "expected one wrapped get, got {shapes:?}");
        assert!(shapes[0].0, "get<P> lost its structural check: {shapes:?}");
        assert_eq!(
            shapes[0].1, None,
            "get<P> kept an unsound return_cast: {shapes:?}",
        );
    }

    /// No raw `GenericCall` on `session.get` may survive with a `return_cast`,
    /// whichever import form produced it.
    #[test]
    fn no_import_form_of_session_get_keeps_a_return_cast() {
        let src = "import session from \"submilli:session\"; \
                   import kv from \"submilli:session\"; \
                   import { get } from \"submilli:session\"; \
                   interface P { step: number; } \
                   function main(): void { \
                     const a = session.get<P>(\"k\"); \
                     const b = kv.get<P>(\"k\"); \
                     const c = get<P>(\"k\"); }";
        let (ta, diags) = run_with_session(src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        assert_eq!(
            session_get_shapes(&ta),
            vec![(true, None), (true, None), (true, None)],
            "every import form must produce a checked, uncast get",
        );

        for i in 0..ta.exprs_len() {
            let expr = ta.try_expr(crate::ExprId(i as u32)).unwrap();
            if let TypedExprKind::GenericCall {
                mangled,
                return_cast,
                ..
            } = &expr.kind
                && crate::stdlib::session::declaration::is_checked_get(mangled)
            {
                assert_eq!(
                    *return_cast, None,
                    "a session.get GenericCall kept a return_cast",
                );
            }
        }
    }

    /// A bare `get(key)` keeps its pre-generic meaning — an unchecked read of
    /// `unknown` — rather than erroring on an uninferable `T`.
    #[test]
    fn untyped_session_get_defaults_to_unknown_without_erroring() {
        let src = "import session from \"submilli:session\"; \
                   function main(): void { const v = session.get(\"k\"); }";
        let (_, diags) = run_with_session(src);
        assert!(diags.is_empty(), "bare get should not error: {diags:?}");
    }

    /// Only a *written* `<unknown>` is rejected; the message names the fix.
    #[test]
    fn explicit_unknown_type_argument_is_rejected() {
        let src = "import session from \"submilli:session\"; \
                   function main(): void { const v = session.get<unknown>(\"k\"); }";
        let (_, diags) = run_with_session(src);
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("would not verify anything")),
            "expected the unknown-target rejection, got: {diags:?}",
        );
    }

    /// A user generic parameter is erased, so it cannot be a check target.
    #[test]
    fn erased_type_parameter_is_rejected() {
        let src = "import session from \"submilli:session\"; \
                   function load<T>(k: string): T { return session.get<T>(k); } \
                   function main(): void { const n = load<number>(\"k\"); }";
        let (_, diags) = run_with_session(src);
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("erased at runtime")),
            "expected the erasure rejection, got: {diags:?}",
        );
    }

    /// The narrowing hint may only fire when dropping `null` actually makes the
    /// operator legal. `boolean + boolean` is rejected either way, so advising a
    /// guard there would send the reader after a fix that leaves the same error.
    #[test]
    fn narrowing_hint_skips_operators_a_guard_cannot_fix() {
        let src = "function main(): void { \
                   let v: boolean | null = true; \
                   if (v !== null) { const f = (): boolean => v + true; } }";
        let (_, diags) = run(src);
        assert!(
            diags.iter().any(|d| d.message.contains("not defined for")),
            "expected the operator error, got: {diags:?}",
        );
        assert!(
            !diags
                .iter()
                .any(|d| d.help.iter().any(|h| h.contains("closure boundary"))),
            "narrowing hint fired where narrowing is not the fix: {diags:?}",
        );
    }

    /// The counterpart: same shape, an operator a guard *does* fix.
    #[test]
    fn narrowing_hint_fires_when_a_guard_would_fix_the_operator() {
        let src = "function main(): void { \
                   let v: string | null = \"a\"; \
                   if (v !== null) { const f = (): string => v + \"!\"; v = null; } }";
        let (_, diags) = run(src);
        assert!(
            diags
                .iter()
                .any(|d| d.help.iter().any(|h| h.contains("closure boundary"))),
            "expected the narrowing hint, got: {diags:?}",
        );
    }

    // ----------------------- Literals / identifiers -----------------------

    #[test]
    fn literal_types() {
        let ta = run_clean(r#"42; "s"; true; null;"#);
        assert_eq!(nth_expr_stmt_ty(&ta, 0), Type::Number);
        assert_eq!(nth_expr_stmt_ty(&ta, 1), Type::String);
        assert_eq!(nth_expr_stmt_ty(&ta, 2), Type::Boolean);
        assert_eq!(nth_expr_stmt_ty(&ta, 3), Type::Null);
    }

    #[test]
    fn identifier_resolves_to_global() {
        let ta = run_clean("let x: number = 1; let y: number = x;");
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::Number);
    }

    #[test]
    fn identifier_resolves_to_local_param() {
        let ta = run_clean("function f(n: number): number { return n; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Return(Some(ret_val)) = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Return(Some)");
        };
        let ret_expr = ta.try_expr(*ret_val).unwrap();
        assert_eq!(ret_expr.ty, Type::Number);
        assert!(matches!(ret_expr.kind, TypedExprKind::LocalRef { .. }));
    }

    #[test]
    fn identifier_resolves_to_local_let() {
        let ta = run_clean("function f(): number { let n: number = 1; return n; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Return(Some(ret_val)) = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Return(Some)");
        };
        assert_eq!(ta.try_expr(*ret_val).unwrap().ty, Type::Number);
    }

    #[test]
    fn unresolved_identifier_diagnoses() {
        let (ta, diags) = run("let y: number = q;");
        assert_eq!(diags.len(), 1);
        assert_eq!(diags[0].message, "unresolved identifier `q`");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Error);
    }

    // ----------------------- LocalRef / GlobalRef split -----------------------

    #[test]
    fn function_local_let_is_local_ref() {
        let ta = run_clean("function f(): number { let n: number = 1; return n; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Return(Some(ret_val)) = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Return(Some)");
        };
        assert!(matches!(
            ta.try_expr(*ret_val).unwrap().kind,
            TypedExprKind::LocalRef { boxed: false, .. }
        ));
    }

    #[test]
    fn param_reference_is_local_ref() {
        let ta = run_clean("function f(n: number): number { return n; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Return(Some(ret_val)) = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Return(Some)");
        };
        assert!(matches!(
            ta.try_expr(*ret_val).unwrap().kind,
            TypedExprKind::LocalRef { boxed: false, .. }
        ));
    }

    #[test]
    fn top_level_let_reference_is_global_ref() {
        // The reference `r` inside `f`'s body resolves to the top-level
        // `let r`, so it's a GlobalRef.
        let ta = run_clean("let r: number = 1; function f(): number { return r; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Return(Some(ret_val)) = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Return(Some)");
        };
        assert!(matches!(
            ta.try_expr(*ret_val).unwrap().kind,
            TypedExprKind::GlobalRef { .. }
        ));
    }

    #[test]
    fn call_to_top_level_function_is_static_with_mangled_name() {
        let ta = run_clean("function g(x: number): number { return x; } let r: number = g(1);");
        // top_level: [Let r (uses g), Function g]
        let assign = ta.top_level_statements[0];
        let TypedStmtKind::AssignGlobal { value, .. } = &ta.try_stmt(assign).unwrap().kind else {
            panic!("expected AssignGlobal");
        };
        // The call resolves to a static `Call` carrying the callee's
        // mangled name directly — no callee expression indirection.
        let TypedExprKind::Call { mangled, .. } = &ta.try_expr(*value).unwrap().kind else {
            panic!("expected static Call (not CallClosure)");
        };
        assert_eq!(mangled.as_str(), "main#g");
    }

    #[test]
    fn unresolved_is_local_ref_placeholder() {
        let (ta, diags) = run("let y: number = q;");
        assert_eq!(diags.len(), 1);
        let assign = ta.top_level_statements[0];
        let TypedStmtKind::AssignGlobal { value, .. } = &ta.try_stmt(assign).unwrap().kind else {
            panic!("expected AssignGlobal");
        };
        // Placeholder for unresolved names; downstream suppression via
        // Type::Error means the variant choice doesn't propagate.
        assert!(matches!(
            ta.try_expr(*value).unwrap().kind,
            TypedExprKind::LocalRef { boxed: false, .. }
        ));
        assert_eq!(ta.try_expr(*value).unwrap().ty, Type::Error);
    }

    // ----------------------- `+` -----------------------

    #[test]
    fn number_plus_number() {
        let ta = run_clean("let x: number = 1 + 2;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Number);
    }

    #[test]
    fn string_plus_string() {
        let ta = run_clean(r#"let x: string = "a" + "b";"#);
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::String);
    }

    #[test]
    fn number_plus_string_diagnoses() {
        let (_, diags) = run(r#"let x: number = 1 + "a";"#);
        assert_eq!(diags.len(), 1);
        assert_eq!(
            diags[0].message,
            "`+` not defined for `number` and `string`"
        );
        assert_eq!(
            diags[0].help,
            vec![
                "`+` does not coerce; convert the string with `Number(...)`, `parseInt(...)`, or `parseFloat(...)` before adding"
            ]
        );
    }

    #[test]
    fn string_plus_number_diagnoses_with_string_help() {
        let (_, diags) = run(r#"let x: string = "a" + 1;"#);
        assert_eq!(diags.len(), 1);
        assert_eq!(
            diags[0].message,
            "`+` not defined for `string` and `number`"
        );
        assert_eq!(
            diags[0].help,
            vec!["`+` does not coerce; wrap the number with `String(...)` before concatenating"]
        );
    }

    #[test]
    fn plus_with_number_hint_propagates() {
        let _ = run_clean("function f(n: number): number { return n + 1; }");
    }

    #[test]
    fn plus_with_string_hint_propagates() {
        let _ = run_clean(r#"function f(s: string): string { return s + "!"; }"#);
    }

    // ----------------------- Other binary / unary -----------------------

    #[test]
    fn arith_sub_correct() {
        let ta = run_clean("let x: number = 1 - 2;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Number);
    }

    #[test]
    fn arith_sub_wrong_operand() {
        let (_, d) = run(r#"let x: number = "a" - 2;"#);
        assert_eq!(d.len(), 1);
        // dispatch shape changed from "force-hint Number,
        // complain about LHS" to "infer operands freely, name which
        // combo isn't defined" — the bigint mixed-type case fires the
        // same phrasing.
        assert_eq!(d[0].message, "`-` not defined for `string` and `number`");
    }

    #[test]
    fn arith_mul_div_rem() {
        let _ = run_clean("let x: number = 2 * 3; let y: number = 4 / 2; let z: number = 5 % 2;");
    }

    #[test]
    fn comparison_lt_correct() {
        let ta = run_clean("let x: boolean = 1 < 2;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Boolean);
    }

    #[test]
    fn comparison_lt_wrong_operand() {
        let (_, d) = run(r#"let x: boolean = "a" < 2;"#);
        assert_eq!(d.len(), 1);
        // comparison accepts `number × number`, `bigint × bigint`,
        // or `string × string`; mismatch names both operands.
        assert_eq!(d[0].message, "`<` not defined for `string` and `number`");
    }

    #[test]
    fn comparison_lt_strings_ok() {
        let ta = run_clean(r#"let x: boolean = "apple" < "banana";"#);
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Boolean);
    }

    #[test]
    fn equality_same_type_correct() {
        let ta = run_clean("let x: boolean = 1 === 1;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Boolean);
    }

    #[test]
    fn equality_different_type_diagnoses() {
        let (_, d) = run(r#"let x: boolean = 1 === "a";"#);
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].message, "expected `1`, got `\"a\"`");
    }

    #[test]
    fn logical_and_correct() {
        let ta = run_clean("let x: boolean = true && false;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::BooleanLiteral(false));
    }

    #[test]
    fn logical_and_keeps_literal_operands() {
        // A `let` initializer keeps its literal types, as in TypeScript: `1`
        // is never falsy, so the result is the right side's `true`.
        let ta = run_clean("let x: number | boolean = 1 && true;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::BooleanLiteral(true));
    }

    #[test]
    fn logical_or_string_fallback_returns_value() {
        let ta = run_clean(r#"let s: string = "name"; let x: string = s || "Unknown";"#);
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::String);
    }

    #[test]
    fn logical_or_nullable_lhs_strips_null() {
        let ta = run_clean(
            r#"function name(): string | null { return null; } let s: string | null = name(); let x: string = s || "d";"#,
        );
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::String);
    }

    #[test]
    fn logical_and_nullable_lhs_keeps_null_in_result() {
        let ta = run_clean(
            "function items(): number[] | null { return null; } let xs: number[] | null = items(); let x: number | null = xs && xs.length;",
        );
        assert_eq!(
            nth_decl_value_ty(&ta, 1),
            Type::union(vec![Type::Number, Type::Null])
        );
    }

    #[test]
    fn unary_not_correct() {
        // As in TypeScript, `!` of a value whose truthiness its type decides
        // is a literal type.
        let ta = run_clean("let x: boolean = !true;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::BooleanLiteral(false));
        let ta = run_clean("let b: boolean = 1 > 2; let x: boolean = !b;");
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::Boolean);
    }

    #[test]
    fn unary_not_truthiness_operands() {
        let ta = run_clean("let x: boolean = !1;");
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::BooleanLiteral(false));
        let ta = run_clean("let xs: number[] = [1]; let x: boolean = !xs;");
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::BooleanLiteral(false));
        let ta = run_clean("let n: number = 1; let x: boolean = !n;");
        assert_eq!(nth_decl_value_ty(&ta, 1), Type::Boolean);
    }

    #[test]
    fn unary_neg_of_a_literal_is_its_literal_type() {
        let ta = run_clean("let x: number = -1;");
        assert_eq!(
            nth_decl_value_ty(&ta, 0),
            Type::NumberLiteral(crate::types::LiteralF64(-1.0))
        );
    }

    #[test]
    fn unary_neg_wrong_operand() {
        let (_, d) = run(r#"let x: number = -"a";"#);
        assert_eq!(d.len(), 1);
        // unary `-` / `+` accept number OR bigint; the
        // catch-all phrasing names the operand type that failed.
        assert_eq!(d[0].message, "unary `-` not defined for `string`");
    }

    // ----------------------- Calls -----------------------

    #[test]
    fn call_correct_args() {
        let src = r#"
            function f(a: number, b: string): boolean { return true; }
            let x: boolean = f(1, "s");
        "#;
        let _ = run_clean(src);
    }

    #[test]
    fn call_arity_mismatch() {
        let src = r#"
            function f(a: number, b: string): boolean { return true; }
            let x: boolean = f(1);
        "#;
        let (_, d) = run(src);
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].message, "expected 2 argument(s), got 1");
    }

    #[test]
    fn call_arg_type_mismatch() {
        let src = r#"
            function f(a: number, b: string): boolean { return true; }
            let x: boolean = f(1, 2);
        "#;
        let (_, d) = run(src);
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].message, "expected `string`, got `number`");
    }

    #[test]
    fn call_return_type_propagates() {
        let src = r#"
            function f(a: number, b: string): boolean { return true; }
            let x: boolean = f(1, "s");
        "#;
        let ta = run_clean(src);
        assert_eq!(nth_decl_value_ty(&ta, 0), Type::Boolean);
    }

    #[test]
    fn call_non_function_diagnoses() {
        let (_, d) = run("let x: number = 1; let y: number = x(1);");
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].message, "cannot call value of type `number`");
    }

    #[test]
    fn call_nested() {
        let src = r#"
            function g(x: number): number { return x; }
            let r: number = g(g(1));
        "#;
        let _ = run_clean(src);
    }

    // ----------------------- object & array inference -----------------------

    fn point_ty() -> Type {
        let mut fields = std::collections::BTreeMap::new();
        fields.insert("x".to_string(), crate::ObjectField::required(Type::Number));
        fields.insert("y".to_string(), crate::ObjectField::required(Type::Number));
        Type::Object {
            index: None,
            fields,
        }
    }

    #[test]
    fn object_literal_no_annotation_infers_shape() {
        let ta = run_clean("function main(): void { let p = { x: 1, y: 2 }; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, point_ty());
    }

    #[test]
    fn object_literal_with_annotation_uses_hint() {
        let (ta, d) =
            run("function main(): void { let p: { x: number; y: number } = { y: 2, x: 1 }; }");
        assert!(d.is_empty(), "unexpected diagnostics: {d:?}");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, point_ty());
    }

    #[test]
    fn object_literal_missing_field_diagnoses() {
        let (_, d) = run("function main(): void { let p: { x: number; y: number } = { x: 1 }; }");
        assert!(
            d.iter()
                .any(|x| x.message.contains("missing required field `y`")),
            "expected missing-field diag, got: {d:?}"
        );
    }

    #[test]
    fn object_literal_missing_fields_collapse_to_one_error() {
        let (_, d) =
            run("function main(): void { let p: { x: number; y: number; z: number } = { x: 1 }; }");
        let missing: Vec<_> = d
            .iter()
            .filter(|x| x.message.contains("missing required field"))
            .collect();
        assert_eq!(missing.len(), 1, "expected one collapsed diag, got: {d:?}");
        assert!(
            missing[0].message.contains("`y`") && missing[0].message.contains("`z`"),
            "collapsed diag should list every missing field: {:?}",
            missing[0].message,
        );
    }

    #[test]
    fn fresh_object_literal_extra_field_diagnoses() {
        let (_, d) = run("function main(): void { let p: { x: number } = { x: 1, y: 2 }; }");
        assert!(
            d.iter().any(|x| x.message.contains("unknown field `y`")),
            "expected excess-field diagnostic, got: {d:?}"
        );
    }

    #[test]
    fn intermediate_object_extra_field_is_accepted_via_width_sub() {
        let (_, d) = run("function takesX(p: { x: number }): void { }\n\
             function main(): void { let p = { x: 1, y: 2 }; takesX(p); }");
        assert!(
            d.is_empty(),
            "expected no diagnostics for non-fresh width subtyping, got: {d:?}"
        );
    }

    #[test]
    fn array_literal_infers_element_type() {
        let ta = run_clean("function main(): void { let xs = [1, 2, 3]; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, Type::Array(Box::new(Type::Number)));
    }

    #[test]
    fn array_literal_unification_failure_diagnoses() {
        let (_, d) = run(r#"function main(): void { let xs = [1, "two"]; }"#);
        assert!(
            d.iter()
                .any(|x| x.message.contains("matching first element")),
            "expected unification diag, got: {d:?}"
        );
    }

    #[test]
    fn empty_array_without_hint_is_never_array() {
        let (_, d) = run("function main(): void { let xs = []; console.log(xs.length); }");
        assert!(d.is_empty(), "expected no diagnostics, got: {d:?}");
    }

    #[test]
    fn empty_array_that_grows_without_hint_diagnoses() {
        let (_, d) = run("function main(): void { let xs = []; xs.push(1); }");
        assert!(
            d.iter().any(|x| x
                .message
                .contains("cannot infer the element type of `xs` from an empty array")),
            "expected empty-array diag, got: {d:?}"
        );
    }

    #[test]
    fn empty_array_with_hint_succeeds() {
        let (ta, d) = run("function main(): void { let xs: number[] = []; }");
        assert!(d.is_empty(), "unexpected diagnostics: {d:?}");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, Type::Array(Box::new(Type::Number)));
    }

    #[test]
    fn field_access_returns_field_type() {
        let ta = run_clean("function main(): void { let p = { x: 1 }; let q = p.x; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, Type::Number);
    }

    #[test]
    fn field_access_missing_field_diagnoses() {
        let (_, d) = run("function main(): void { let p = { x: 1 }; let q = p.y; }");
        assert!(
            d.iter().any(|x| x.message.contains("does not exist")),
            "expected missing-field diag, got: {d:?}"
        );
    }

    #[test]
    fn field_access_on_non_object_diagnoses() {
        let (_, d) = run("function main(): void { let n = 1; let q = n.x; }");
        assert!(
            d.iter().any(|x| x.message.contains("non-object type")),
            "expected non-object diag, got: {d:?}"
        );
    }

    #[test]
    fn index_access_returns_element_type() {
        let ta = run_clean("function main(): void { let xs = [1, 2, 3]; let q = xs[0]; }");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block");
        };
        let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Let");
        };
        assert_eq!(*ty, Type::Number);
    }

    #[test]
    fn index_access_on_non_array_diagnoses() {
        let (_, d) = run("function main(): void { let n = 1; let q = n[0]; }");
        assert!(
            d.iter().any(|x| x.message.contains("non-array type")),
            "expected non-array diag, got: {d:?}"
        );
    }

    // ----------------------- Integration snapshot -----------------------

    #[test]
    fn snapshot_mixed_program() {
        let src = r#"
function add(a: number, b: number): number { return a + b; }
let result: number = add(1, 2);
function main(): void { if (result < 10) { } }
"#;
        let ta = run_clean(src);
        insta::assert_debug_snapshot!(ta);
    }

    // ----------------------- number coercions -----------------------

    // `Number` / `String` are now regular prelude `Const`
    // values typed as `NumberConstructor` / `StringConstructor`, so
    // they're legal in value position (a const holding the
    // constructor object — same shape as `console` / `Uint8Array`).
    #[test]
    fn number_is_a_value_of_constructor_interface() {
        let (_, diags) = run("function main(): void { let f = Number; }");
        assert!(
            diags.is_empty(),
            "expected no diagnostics for `Number` as a value, got: {diags:?}"
        );
    }

    #[test]
    fn string_is_a_value_of_constructor_interface() {
        let (_, diags) = run("function main(): void { let f = String; }");
        assert!(
            diags.is_empty(),
            "expected no diagnostics for `String` as a value, got: {diags:?}"
        );
    }

    #[test]
    fn bare_to_string_is_unresolved() {
        let (_, diags) = run("function main(): void { let s = toString(42); }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("unresolved identifier `toString`")),
            "expected unresolved identifier diagnostic, got: {diags:?}"
        );
    }

    // `Number(boolean)` now goes through the standard
    // call-signature dispatch — the union parameter `string | bigint`
    // rejects `boolean` via the standard assignability diagnostic.
    #[test]
    fn number_call_with_wrong_type_diagnoses() {
        let (_, diags) = run("function main(): void { let n = Number(true); }");
        assert!(
            !diags.is_empty(),
            "expected an assignability diagnostic for Number(boolean), got none"
        );
    }

    #[test]
    fn string_call_on_string_is_identity() {
        let (_, diags) = run(r#"function main(): void { let s = String("x"); }"#);
        assert!(
            diags.is_empty(),
            "String(\"x\") should typecheck cleanly, got: {diags:?}"
        );
    }

    #[test]
    fn to_string_on_string_receiver_typechecks() {
        let (_, diags) = run(r#"function main(): void { let s = "hi".toString(); }"#);
        assert!(
            diags.is_empty(),
            "\"hi\".toString() should typecheck cleanly, got: {diags:?}"
        );
    }

    // ----------------------- console.log -----------------------

    #[test]
    fn console_value_typechecks_as_console_interface_ref() {
        let (_, diags) = run("function main(): void { let c = console; }");
        assert!(
            diags.is_empty(),
            "console-as-value should typecheck cleanly, got: {diags:?}"
        );
    }

    #[test]
    fn console_log_member_call_resolves_to_variadic_method() {
        let (ta, diags) = run(r#"function main(): void { console.log("hi"); }"#);
        assert!(diags.is_empty(), "expected clean typecheck, got {diags:?}");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected block body");
        };
        let TypedStmtKind::Expr(call_id) = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected expression statement");
        };
        let TypedExprKind::GenericMethodCall { name, args, .. } =
            &ta.try_expr(*call_id).unwrap().kind
        else {
            panic!(
                "expected GenericMethodCall, got {:?}",
                ta.try_expr(*call_id).unwrap().kind,
            );
        };
        assert_eq!(name.name, "log");
        assert_eq!(args.len(), 2);
        assert!(args[0].is_generic);
        let rest = args[1].expr;
        let TypedExprKind::ArrayLiteral { elements, .. } = &ta.try_expr(rest).unwrap().kind else {
            panic!(
                "expected packed rest ArrayLiteral, got {:?}",
                ta.try_expr(rest).unwrap().kind
            );
        };
        assert!(elements.is_empty());
    }

    #[test]
    fn console_log_multi_arg_packs_rest_array() {
        let (ta, diags) = run(r#"function main(): void { console.log("a", 1, true); }"#);
        assert!(diags.is_empty(), "expected clean typecheck, got {diags:?}");
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected block body");
        };
        let TypedStmtKind::Expr(call_id) = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected expression statement");
        };
        let TypedExprKind::GenericMethodCall { name, args, .. } =
            &ta.try_expr(*call_id).unwrap().kind
        else {
            panic!(
                "expected GenericMethodCall, got {:?}",
                ta.try_expr(*call_id).unwrap().kind,
            );
        };
        assert_eq!(name.name, "log");
        assert_eq!(args.len(), 2);
        assert!(args[0].is_generic);
        let rest = args[1].expr;
        let TypedExprKind::ArrayLiteral {
            elements,
            element_ty,
        } = &ta.try_expr(rest).unwrap().kind
        else {
            panic!(
                "expected packed rest ArrayLiteral, got {:?}",
                ta.try_expr(rest).unwrap().kind
            );
        };
        assert_eq!(elements.len(), 2);
        assert_eq!(*element_ty, Type::Unknown);
    }

    #[test]
    fn console_log_rejects_zero_args() {
        let (_, diags) = run("function main(): void { console.log(); }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("method `log` expects 1+ argument(s), got 0")),
            "expected zero-arg console.log diagnostic, got {diags:?}"
        );
    }

    // ----------------------- Equality -----------------------

    #[test]
    fn mixed_type_equality_rejected() {
        let (_, diags) = run(
            r#"function main(): void { let n: number = 1; let s: string = "1"; let b = n === s; }"#,
        );
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("expected `number`")),
            "expected mixed-type equality diagnostic, got: {diags:?}"
        );
    }

    // ============================================================
    // Arrow function inference
    // ============================================================

    /// Pull a `Closure` typed-expr out of `function main(): void { let f = <arrow>; }`.
    fn closure_in_main_let(ta: &TypedAst) -> (Vec<TypedParam>, Type, ClosureBody) {
        let main_fn = ta
            .functions
            .iter()
            .find(|f| f.name.name == "main")
            .expect("main not found");
        let body_id = main_fn.body;
        let stmts = match &ta.try_stmt(body_id).unwrap().kind {
            TypedStmtKind::Block(stmts) => stmts.clone(),
            _ => panic!("expected block body"),
        };
        let let_stmt = stmts
            .into_iter()
            .find(|&sid| {
                matches!(
                    &ta.try_stmt(sid).unwrap().kind,
                    TypedStmtKind::Let { .. } | TypedStmtKind::Const { .. }
                )
            })
            .expect("expected let/const in main body");
        let value = match &ta.try_stmt(let_stmt).unwrap().kind {
            TypedStmtKind::Let { value, .. } | TypedStmtKind::Const { value, .. } => *value,
            _ => unreachable!(),
        };
        let expr = ta.try_expr(value).unwrap();
        match &expr.kind {
            TypedExprKind::Closure {
                params,
                return_type,
                body,
                ..
            } => (params.clone(), return_type.clone(), body.clone()),
            other => panic!("expected Closure, got {other:?}"),
        }
    }

    #[test]
    fn arrow_with_typed_param_infers_expr_body_return() {
        let ta = run_clean("function main(): void { let f = (x: number) => x * 2; }");
        let (params, ret, _body) = closure_in_main_let(&ta);
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].ty, Type::Number);
        assert_eq!(ret, Type::Number);
    }

    #[test]
    fn arrow_with_typed_param_block_body_unifies_single_return() {
        let ta = run_clean("function main(): void { let f = (x: number) => { return x * 2; }; }");
        let (_params, ret, _body) = closure_in_main_let(&ta);
        assert_eq!(ret, Type::Number);
    }

    #[test]
    fn arrow_block_body_two_compatible_returns_unifies() {
        let ta = run_clean(
            "function main(): void { let f = (x: number) => { if (x > 0) { return x; } return 0; }; }",
        );
        let (_params, ret, _body) = closure_in_main_let(&ta);
        assert_eq!(ret, Type::Number);
    }

    #[test]
    fn arrow_block_body_conflicting_returns_errors() {
        let (_, diags) = run(
            r#"function main(): void { let f = (x: number) => { if (x > 0) { return x; } return "y"; }; }"#,
        );
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("conflicts with earlier return")),
            "expected conflicting-return diagnostic, got: {diags:?}"
        );
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("annotate the closure's return type")),
            "expected a fix in the diagnostic, got: {diags:?}"
        );
    }

    #[test]
    fn arrow_bare_ident_without_hint_errors() {
        let (_, diags) = run("function main(): void { let f = x => x; }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("requires a type annotation")),
            "expected `parameter requires a type annotation`, got: {diags:?}"
        );
    }

    #[test]
    fn arrow_with_explicit_return_annotation_used() {
        let ta = run_clean("function main(): void { let f = (x: number): number => x; }");
        let (_params, ret, _body) = closure_in_main_let(&ta);
        assert_eq!(ret, Type::Number);
    }

    #[test]
    fn arrow_block_body_void_when_no_returns() {
        let ta = run_clean(
            "function main(): void { let f = (x: number) => { console.log(x.toString()); }; }",
        );
        let (_params, ret, _body) = closure_in_main_let(&ta);
        assert_eq!(ret, Type::Void);
    }

    /// A failing field read that is itself a method call's receiver used to be
    /// reported twice: the method-dispatch path infers the receiver, and the
    /// fall-through then re-infers the whole callee. Presence is not the property
    /// under test — the count is, which no fixture directive can express.
    #[test]
    fn failing_receiver_of_a_method_call_reports_once() {
        let (_, diags) =
            run("function main(): string { let n: number = 3; return n.nope.toString(); }");
        let reads = diags
            .iter()
            .filter(|d| d.message.contains("cannot read field `nope`"))
            .count();
        assert_eq!(reads, 1, "expected one read diagnostic, got {diags:?}");
    }

    /// The arguments of a call on a poisoned receiver are still walked, so a real
    /// error in one is not lost with the duplicate.
    #[test]
    fn poisoned_receiver_still_checks_its_arguments() {
        let (_, diags) =
            run("function main(): string { let n: number = 3; return n.nope.toString(missing); }");
        assert!(
            diags.iter().any(|d| d.message.contains("missing")),
            "argument diagnostic lost: {diags:?}"
        );
    }

    // ============================================================
    // `unknown` rejection diagnostics
    // ============================================================

    #[test]
    fn field_access_on_unknown_diagnoses() {
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = x.length; }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("cannot read field `length` on `unknown`")),
            "expected field-on-unknown diag, got: {diags:?}",
        );
        assert!(
            diags
                .iter()
                .any(|d| d.help.iter().any(|h| h.contains("narrow first"))),
            "expected narrow-first help, got: {diags:?}",
        );
    }

    #[test]
    fn index_access_on_unknown_diagnoses() {
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = x[0]; }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("cannot index into `unknown`")),
            "expected index-on-unknown diag, got: {diags:?}",
        );
    }

    #[test]
    fn call_on_unknown_diagnoses() {
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = x(); }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("cannot call value of type `unknown`")),
            "expected call-on-unknown diag, got: {diags:?}",
        );
    }

    #[test]
    fn add_on_unknown_diagnoses() {
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = x + 1; }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("cannot apply `+` to `unknown`")),
            "expected add-on-unknown diag, got: {diags:?}",
        );
    }

    #[test]
    fn arithmetic_on_unknown_diagnoses() {
        for op in ["-", "*", "/", "%"] {
            let src = format!("function main(): void {{ let x: unknown = 1; let y = x {op} 1; }}");
            let (_, diags) = run(&src);
            assert!(
                diags.iter().any(|d| d
                    .message
                    .contains(&format!("cannot apply `{op}` to `unknown`"))),
                "{op}: expected unknown-arith diag, got: {diags:?}",
            );
        }
    }

    #[test]
    fn ordering_on_unknown_diagnoses() {
        for op in ["<", ">", "<=", ">="] {
            let src = format!("function main(): void {{ let x: unknown = 1; let y = x {op} 1; }}");
            let (_, diags) = run(&src);
            assert!(
                diags.iter().any(|d| d
                    .message
                    .contains(&format!("cannot apply `{op}` to `unknown`"))),
                "{op}: expected unknown-ordering diag, got: {diags:?}",
            );
        }
    }

    #[test]
    fn boolean_context_on_unknown_diagnoses() {
        // `if (x)` where `x: unknown` rejects with a "narrow first"
        // hint, not a generic "expected boolean" mismatch.
        let (_, diags) = run("function main(): void { let x: unknown = 1; if (x) { } }");
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("cannot use `unknown` as a condition")),
            "expected unknown-as-condition diag, got: {diags:?}",
        );
        // `&&` operand:
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = x && true; }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("cannot use `unknown` in a boolean context")),
            "expected unknown-in-bool diag, got: {diags:?}",
        );
        // Unary `!`:
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = !x; }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("cannot use `unknown` in a boolean context")),
            "expected unknown-in-not diag, got: {diags:?}",
        );
    }

    #[test]
    fn unary_arithmetic_on_unknown_diagnoses() {
        let (_, diags) = run("function main(): void { let x: unknown = 1; let y = -x; }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("cannot apply unary arithmetic to `unknown`")),
            "expected unknown-unary-arith diag, got: {diags:?}",
        );
    }

    #[test]
    fn typeof_narrowing_lets_unknown_through() {
        // typeof x === "string" narrows unknown to string; the body
        // can then use it as a string.
        let (_, diags) = run("function main(): void { let x: unknown = \"hi\"; \
             if (typeof x === \"string\") { let n: number = x.length; } }");
        assert!(
            diags.is_empty(),
            "expected clean typecheck after typeof narrowing, got: {diags:?}",
        );
    }

    #[test]
    fn anything_assigns_into_unknown() {
        // Every concrete type flows into an `unknown` slot.
        let (_, diags) = run("function main(): void { \
             let a: unknown = 1; \
             let b: unknown = \"hi\"; \
             let c: unknown = true; \
             let d: unknown = null; \
             let e: unknown = [1, 2]; }");
        assert!(
            diags.is_empty(),
            "expected all upcasts to typecheck, got: {diags:?}"
        );
    }

    #[test]
    fn cast_optional_to_required_field_suggests_narrowing() {
        // The MCP-result footgun: casting a value with an optional `foo?` field to
        // a type that requires it. Steer toward narrowing, not `as unknown as T`.
        let src = "interface Row { commit: { message: string }; } \
                   function main(): void { \
                     const x: { commit?: { message: string }; sha: string } = { sha: \"a\" }; \
                     const y = x as Row; \
                   }";
        let (_, diags) = run(src);
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("`commit` is optional on the source but required on the target")),
            "expected an optionality-specific cast error, got: {diags:?}",
        );
        assert!(
            diags.iter().any(|d| d
                .help
                .iter()
                .any(|h| h.contains("narrow the optional field"))),
            "expected a narrow-don't-cast help block, got: {diags:?}",
        );
        assert!(
            !diags
                .iter()
                .any(|d| d.message.contains("types are not related")),
            "the old misleading message must be gone: {diags:?}",
        );
    }

    #[test]
    fn cast_between_unrelated_types_keeps_the_generic_message() {
        let src = "function main(): void { \
                     const x: { a: string } = { a: \"x\" }; \
                     const y = x as { b: number }; \
                   }";
        let (_, diags) = run(src);
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("no assignable direction between these types")),
            "expected the generic unrelated-cast message, got: {diags:?}",
        );
    }

    #[test]
    fn tostring_on_unknown_typechecks() {
        // the universal `$Object`-vtable methods
        // (`toString`, `toJson`) are callable on un-narrowed
        // `unknown`. Spec §2.11.
        let (_, diags) =
            run("function main(): void { let x: unknown = 1; let s: string = x.toString(); }");
        assert!(
            diags.is_empty(),
            "expected toString on unknown to typecheck, got: {diags:?}",
        );
    }

    #[test]
    fn tojson_on_unknown_typechecks() {
        let (_, diags) =
            run("function main(): void { let x: unknown = 1; let s: string = x.toJson(); }");
        assert!(
            diags.is_empty(),
            "expected toJson on unknown to typecheck, got: {diags:?}",
        );
    }

    #[test]
    fn non_vtable_method_on_unknown_still_rejects() {
        // `length` isn't on the `$Object` vtable — still rejected
        // with the "narrow first" hint. Confirms the universal-
        // method allowlist hasn't accidentally opened the door
        // for arbitrary member access.
        let (_, diags) = run("function main(): void { let x: unknown = 1; let n = x.length; }");
        assert!(
            diags.iter().any(|d| d
                .message
                .contains("cannot read field `length` on `unknown`")),
            "expected length-on-unknown to reject, got: {diags:?}",
        );
    }

    // ----------------------- Template literals -----------------------

    /// Recursively collect every `MethodCall { name: "toString" }`
    /// reachable from `id`. Used by the elision tests below — string
    /// interpolations must produce zero such nodes; primitive
    /// interpolations must produce exactly one per slot.
    fn collect_to_string_calls(ta: &TypedAst, id: crate::ExprId) -> Vec<crate::ExprId> {
        fn walk(ta: &TypedAst, id: crate::ExprId, out: &mut Vec<crate::ExprId>) {
            let e = ta.try_expr(id).unwrap();
            if let TypedExprKind::MethodCall { name, .. } = &e.kind
                && name.name == "toString"
            {
                out.push(id);
            }
            match &e.kind {
                TypedExprKind::Binary { lhs, rhs, .. } => {
                    walk(ta, *lhs, out);
                    walk(ta, *rhs, out);
                }
                TypedExprKind::MethodCall { receiver, args, .. } => {
                    walk(ta, *receiver, out);
                    for &a in args {
                        walk(ta, a, out);
                    }
                }
                _ => {}
            }
        }
        let mut out = Vec::new();
        walk(ta, id, &mut out);
        out
    }

    #[test]
    fn template_literal_number_interpolation_wraps_in_to_string() {
        let ta = run_clean(
            r#"function main(): void { const n: number = 1; const s: string = `n=${n}`; }"#,
        );
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        // stmts[0] = const n; stmts[1] = const s
        let TypedStmtKind::Const { value, ty, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Const for s")
        };
        assert_eq!(*ty, Type::String);
        assert_eq!(ta.try_expr(*value).unwrap().ty, Type::String);
        let calls = collect_to_string_calls(&ta, *value);
        assert_eq!(
            calls.len(),
            1,
            "expected one toString call for number interpolation, got {}",
            calls.len()
        );
        // Confirm the resolved iface is the Number interface.
        let TypedExprKind::MethodCall { iface, .. } = &ta.try_expr(calls[0]).unwrap().kind else {
            unreachable!();
        };
        assert_eq!(iface.as_str(), crate::mangle::prelude("Number").as_str());
    }

    #[test]
    fn template_interpolation_conversion_spans_its_substitution() {
        let src =
            r#"function main(): void { const n: number = 1; const s: string = `a${n}${ n }`; }"#;
        let ta = run_clean(src);
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        let TypedStmtKind::Const { value, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Const for s")
        };
        let text = |span: crate::Span| &src[span.start as usize..span.end as usize];
        let spans: Vec<(&str, &str)> = collect_to_string_calls(&ta, *value)
            .into_iter()
            .map(|call| {
                let call_expr = ta.try_expr(call).unwrap();
                let TypedExprKind::MethodCall { receiver, .. } = &call_expr.kind else {
                    unreachable!();
                };
                (
                    text(call_expr.span),
                    text(ta.try_expr(*receiver).unwrap().span),
                )
            })
            .collect();
        assert_eq!(spans, vec![("${n}", "n"), ("${ n }", "n")]);
    }

    #[test]
    fn template_literal_string_interpolation_elides_to_string() {
        // The acceptance criterion: when the interpolation is
        // already string-typed, no `.toString()` wrapping is emitted.
        let ta = run_clean(
            r#"function main(): void { const x: string = "x"; const s: string = `s=${x}`; }"#,
        );
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        let TypedStmtKind::Const { value, ty, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Const for s")
        };
        assert_eq!(*ty, Type::String);
        let calls = collect_to_string_calls(&ta, *value);
        assert!(
            calls.is_empty(),
            "expected no toString call for string interpolation, got {}",
            calls.len()
        );
    }

    #[test]
    fn template_literal_boolean_interpolation_wraps_in_to_string() {
        let ta = run_clean(
            r#"function main(): void { const b: boolean = true; const s: string = `b=${b}`; }"#,
        );
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        let TypedStmtKind::Const { value, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Const for s")
        };
        let calls = collect_to_string_calls(&ta, *value);
        assert_eq!(calls.len(), 1);
        let TypedExprKind::MethodCall { iface, .. } = &ta.try_expr(calls[0]).unwrap().kind else {
            unreachable!();
        };
        assert_eq!(iface.as_str(), crate::mangle::prelude("Boolean").as_str());
    }

    #[test]
    fn template_literal_lone_interpolation_skips_empty_parts() {
        // `` `${n}` `` has empty head and tail. After elision the
        // chain is a single operand (the toString call) — no Binary
        // wrapper.
        let ta = run_clean(
            r#"function main(): void { const n: number = 1; const s: string = `${n}`; }"#,
        );
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        let TypedStmtKind::Const { value, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
            panic!("expected Const for s")
        };
        // The top expression is the toString MethodCall itself
        // (no Binary wrapping with empty-string operands).
        match &ta.try_expr(*value).unwrap().kind {
            TypedExprKind::MethodCall { name, .. } => {
                assert_eq!(name.name, "toString");
            }
            other => panic!("expected lone MethodCall, got {other:?}"),
        }
    }

    #[test]
    fn template_literal_no_substitution_collapses_to_string_literal() {
        // No-substitution templates lower to `ExprKind::String` at the
        // parser level — by the time we reach the typechecker, they
        // are indistinguishable from `"plain"`.
        let ta = run_clean(r#"function main(): void { const s: string = `plain`; }"#);
        let body = ta.functions[0].body;
        let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
            panic!("expected Block")
        };
        let TypedStmtKind::Const { value, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
            panic!("expected Const")
        };
        assert!(matches!(
            &ta.try_expr(*value).unwrap().kind,
            TypedExprKind::String(s) if s == "plain"
        ));
    }

    #[test]
    fn template_literal_nullish_interpolation_converts_at_run_time() {
        let (typed, diags) = run(
            r#"function show(n: string | null, u: number | undefined): string { return `${n} ${u}`; }"#,
        );
        assert!(diags.is_empty(), "{diags:?}");
        let conversions = typed
            .expr_ids()
            .unwrap()
            .filter(|id| {
                matches!(
                    typed.try_expr(*id).unwrap().kind,
                    TypedExprKind::IntrinsicCall {
                        kind: crate::Intrinsic::ToString,
                        ..
                    }
                )
            })
            .count();
        assert_eq!(conversions, 2);
    }

    // ----------------------- namespace-member calls -----------------------

    /// Synthetic package exercising the three argument shapes a namespace
    /// call must bind: a trailing optional (defaulted) param, a rest param,
    /// and a generic. No stdlib package carries a rest param, so the shapes
    /// are declared directly here.
    fn ns_test_package() -> crate::PackageDeclaration {
        use crate::{DefaultValue, Param, Span, ValueKind, ValueSymbol};

        fn func(name: &str, generics: Vec<String>, params: Vec<Param>, ret: Type) -> ValueSymbol {
            ValueSymbol {
                name: name.to_string(),
                mangled_name: crate::mangle::package_symbol("test:ns", name),
                declaration_span: Span::at(crate::FileId(0)),
                kind: ValueKind::Function {
                    generics,
                    params,
                    ret,
                    type_predicate: None,
                    doc: None,
                },
            }
        }

        let mut defs = crate::PackageDeclaration::with_package("test:ns");
        defs.values.insert(
            "opt".to_string(),
            func(
                "opt",
                Vec::new(),
                vec![
                    Param::new("a", Type::Number),
                    Param::with_default("b", Type::Number, DefaultValue::Number(5.0)),
                ],
                Type::Number,
            ),
        );
        defs.values.insert(
            "sum".to_string(),
            func(
                "sum",
                Vec::new(),
                vec![Param::rest("nums", Type::Array(Box::new(Type::Number)))],
                Type::Number,
            ),
        );
        defs.values.insert(
            "identity".to_string(),
            func(
                "identity",
                vec!["T".to_string()],
                vec![Param::new("x", Type::TypeVar("T".to_string()))],
                Type::TypeVar("T".to_string()),
            ),
        );
        defs
    }

    /// First call-shaped node in the typed AST (namespace calls lower to a
    /// `Call` or, when generic, a `GenericCall`).
    fn first_call_arg_count(ta: &TypedAst) -> usize {
        for i in 0..ta.exprs_len() {
            match &ta.try_expr(crate::ExprId(i as u32)).unwrap().kind {
                TypedExprKind::Call { args, .. } => return args.len(),
                TypedExprKind::GenericCall { args, .. } => return args.len(),
                _ => {}
            }
        }
        panic!("no call node found");
    }

    #[test]
    fn namespace_call_omits_trailing_optional_arg() {
        let pkg = ns_test_package();
        let (ta, diags) = run_with_packages(
            r#"import ns from "test:ns";
               function main(): void { const r: number = ns.opt(1); }"#,
            &[&pkg],
        );
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        // the defaulted `b = 5` is synthesized, so the lowered call is arity-2.
        assert_eq!(first_call_arg_count(&ta), 2);
    }

    #[test]
    fn namespace_call_binds_rest_param() {
        let pkg = ns_test_package();
        let (ta, diags) = run_with_packages(
            r#"import ns from "test:ns";
               function main(): void { const r: number = ns.sum(1, 2, 3); }"#,
            &[&pkg],
        );
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        // the three trailing args pack into one rest array, so arity-1.
        assert_eq!(first_call_arg_count(&ta), 1);
    }

    #[test]
    fn namespace_call_to_generic_function_infers_return() {
        let pkg = ns_test_package();
        let (ta, diags) = run_with_packages(
            r#"import ns from "test:ns";
               function main(): void { const r: number = ns.identity(42); }"#,
            &[&pkg],
        );
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        // `T` binds to `number` from the argument; the call lowers to a
        // `GenericCall` (single arg, no spurious arity rejection).
        assert_eq!(first_call_arg_count(&ta), 1);
    }

    #[test]
    fn namespace_call_too_few_args_still_errors() {
        let pkg = ns_test_package();
        let (_, diags) = run_with_packages(
            r#"import ns from "test:ns";
               function main(): void { const r: number = ns.opt(); }"#,
            &[&pkg],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("argument(s), got 0")),
            "expected arity diagnostic, got: {diags:?}",
        );
    }

    /// Typecheck `source` against the real `submilli:llm` declaration.
    fn run_with_llm(source: &str) -> (TypedAst, Vec<crate::Diagnostic>) {
        let llm = crate::stdlib::llm::declaration::package_declaration();
        run_with_packages(source, &[&llm])
    }

    /// Every `llm.call`/`llm.batch` in `ta` that was wrapped in a `Cast`, as
    /// (has a structural `check`, the inner call's `return_cast`). Mirrors
    /// `session_get_shapes`.
    fn llm_call_shapes(ta: &TypedAst) -> Vec<(bool, Option<Type>)> {
        let mut out = Vec::new();
        for i in 0..ta.exprs_len() {
            let expr = ta.try_expr(crate::ExprId(i as u32)).unwrap();
            let TypedExprKind::Cast { value, check, .. } = &expr.kind else {
                continue;
            };
            let TypedExprKind::GenericCall {
                mangled,
                return_cast,
                ..
            } = &ta.try_expr(*value).unwrap().kind
            else {
                continue;
            };
            if crate::stdlib::llm::declaration::is_checked_call(mangled) {
                out.push((check.is_some(), return_cast.clone()));
            }
        }
        out
    }

    /// Every schema string that reached an `llm.call`/`llm.batch` argument
    /// list, in call order. The schema rides in the trailing `schema` slot,
    /// which the untyped form leaves as the `null` default.
    fn llm_schemas(ta: &TypedAst) -> Vec<Option<String>> {
        let mut out = Vec::new();
        for i in 0..ta.exprs_len() {
            let expr = ta.try_expr(crate::ExprId(i as u32)).unwrap();
            let TypedExprKind::GenericCall { mangled, args, .. } = &expr.kind else {
                continue;
            };
            if !crate::stdlib::llm::declaration::is_checked_call(mangled) {
                continue;
            }
            let schema = args
                .last()
                .and_then(|a| match &ta.try_expr(a.expr).unwrap().kind {
                    TypedExprKind::String(s) => Some(s.clone()),
                    _ => None,
                });
            out.push(schema);
        }
        out
    }

    const SEVERITY: &str = "interface Severity { level: string; score: number; }";

    /// R5: a typed call emits a structural test, and the schema for `T` reaches
    /// the argument list as a compile-time constant.
    #[test]
    fn typed_llm_call_emits_a_structural_test_and_a_schema() {
        let src = format!(
            "import llm from \"submilli:llm\"; {SEVERITY} \
             function main(): void {{ const s = llm.call<Severity>(\"m\", \"p\"); }}"
        );
        let (ta, diags) = run_with_llm(&src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");

        let shapes = llm_call_shapes(&ta);
        assert_eq!(shapes.len(), 1, "expected one wrapped call, got {shapes:?}");
        assert!(shapes[0].0, "call<Severity> lost its structural check");

        let schemas = llm_schemas(&ta);
        assert_eq!(schemas.len(), 1, "expected one call, got {schemas:?}");
        let schema = schemas[0].as_deref().expect("a typed call sends a schema");
        let parsed: serde_json::Value = serde_json::from_str(schema).expect("schema is JSON");
        assert_eq!(parsed["type"], "object", "schema: {schema}");
        assert_eq!(parsed["properties"]["level"]["type"], "string");
        assert_eq!(parsed["properties"]["score"]["type"], "number");
        assert!(
            !schema.contains("$ref") && !schema.contains("$defs"),
            "the schema must be fully inlined (KTD5): {schema}",
        );
    }

    /// Nested and optional fields are carried into the schema and into the
    /// check, rather than being flattened to a bare `object`.
    #[test]
    fn nested_and_optional_fields_reach_the_schema_and_the_check() {
        let src = "import llm from \"submilli:llm\"; \
                   interface Inner { tag: string; } \
                   interface Outer { inner: Inner; note?: string; } \
                   function main(): void { const o = llm.call<Outer>(\"m\", \"p\"); }";
        let (ta, diags) = run_with_llm(src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");

        let schema = llm_schemas(&ta)[0].clone().expect("schema emitted");
        let parsed: serde_json::Value = serde_json::from_str(&schema).expect("schema is JSON");
        // The nested interface is inlined in full, not referenced.
        assert_eq!(
            parsed["properties"]["inner"]["properties"]["tag"]["type"], "string",
            "nested field lost its shape: {schema}",
        );
        // An optional field is present but not required; a required-only
        // `inner` is what distinguishes the two.
        let required: Vec<&str> = parsed["required"]
            .as_array()
            .expect("required list")
            .iter()
            .map(|v| v.as_str().expect("string"))
            .collect();
        assert!(required.contains(&"inner"), "schema: {schema}");
        assert!(
            !required.contains(&"note"),
            "an optional field must not be required: {schema}",
        );

        // And the check walks the same nested shape rather than stopping at the
        // outer object.
        let shapes = llm_call_shapes(&ta);
        assert_eq!(shapes, vec![(true, None)], "shapes: {shapes:?}");
    }

    /// The soundness invariant, and the one most at risk of silently
    /// regressing: a `call<T>` must lower to a `Cast` carrying a structural
    /// check, and the call it wraps must NOT carry a `return_cast` — that is a
    /// `ref.cast`, a representation-only narrow that verifies nothing and traps
    /// uncatchably on a null response. A shape mismatch throws either way, so
    /// only this assertion distinguishes them.
    #[test]
    fn typed_llm_call_is_a_checked_cast_and_never_a_return_cast() {
        let src = format!(
            "import llm from \"submilli:llm\"; {SEVERITY} \
             function main(): void {{ const s = llm.call<Severity>(\"m\", \"p\"); }}"
        );
        let (ta, diags) = run_with_llm(&src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");

        let shapes = llm_call_shapes(&ta);
        assert_eq!(shapes.len(), 1, "expected one wrapped call, got {shapes:?}");
        assert!(shapes[0].0, "call<Severity> lost its structural check");
        assert_eq!(
            shapes[0].1, None,
            "call<Severity> kept an unsound return_cast: {shapes:?}",
        );
    }

    /// The same invariant across every import form. Interception matches the
    /// package-export mangled name, so an alias, a named import, and a
    /// namespace import must all land on the checked path identically —
    /// mirroring `fixtures/imports/session_*`.
    #[test]
    fn no_import_form_of_llm_call_keeps_a_return_cast() {
        let src = format!(
            "import llm from \"submilli:llm\"; \
             import ai from \"submilli:llm\"; \
             import {{ call }} from \"submilli:llm\"; \
             import * as everything from \"submilli:llm\"; {SEVERITY} \
             function main(): void {{ \
               const a = llm.call<Severity>(\"m\", \"p\"); \
               const b = ai.call<Severity>(\"m\", \"p\"); \
               const c = call<Severity>(\"m\", \"p\"); \
               const d = everything.call<Severity>(\"m\", \"p\"); }}"
        );
        let (ta, diags) = run_with_llm(&src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        assert_eq!(
            llm_call_shapes(&ta),
            vec![(true, None), (true, None), (true, None), (true, None)],
            "every import form must produce a checked, uncast call",
        );

        // And no raw `GenericCall` on the symbol survives with a `return_cast`,
        // whichever form produced it.
        for i in 0..ta.exprs_len() {
            let expr = ta.try_expr(crate::ExprId(i as u32)).unwrap();
            if let TypedExprKind::GenericCall {
                mangled,
                return_cast,
                ..
            } = &expr.kind
                && crate::stdlib::llm::declaration::is_checked_call(mangled)
            {
                assert_eq!(*return_cast, None, "an llm call kept a return_cast");
            }
        }
    }

    /// Every import form also emits the same schema — the interception is not
    /// keyed on the receiver, so an aliased or namespace import must not
    /// silently fall through to the untyped path.
    #[test]
    fn every_import_form_emits_the_same_schema() {
        let src = format!(
            "import llm from \"submilli:llm\"; \
             import ai from \"submilli:llm\"; \
             import {{ call }} from \"submilli:llm\"; \
             import * as everything from \"submilli:llm\"; {SEVERITY} \
             function main(): void {{ \
               const a = llm.call<Severity>(\"m\", \"p\"); \
               const b = ai.call<Severity>(\"m\", \"p\"); \
               const c = call<Severity>(\"m\", \"p\"); \
               const d = everything.call<Severity>(\"m\", \"p\"); }}"
        );
        let (ta, diags) = run_with_llm(&src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");

        let schemas = llm_schemas(&ta);
        assert_eq!(schemas.len(), 4, "expected four calls, got {schemas:?}");
        let first = schemas[0].as_deref().expect("a typed call sends a schema");
        for (i, s) in schemas.iter().enumerate() {
            assert_eq!(
                s.as_deref(),
                Some(first),
                "import form {i} emitted a different schema",
            );
        }
    }

    /// `batch<T[]>` takes the same path: a checked cast, no `return_cast`, and
    /// a schema for the whole result.
    #[test]
    fn typed_llm_batch_is_a_checked_cast_too() {
        let src = format!(
            "import llm from \"submilli:llm\"; {SEVERITY} \
             function main(): void {{ const s = llm.batch<Severity[]>(\"m\", [\"p\"]); }}"
        );
        let (ta, diags) = run_with_llm(&src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        assert_eq!(llm_call_shapes(&ta), vec![(true, None)]);

        let schema = llm_schemas(&ta)[0].clone().expect("schema emitted");
        let parsed: serde_json::Value = serde_json::from_str(&schema).expect("schema is JSON");
        assert_eq!(parsed["type"], "array", "schema: {schema}");
        assert_eq!(parsed["items"]["properties"]["level"]["type"], "string");
    }

    /// R7, and the distinction the `type_args_written` flag exists for: a bare
    /// `call(...)` is not an error — it keeps its pre-generic meaning and
    /// returns the `Completion` envelope, unwrapped and unschema'd.
    #[test]
    fn untyped_llm_call_returns_the_completion_envelope_without_erroring() {
        let src = "import llm from \"submilli:llm\"; \
                   function main(): void { const c = llm.call(\"m\", \"p\"); \
                                           const t = c.text; }";
        let (ta, diags) = run_with_llm(src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
        assert!(
            llm_call_shapes(&ta).is_empty(),
            "an untyped call must not be wrapped in a checked cast",
        );
        assert_eq!(
            llm_schemas(&ta),
            vec![None],
            "an untyped call must send no schema",
        );
    }

    /// The untyped `batch` likewise keeps its `Completion[]` envelope, so a
    /// per-element `ok` is still readable.
    #[test]
    fn untyped_llm_batch_returns_completion_array() {
        let src = "import llm from \"submilli:llm\"; \
                   function main(): void { const r = llm.batch(\"m\", [\"p\"]); \
                                           const ok = r[0].ok; }";
        let (_, diags) = run_with_llm(src);
        assert!(diags.is_empty(), "unexpected diags: {diags:?}");
    }

    /// R7: a *written* `<unknown>` is the error, because it asks for a check
    /// that cannot exist and a schema that would constrain nothing.
    #[test]
    fn written_unknown_type_argument_is_rejected() {
        let src = "import llm from \"submilli:llm\"; \
                   function main(): void { const v = llm.call<unknown>(\"m\", \"p\"); }";
        let (_, diags) = run_with_llm(src);
        let d = diags
            .iter()
            .find(|d| d.message.contains("llm.call<unknown>"))
            .unwrap_or_else(|| panic!("expected an unknown rejection, got: {diags:?}"));
        assert!(
            d.message.contains("admits every value"),
            "message must say why: {}",
            d.message,
        );
        assert!(
            d.help.iter().any(|h| h.contains("llm.call<Severity>")),
            "help must show the fix: {:?}",
            d.help,
        );
    }

    /// R7: `call<T>` inside a user generic. The reason is
    /// `unsupported_cast_target_reason`'s erasure arm verbatim — the same text
    /// `as` and MCP produce — and the `help:` names the fix.
    #[test]
    fn type_argument_erased_by_a_user_generic_is_rejected() {
        let src = "import llm from \"submilli:llm\"; \
                   function pick<T>(): T { return llm.call<T>(\"m\", \"p\"); } \
                   function main(): void { const n = pick<number>(); }";
        let (_, diags) = run_with_llm(src);
        let d = diags
            .iter()
            .find(|d| d.message.contains("cannot be verified at runtime"))
            .unwrap_or_else(|| panic!("expected an erasure rejection, got: {diags:?}"));
        assert!(
            d.message
                .contains("generic type parameters are erased at runtime"),
            "must reuse the shared erasure reason verbatim: {}",
            d.message,
        );
        assert!(
            d.help
                .iter()
                .any(|h| h.contains("emitted at compile time") && h.contains("llm.call<Severity>")),
            "help must explain the erasure and name the fix: {:?}",
            d.help,
        );
    }

    /// KTD5: the schema surface is strictly narrower than the cast surface. A
    /// `Uint8Array` field is a legal `as` target and has no JSON form, so only
    /// the schema gate catches it — and the diagnostic names the field.
    #[test]
    fn a_type_outside_the_schema_surface_is_rejected_naming_the_field() {
        let src = "import llm from \"submilli:llm\"; \
                   interface Blob { blob: Uint8Array; } \
                   function main(): void { const b = llm.call<Blob>(\"m\", \"p\"); }";
        let (_, diags) = run_with_llm(src);
        let d = diags
            .iter()
            .find(|d| d.message.contains("has no JSON Schema"))
            .unwrap_or_else(|| panic!("expected a schema rejection, got: {diags:?}"));
        assert!(
            d.message.contains("field `blob`"),
            "the diagnostic must name the offending field: {}",
            d.message,
        );

        // Control: the same type IS accepted by the cast gate, which is what
        // makes the second gate load-bearing rather than redundant.
        let cast_src = "interface Blob { blob: Uint8Array; } \
                        function main(): void { const v: unknown = null; const b = v as Blob; }";
        let (_, cast_diags) = run(cast_src);
        assert!(
            cast_diags.is_empty(),
            "`as Blob` must still be legal — otherwise the schema gate proves nothing: \
             {cast_diags:?}",
        );
    }

    /// A recursive type has no finite inlining, and the reject names the field
    /// that closes the cycle rather than only the type.
    #[test]
    fn a_recursive_type_is_rejected_naming_the_closing_field() {
        let src = "import llm from \"submilli:llm\"; \
                   interface Node { value: string; next: Node | null; } \
                   function main(): void { const n = llm.call<Node>(\"m\", \"p\"); }";
        let (_, diags) = run_with_llm(src);
        let d = diags
            .iter()
            .find(|d| d.message.contains("has no JSON Schema"))
            .unwrap_or_else(|| panic!("expected a schema rejection, got: {diags:?}"));
        assert!(
            d.message.contains("field `next`"),
            "must name the field that closes the cycle: {}",
            d.message,
        );
    }

    /// A `Type::Error` has already reported its own diagnostic. The schema
    /// emitter still rejects it — there is no schema — but the rejection is
    /// `cascading` and must stay silent rather than blame the same mistake
    /// twice.
    #[test]
    fn a_cascading_schema_reject_emits_no_second_diagnostic() {
        let src = "import llm from \"submilli:llm\"; \
                   function main(): void { const x = llm.call<NoSuchType>(\"m\", \"p\"); }";
        let (_, diags) = run_with_llm(src);
        assert!(
            !diags
                .iter()
                .any(|d| d.message.contains("has no JSON Schema")),
            "an already-failed type must not cascade a schema diagnostic: {diags:?}",
        );
        assert_eq!(
            diags.len(),
            1,
            "exactly the original unresolved-type diagnostic: {diags:?}",
        );
    }
}

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

    #[test]
    fn mismatched_template_and_nonnull_dispatch_return_internal_errors() {
        super::super::test_support::with_inferer(|tc| {
            let span = Span::at(crate::FileId(0));
            assert!(matches!(
                tc.lower_template_literal(Vec::new(), Vec::new(), Vec::new(), None, span),
                Err(CompilerFailure::Internal { .. })
            ));
            let part = ChainPart::NonNull { span };
            assert!(matches!(
                chain_step_phrasing(&part),
                Err(CompilerFailure::Internal { .. })
            ));
            assert!(matches!(
                namespace_fix_forms("Math", &part),
                Err(CompilerFailure::Internal { .. })
            ));
        });
    }
}

/// Whether `ty` holds an error type anywhere a cast compares, as `<error>[]` does.
fn has_error_component(ty: &Type) -> bool {
    match ty.peel() {
        Type::Error => true,
        Type::Array(inner) => has_error_component(inner),
        Type::Tuple(members) => members.iter().any(has_error_component),
        Type::Union(members) => members.iter().any(has_error_component),
        _ => false,
    }
}