bock-codegen 1.0.0

Multi-target code generation for Bock — JS, TS, Python, Rust, Go
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
//! TypeScript code generator — rule-based (Tier 2) transpilation from AIR to TS.
//!
//! Extends the JavaScript codegen with:
//! - Type annotations on parameters, return types, and bindings
//! - Generics → TS generics (preserved, not erased)
//! - Traits → TS interfaces
//! - Algebraic types → discriminated union types + tagged objects
//! - Type aliases → `type X = ...`

use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::path::PathBuf;

use bock_air::{AIRNode, AirInterpolationPart, EnumVariantPayload, NodeKind, ResultVariant};
use bock_ast::{AssignOp, BinOp, Literal, TypeExpr, UnaryOp, Visibility};
use bock_errors::Span;
use bock_types::AIRModule;

use crate::error::CodegenError;
use crate::generator::{CodeGenerator, GeneratedCode, OutputFile, SourceMap, SourceMapping};
use crate::profile::TargetProfile;

/// Runtime helpers injected when `Channel` / `spawn` appear in a module.
/// See the analogous `CONCURRENCY_RUNTIME_JS` in `js.rs`.
/// Conservative module scan — if the serialized AIR mentions `Channel`
/// or `spawn`, emit the runtime prelude. Unused helpers are trivially
/// dead-code eliminated by downstream TS tooling.
fn module_uses_concurrency(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let s = format!("{n:?}");
        s.contains("\"Channel\"") || s.contains("\"spawn\"")
    })
}

/// Runtime type for Bock `Optional[T]` in TypeScript. The *value*
/// representation is a tagged object — `{ _tag: "Some", _0: v }` or
/// `{ _tag: "None" }` (see [`TsEmitCtx::try_emit_prelude_ctor`] and the `None`
/// identifier in [`TsEmitCtx::emit_expr`]) — so the *type* must be the matching
/// discriminated union, not `T | null`. This mirrors the Go `__bockOption`
/// runtime added in the codegen-correctness workstream: type and value agree,
/// a `match` lowered to `switch (x._tag)` narrows correctly, and the two-variant
/// union is provably exhaustive (so a `string`-returning match needs no
/// `default`).
const OPTIONAL_RUNTIME_TS: &str = "\
// ── Bock Optional runtime ──
type BockOption<T> =
  | { readonly _tag: \"Some\"; readonly _0: T }
  | { readonly _tag: \"None\" };
";

/// True if the module references `Optional`, `Some`, or `None` anywhere — or
/// calls `pop`, whose DQ30 lowering produces a `BockOption<T>`-typed IIFE —
/// so the Optional runtime type prelude must be emitted. A cheap structural
/// scan over the debug rendering, mirroring [`module_uses_concurrency`] and
/// the Go backend's `go_module_uses_optional`. Over-matching (e.g. a user
/// method named `pop`) only emits/imports an unused type alias, which is
/// harmless under the scaffolded tsconfig.
fn module_uses_optional(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let s = format!("{n:?}");
        s.contains("\"Optional\"")
            || s.contains("TypeOptional")
            || s.contains("\"Some\"")
            || s.contains("\"None\"")
            || s.contains("\"pop\"")
    })
}

/// Runtime type for Bock `Result[T, E]` in TypeScript. The value representation
/// is a tagged object — `{ _tag: "Ok", _0: v }` or `{ _tag: "Err", _0: e }`
/// (see [`TsEmitCtx::try_emit_prelude_ctor`], the `ResultConstruct` arm, and the
/// `Result`-match lowering) — so the type is the matching discriminated union,
/// not the structural `Ok`/`Err` aliases that previously went undefined. Both
/// arms carry the payload under the same `_0` key the match reads, so a `match r
/// { Ok(v) => …; Err(e) => … }` lowered to `switch (r._tag)` narrows correctly
/// and the two-variant union is provably exhaustive (no `default` needed). This
/// mirrors [`OPTIONAL_RUNTIME_TS`].
const RESULT_RUNTIME_TS: &str = "\
// ── Bock Result runtime ──
type BockResult<T, E> =
  | { readonly _tag: \"Ok\"; readonly _0: T }
  | { readonly _tag: \"Err\"; readonly _0: E };
";

/// True if the module references `Result`, `Ok`, or `Err` anywhere, so the
/// `Result` runtime type prelude must be emitted. Mirrors [`module_uses_optional`].
fn module_uses_result(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let s = format!("{n:?}");
        s.contains("\"Result\"")
            || s.contains("ResultConstruct")
            || s.contains("\"Ok\"")
            || s.contains("\"Err\"")
    })
}

const CONCURRENCY_RUNTIME_TS: &str = "\
// ── Bock concurrency runtime ──
type __BockChannel<T> = {
  send(v: T): void;
  recv(): Promise<T>;
  close(): void;
};
const __bockChannelNew = <T>(): [__BockChannel<T>, __BockChannel<T>] => {
  const queue: T[] = [];
  const waiters: Array<(v: T) => void> = [];
  const ch: __BockChannel<T> = {
    send(v: T) {
      if (waiters.length > 0) { waiters.shift()!(v); } else { queue.push(v); }
    },
    recv(): Promise<T> {
      return new Promise<T>((resolve) => {
        if (queue.length > 0) { resolve(queue.shift()!); }
        else { waiters.push(resolve); }
      });
    },
    close() {}
  };
  return [ch, ch];
};
const __bockSpawn = <T>(x: Promise<T>): Promise<T> => x;
";

/// Runtime helpers for Bock range expressions (`0..n` / `0..=n`) in TypeScript.
/// TS has no native range value, so `for i in 0..n` lowers to
/// `for (const i of range(0, n))`. `range` is half-open, `rangeInclusive`
/// inclusive — matching Python's `range(lo, hi)` / `range(lo, hi + 1)` and
/// Rust's `lo..hi` / `lo..=hi`. Emitted once into the shared `_bock_runtime.ts`
/// (per-module path) or inlined at most once (single-module path), gated on a
/// ctx flag (mirrors [`OPTIONAL_RUNTIME_TS`]).
const RANGE_RUNTIME_TS: &str = "\
// ── Bock range runtime ──
const range = (lo: number, hi: number): number[] => { const r: number[] = []; for (let i = lo; i < hi; i++) r.push(i); return r; };
const rangeInclusive = (lo: number, hi: number): number[] => { const r: number[] = []; for (let i = lo; i <= hi; i++) r.push(i); return r; };
";

/// True if the module references a `Range` node anywhere (so the range runtime
/// prelude must be emitted). Mirrors [`module_uses_optional`]. `RangePat` does
/// not contain the `Range {` substring, so match-arm range patterns do not
/// trigger the (value-only) helpers.
fn module_uses_range(items: &[AIRNode]) -> bool {
    items.iter().any(|n| format!("{n:?}").contains("Range {"))
}

/// Runtime helper for DQ29 structural equality in TypeScript — the typed twin
/// of the JS backend's `__bockEq` (see `EQ_RUNTIME_JS` in `js.rs` for the full
/// semantics): `===` on two objects is reference identity, so every stamped
/// `==`/`!=` (lanes `"structural"`/`"deep"`/`"generic"` of
/// [`crate::generator::user_eq_kind`]) and every `a.eq(b)` bridge call on an
/// `Equatable`-bounded generic lowers through this deep, order-independent
/// (for `Map`/`Set`), explicit-impl-honoring comparison. Non-objects fall back
/// to `===`, preserving IEEE `NaN !== NaN`. Emitted once into the shared
/// `_bock_runtime.ts` (per-module path) or inlined at most once
/// (single-module path), gated on a ctx flag (mirrors [`RANGE_RUNTIME_TS`]).
const EQ_RUNTIME_TS: &str = "\
// ── Bock structural equality runtime ──
const __bockEq = (a: unknown, b: unknown): boolean => {
  if (a === b) return true;
  if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {
    return a === b;
  }
  const ea = (a as { eq?: unknown }).eq;
  const eb = (b as { eq?: unknown }).eq;
  if (typeof ea === \"function\" && typeof eb === \"function\") {
    return (ea as (s: unknown, o: unknown) => boolean).call(a, a, b);
  }
  if (Array.isArray(a)) {
    if (!Array.isArray(b) || a.length !== b.length) return false;
    for (let i = 0; i < a.length; i++) { if (!__bockEq(a[i], b[i])) return false; }
    return true;
  }
  if (a instanceof Map) {
    if (!(b instanceof Map) || a.size !== b.size) return false;
    for (const [k, v] of a) {
      if (b.has(k)) { if (!__bockEq(b.get(k), v)) return false; continue; }
      let found = false;
      for (const [bk, bv] of b) { if (__bockEq(k, bk) && __bockEq(v, bv)) { found = true; break; } }
      if (!found) return false;
    }
    return true;
  }
  if (a instanceof Set) {
    if (!(b instanceof Set) || a.size !== b.size) return false;
    for (const x of a) {
      if (b.has(x)) continue;
      let found = false;
      for (const y of b) { if (__bockEq(x, y)) { found = true; break; } }
      if (!found) return false;
    }
    return true;
  }
  const ra = a as Record<string, unknown>;
  const rb = b as Record<string, unknown>;
  const ka = Object.keys(ra);
  const kb = Object.keys(rb);
  if (ka.length !== kb.length) return false;
  for (const k of ka) { if (!__bockEq(ra[k], rb[k])) return false; }
  return true;
};
";

/// True if the module contains an equality that must lower through
/// [`EQ_RUNTIME_TS`]'s `__bockEq` — a non-`"impl"` `user_eq` stamp or an
/// `Equatable`-bounded bridge call. Mirrors the JS backend's scan (see
/// `js_module_uses_eq` in `js.rs`).
fn module_uses_eq(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let dbg = format!("{n:?}");
        dbg.contains("\"user_eq\": String(\"structural\")")
            || dbg.contains("\"user_eq\": String(\"deep\")")
            || dbg.contains("\"user_eq\": String(\"deep_custom\")")
            || dbg.contains("\"user_eq\": String(\"generic\")")
            || dbg.contains("TraitBound:Equatable")
    })
}

/// The structural comparison runtime: lower a bounded `T: Comparable`'s
/// `a.compare(b)` through this so it dispatches to the instantiated type's own
/// `compare` method when present (a record/enum carrying an `impl Comparable`),
/// falling back to the native ternary for a primitive instantiation. Without it
/// the bounded bridge emitted the native ternary unconditionally, so `(a) < (b)`
/// on two RECORDS is always `false` and `(a) === (b)` is reference identity —
/// every comparison wrongly returned `Greater`, mis-ordering `max`/`min`/sort
/// over a user `Comparable` type. The emitted `compare` method takes
/// `(self, other)`, so the helper calls `a.compare(a, b)`. Mirrors
/// [`EQ_RUNTIME_TS`]'s `__bockEq`. (Q-bounded-comparable-codegen.)
const COMPARE_RUNTIME_TS: &str = "// ── Bock structural comparison runtime ──
type __BockOrdering = { _tag: \"Less\" } | { _tag: \"Equal\" } | { _tag: \"Greater\" };
const __bockCompare = (a: any, b: any): __BockOrdering => {
  if (a !== null && typeof a === \"object\" && typeof a.compare === \"function\") {
    return a.compare(a, b);
  }
  return (a < b ? { _tag: \"Less\" } : (a === b ? { _tag: \"Equal\" } : { _tag: \"Greater\" }));
};
";

/// True if the module contains a bounded `T: Comparable` `compare` bridge call,
/// so [`COMPARE_RUNTIME_TS`]'s `__bockCompare` must be emitted. Mirrors
/// [`module_uses_eq`].
fn module_uses_compare(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let dbg = format!("{n:?}");
        dbg.contains("TraitBound:Comparable")
    })
}

/// The display-string runtime: lower a `${expr}` interpolation part through this
/// so a user value with a `Displayable` impl (its emitted `to_string` method) is
/// rendered via that method, not the structural `[object Object]`. Primitives /
/// arrays / plain objects fall back to native `String(x)`. The user `to_string`
/// is `T.prototype.to_string = function(self) { … }` (snake_case, distinct from
/// JS `toString`), so the helper detects it by `typeof x.to_string ===
/// "function"` and calls `x.to_string(x)`. Mirrors `STR_RUNTIME_JS` in `js.rs`.
/// (Q-displayable-interpolation-dispatch.)
const STR_RUNTIME_TS: &str = "// ── Bock display-string runtime ──
const __bockStr = (x: any): string => {
  if (x !== null && typeof x === \"object\" && typeof x.to_string === \"function\") {
    return x.to_string(x);
  }
  return String(x);
};
";

/// True if the module contains a string interpolation (`${expr}`), so
/// [`STR_RUNTIME_TS`]'s `__bockStr` must be emitted. Mirrors [`module_uses_eq`].
fn module_uses_str(items: &[AIRNode]) -> bool {
    items.iter().any(|n| {
        let dbg = format!("{n:?}");
        dbg.contains("Interpolation")
    })
}

/// The shared per-module runtime module name (without extension). In the
/// per-module (native-import) emission path the Optional/Result runtime *types*
/// (`BockOption`, `BockResult`) and the concurrency / range runtime *helpers*
/// (`__bockChannelNew`, `range`, …) live in one file — `_bock_runtime.ts` at
/// the build root — and every emitted module imports the names it references.
/// A single shared definition avoids redeclaring `type BockOption` / `const
/// range` across files (a TS redeclaration error).
const RUNTIME_MODULE_TS: &str = "_bock_runtime";
#[derive(Debug)]
pub struct TsGenerator {
    profile: TargetProfile,
}

impl TsGenerator {
    /// Creates a new TypeScript code generator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            profile: TargetProfile::typescript(),
        }
    }
}

impl Default for TsGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl CodeGenerator for TsGenerator {
    fn target(&self) -> &TargetProfile {
        &self.profile
    }

    fn generate_module(&self, module: &AIRModule) -> Result<GeneratedCode, CodegenError> {
        // Shared pre-pass: hoist value-position diverging control flow (see
        // `hoist_value_cf`) into declare-then-assign temp blocks.
        let module =
            &crate::generator::hoist_value_cf(crate::generator::lower_blanket_into(module.clone()));
        let mut ctx = TsEmitCtx::new();
        ctx.enum_variants =
            crate::generator::collect_enum_variants(&[(module, std::path::Path::new(""))]);
        ctx.generic_decls =
            crate::generator::collect_generic_decls(&[(module, std::path::Path::new(""))]);
        ctx.trait_decls =
            crate::generator::collect_trait_decls(&[(module, std::path::Path::new(""))]);
        ctx.exported_types =
            crate::generator::collect_exported_type_names(&[(module, std::path::Path::new(""))]);
        ctx.class_fields =
            crate::generator::collect_class_fields(&[(module, std::path::Path::new(""))]);
        ctx.const_names =
            crate::generator::collect_const_names(&[(module, std::path::Path::new(""))]);
        ctx.emit_node(module)?;
        let (content, mappings) = ctx.finish();
        let source_map = SourceMap {
            generated_file: String::new(),
            mappings,
            ..Default::default()
        };
        Ok(GeneratedCode {
            files: vec![OutputFile {
                path: PathBuf::new(),
                content,
                source_map: Some(source_map),
            }],
        })
    }

    fn entry_invocation(&self, main_is_async: bool) -> Option<String> {
        if main_is_async {
            Some("(async () => { await main(); })();\n".to_string())
        } else {
            Some("main();\n".to_string())
        }
    }

    /// Emit a per-module **native ES-module import tree** (spec §20.6.1; DQ19
    /// resolved): each reachable module → its own `.ts` file, cross-module
    /// references resolved with real ESM `import`/`import type`. Mirrors the JS
    /// backend's per-module path (see [`crate::js`]) plus TS's type level:
    /// Optional/Result runtime *types* and concurrency/range runtime *helpers*
    /// are emitted once into a shared `_bock_runtime.ts`, imported per file. The
    /// minimal `package.json` `{"type":"module"}` run affordance — which makes
    /// the `.ts` source tree run under `node --experimental-strip-types` — is
    /// emitted by the **scaffolder** in project mode (S6a / DV18), not by codegen,
    /// so `--source-only` output is bare source.
    ///
    /// Output-path mapping is keyed on each module's *declared* path
    /// (`module core.option` ⇒ `core/option.ts`, imported `"./core/option.ts"` —
    /// ESM specifiers reference the *emitted* `.ts` source directly so node
    /// strip-types resolves them verbatim; `tsc` accepts the `.ts` extension via
    /// `rewriteRelativeImportExtensions`, which also rewrites it to `.js` on
    /// emit). The entry module is always `main.ts`.
    fn generate_project(
        &self,
        modules: &[(&AIRModule, &std::path::Path)],
    ) -> Result<GeneratedCode, CodegenError> {
        // Shared pre-pass: hoist value-position diverging control flow on every
        // module before registry collection or emission (see `hoist_value_cf`).
        let hoisted: Vec<(AIRModule, &std::path::Path)> = modules
            .iter()
            .map(|(m, p)| {
                (
                    crate::generator::hoist_value_cf(crate::generator::lower_blanket_into(
                        (*m).clone(),
                    )),
                    *p,
                )
            })
            .collect();
        let modules: Vec<(&AIRModule, &std::path::Path)> =
            hoisted.iter().map(|(m, p)| (m, *p)).collect();
        let modules = modules.as_slice();
        // Emit only modules the entry program actually `use`s (plus the entry
        // itself), dependency-ordered — never the prelude-only stdlib.
        let reachable = crate::generator::reachable_modules(modules);
        let modules = reachable.as_slice();
        if modules.is_empty() {
            return Ok(GeneratedCode { files: vec![] });
        }

        let entry_idx = modules
            .iter()
            .position(|(m, _)| crate::generator::module_declares_main_fn(m))
            .unwrap_or(modules.len() - 1);

        let enum_variants = crate::generator::collect_enum_variants(modules);
        let generic_decls = crate::generator::collect_generic_decls(modules);
        let trait_decls = crate::generator::collect_trait_decls(modules);
        let exported_types = crate::generator::collect_exported_type_names(modules);
        let record_names = crate::generator::collect_record_names(modules);
        let class_fields = crate::generator::collect_class_fields(modules);
        let const_names = crate::generator::collect_const_names(modules);
        let public_symbols = crate::generator::collect_public_symbols_for_esm(modules);
        // Program-wide field/method name-collision set (camelCased). Built across
        // *all* reachable modules so a call site in `main.ts` to a renamed method
        // declared in `core/error.ts` agrees with that declaration.
        let mut field_method_collisions = HashSet::new();
        for (module, _) in modules {
            field_method_collisions.extend(crate::generator::collect_record_field_names(
                module,
                to_camel_case,
            ));
        }

        let main_is_async = modules
            .iter()
            .any(|(m, _)| crate::generator::module_main_fn_is_async(m));
        let invocation = self.entry_invocation(main_is_async);

        let mut files: Vec<OutputFile> = Vec::with_capacity(modules.len() + 2);
        let mut runtime_optional = false;
        let mut runtime_result = false;
        let mut runtime_concurrency = false;
        let mut runtime_range = false;
        let mut runtime_eq = false;
        let mut runtime_compare = false;
        let mut runtime_str = false;

        for (i, (module, source_path)) in modules.iter().enumerate() {
            let own_path = crate::generator::module_path_string(module).unwrap_or_default();
            let mut ctx = TsEmitCtx::new();
            ctx.per_module = true;
            ctx.enum_variants = enum_variants.clone();
            ctx.generic_decls = generic_decls.clone();
            ctx.trait_decls = trait_decls.clone();
            ctx.exported_types = exported_types.clone();
            // Record names need the whole reachable set so a cross-module record
            // construction lowers to `new Name(...)` (see the JS backend note).
            ctx.record_names = record_names.clone();
            // Class field-orders likewise: a cross-module `class` construction
            // must lower to its positional `new Name(...)`.
            ctx.class_fields = class_fields.clone();
            ctx.const_names = const_names.clone();
            ctx.field_method_collisions = field_method_collisions.clone();
            ctx.seed_effect_registries(modules);
            ctx.self_module_path = if i == entry_idx {
                String::new()
            } else {
                own_path.clone()
            };
            // The shared collector now matches a glob-imported (`use models.*`)
            // enum variant by its bare source name as well as its emitted
            // `Enum_Variant` value-name, so the cross-module variant import is
            // produced here for js and ts alike (no TS-local recovery needed).
            ctx.implicit_imports =
                crate::generator::implicit_esm_imports_for(module, &public_symbols, &own_path);
            ctx.public_symbols = public_symbols.clone();
            ctx.enum_variant_exports = crate::generator::enum_variant_value_names(module);
            ctx.emit_node(module)?;
            runtime_optional |= ctx.needs_runtime_optional;
            runtime_result |= ctx.needs_runtime_result;
            runtime_concurrency |= ctx.needs_runtime_concurrency;
            runtime_range |= ctx.needs_runtime_range;
            runtime_eq |= ctx.needs_runtime_eq;
            runtime_compare |= ctx.needs_runtime_compare;
            runtime_str |= ctx.needs_runtime_str;
            let (mut content, mappings) = ctx.finish();

            if i == entry_idx && crate::generator::module_declares_main_fn(module) {
                if let Some(invoc) = invocation.as_ref() {
                    if !content.is_empty() && !content.ends_with('\n') {
                        content.push('\n');
                    }
                    content.push_str(invoc);
                }
            }

            let out_path = self.module_output_path(module, source_path, i == entry_idx);
            let generated_file = out_path
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            files.push(OutputFile {
                path: out_path,
                content,
                source_map: Some(SourceMap {
                    generated_file,
                    mappings,
                    ..Default::default()
                }),
            });
        }

        // Shared runtime module: Optional/Result types and concurrency/range
        // helpers, each `export`ed (types via `export type`, values via `export
        // const`) so consuming modules `import` / `import type` them.
        if runtime_optional
            || runtime_result
            || runtime_concurrency
            || runtime_range
            || runtime_eq
            || runtime_compare
            || runtime_str
        {
            let mut content = String::new();
            if runtime_optional {
                content.push_str(&export_runtime_decls(OPTIONAL_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_result {
                content.push_str(&export_runtime_decls(RESULT_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_concurrency {
                content.push_str(&export_runtime_decls(CONCURRENCY_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_range {
                content.push_str(&export_runtime_decls(RANGE_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_compare {
                content.push_str(&export_runtime_decls(COMPARE_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_str {
                content.push_str(&export_runtime_decls(STR_RUNTIME_TS));
                content.push('\n');
            }
            if runtime_eq {
                content.push_str(&export_runtime_decls(EQ_RUNTIME_TS));
                content.push('\n');
            }
            files.push(OutputFile {
                path: PathBuf::from(format!("{RUNTIME_MODULE_TS}.ts")),
                content,
                source_map: Some(SourceMap {
                    generated_file: format!("{RUNTIME_MODULE_TS}.ts"),
                    ..Default::default()
                }),
            });
        }

        // Run-affordance emission moved to the project-mode scaffolder (S6a /
        // DV18): codegen emits only the per-module `.ts` *source* tree in all
        // modes; the `package.json` `{"type":"module"}` run affordance — which
        // makes the `.ts` source tree run as ES modules under `node
        // --experimental-strip-types main.ts` — is emitted by `JsScaffolder`
        // (shared js/ts) in project mode only (never under `--source-only`). The
        // TS-only `tsconfig.json` (with `rewriteRelativeImportExtensions`) is
        // emitted by the TS scaffolder. See `scaffold.rs`.

        Ok(GeneratedCode { files })
    }

    /// Transpile `@test` functions into a Vitest/Jest `bock.test.ts` file (S7).
    ///
    /// Identical in shape to the JS backend's `generate_tests` (shared via
    /// [`crate::generator::js_ts_generate_tests`]); only the file extension and
    /// the concrete TS emit context differ. `framework` selects Vitest (default)
    /// vs Jest.
    fn generate_tests(
        &self,
        modules: &[(&AIRModule, &std::path::Path)],
        framework: &str,
    ) -> Result<crate::generator::TestArtifacts, CodegenError> {
        crate::generator::js_ts_generate_tests(
            modules,
            framework,
            &self.target().conventions.file_extension,
            // TS/ESM specifiers reference the emitted `.ts` source directly so the
            // tree runs verbatim under `node --experimental-strip-types` (which
            // does not rewrite `.js`→`.ts`); `tsc` accepts the `.ts` specifier via
            // `rewriteRelativeImportExtensions` (emitted into the scaffolded
            // tsconfig), which also rewrites it to `.js` on emit.
            "ts",
            |module, source_path, is_entry| self.module_output_path(module, source_path, is_entry),
            |ctx_modules| {
                let mut ctx = TsEmitCtx::new();
                ctx.per_module = true;
                ctx.enum_variants = crate::generator::collect_enum_variants(ctx_modules);
                ctx.generic_decls = crate::generator::collect_generic_decls(ctx_modules);
                ctx.trait_decls = crate::generator::collect_trait_decls(ctx_modules);
                ctx.exported_types = crate::generator::collect_exported_type_names(ctx_modules);
                ctx.record_names = crate::generator::collect_record_names(ctx_modules);
                ctx.class_fields = crate::generator::collect_class_fields(ctx_modules);
                ctx.const_names = crate::generator::collect_const_names(ctx_modules);
                let mut field_method_collisions = HashSet::new();
                for (module, _) in ctx_modules {
                    field_method_collisions.extend(crate::generator::collect_record_field_names(
                        module,
                        to_camel_case,
                    ));
                }
                ctx.field_method_collisions = field_method_collisions;
                ctx.seed_effect_registries(ctx_modules);
                Box::new(TsTestEmitter { ctx })
            },
        )
    }
}

/// Adapter wrapping a TS [`TsEmitCtx`] so the shared js/ts test-file builder can
/// drive expression lowering without depending on the private context type.
struct TsTestEmitter {
    ctx: TsEmitCtx,
}

impl crate::generator::JsTsExprEmitter for TsTestEmitter {
    fn expr_to_string(&mut self, node: &AIRNode) -> Result<String, CodegenError> {
        self.ctx.expr_to_string(node)
    }
}

impl TsGenerator {
    /// Output path for one module in the per-module native-import tree. The entry
    /// module is always `main.ts`; every other module is placed at the path
    /// mirrored from its declared module-path (`core.option` ⇒ `core/option.ts`).
    fn module_output_path(
        &self,
        module: &AIRModule,
        source_path: &std::path::Path,
        is_entry: bool,
    ) -> PathBuf {
        if is_entry {
            return crate::generator::derive_output_path(source_path, self.target());
        }
        match crate::generator::module_path_string(module) {
            Some(path) if !path.is_empty() => {
                let rel: PathBuf = path.split('.').collect();
                rel.with_extension(&self.target().conventions.file_extension)
            }
            _ => crate::generator::derive_output_path(source_path, self.target()),
        }
    }
}

/// Rewrite a TS runtime-prelude string so each **top-level** declaration is
/// exported: a `type NAME` line becomes `export type NAME`, a `const NAME` line
/// becomes `export const NAME`. Used to build the shared `_bock_runtime.ts`,
/// whose helpers/types consuming modules import. Only column-0 declarations are
/// rewritten; indented inner lines (a helper body's local `const`) are left
/// untouched.
fn export_runtime_decls(runtime: &str) -> String {
    runtime
        .lines()
        .map(|line| {
            if let Some(rest) = line.strip_prefix("type ") {
                format!("export type {rest}")
            } else if let Some(rest) = line.strip_prefix("const ") {
                format!("export const {rest}")
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

// ─── Emission context ────────────────────────────────────────────────────────

/// Where the value produced by a statement-position control-flow expression
/// (lowered by [`TsEmitCtx::emit_value_in_stmt_pos`]) should go. Either `return`
/// it (the expression was a function-body tail) or assign it to a named binding
/// (the expression initialised a `let`/`const`). A diverging tail
/// (`return`/`break`/`continue`/`todo()`) ignores the sink.
#[derive(Clone)]
enum ValueSink {
    /// `return <value>;`
    Return,
    /// `<name> = <value>;`
    Assign(String),
    /// `<value>;` — the value is discarded (the expression is a statement-
    /// position tail: a loop body, a statement-`if`/`match` arm, etc., whose
    /// value Bock drops). Distinct from [`ValueSink::Return`]: emitting `return`
    /// here would abort the enclosing function (e.g. exit a `for` loop after one
    /// iteration), so the value is emitted as a bare expression statement.
    Discard,
}

/// Internal state for TypeScript emission.
struct TsEmitCtx {
    buf: String,
    indent: usize,
    /// Maps effect operation name → effect type name (e.g., "log" → "Logger").
    effect_ops: HashMap<String, String>,
    /// Maps effect type name → current handler variable name in scope.
    current_handler_vars: HashMap<String, String>,
    /// Maps function name → effect type names from its `with` clause.
    fn_effects: HashMap<String, Vec<String>>,
    /// Maps composite effect name → component effect names.
    composite_effects: HashMap<String, Vec<String>>,
    /// Names of records declared in this module (emitted as classes).
    record_names: HashSet<String>,
    /// Names of `class` declarations mapped to their **field names in
    /// declaration order**, pre-scanned across the reachable program. A Bock
    /// `class` emits a *positional* `constructor(a, b)` (unlike a record's
    /// destructured `constructor({ a, b })`), so a `class` literal `T { a: x, b:
    /// y }` must lower to `new T(x, y)` with arguments ordered by the declared
    /// field order — not the bare object literal the record path emits (which
    /// `tsc` rejects: the inherent/trait methods are not on an object-literal
    /// type). See [`crate::generator::collect_class_fields`].
    class_fields: HashMap<String, Vec<String>>,
    /// Declared names of module-scope `const`s, pre-scanned across the reachable
    /// program; emitted verbatim at both declaration and use so the two agree
    /// (the `to_camel_case` transform would mangle a SCREAMING_SNAKE use site).
    /// See [`crate::generator::collect_const_names`].
    const_names: HashSet<String>,
    /// Names of effects declared in this module (for typing handler vars).
    effect_names: HashSet<String>,
    /// 1-indexed current line in `buf`, maintained incrementally.
    cur_line: u32,
    /// 1-indexed current column (char count) in `buf`, maintained incrementally.
    cur_col: u32,
    /// Byte offset in `buf` up to which (cur_line, cur_col) is accurate.
    scan_pos: usize,
    /// Last (gen_line, gen_col) we recorded — avoids duplicate mappings.
    last_marked: Option<(u32, u32)>,
    /// Collected source-map entries (populated via [`Self::mark_span`]).
    mappings: Vec<SourceMapping>,
    /// Loop-label stack — see [`crate::generator::loop_needs_break_label`].
    /// `break` inside a `switch` exits the switch, so a statement-arm `match`
    /// that wants to `break`/`continue` an enclosing loop uses a labelled jump.
    loop_labels: Vec<Option<String>>,
    /// Depth of statement-arm `switch` emission; > 0 routes `break`/`continue`
    /// to the innermost labelled loop.
    switch_label_depth: usize,
    /// Monotonic counter for unique loop-label names.
    loop_label_counter: usize,
    /// Monotonic counter for unique `match` scrutinee temporaries. A non-trivial
    /// scrutinee (a call, etc.) is hoisted into `const __matchN = <scrutinee>;`
    /// once, so it is evaluated a single time and — crucially for TypeScript —
    /// the discriminated-union narrowing on `__matchN._tag` flows to `__matchN._0`
    /// in the arm bodies. Re-emitting the scrutinee expression inline (the prior
    /// behavior) both double-evaluated it and defeated narrowing (TS2339 on `_0`).
    match_temp_counter: usize,
    /// Set once the Optional runtime prelude has been emitted in the
    /// single-module self-contained path ([`TsGenerator::generate_module`]), so
    /// a module referencing it more than once still inlines it at most once (a
    /// duplicate `type Option<T>` is a TS redeclaration error). The per-module
    /// project path emits the runtime once into the shared `_bock_runtime.ts`.
    optional_runtime_emitted: bool,
    /// Set once the `Result` runtime prelude has been emitted; deduped exactly as
    /// [`Self::optional_runtime_emitted`] (a duplicate `type BockResult<T, E>` is
    /// a TS redeclaration error).
    result_runtime_emitted: bool,
    /// Set once the concurrency runtime prelude has been emitted; deduped exactly
    /// as [`Self::optional_runtime_emitted`].
    concurrency_runtime_emitted: bool,
    /// Set once the range runtime prelude ([`RANGE_RUNTIME_TS`]) has been
    /// emitted; deduped exactly as [`Self::optional_runtime_emitted`] (a
    /// duplicate `const range` is a redeclaration error).
    range_runtime_emitted: bool,
    /// Set once the structural-equality runtime ([`EQ_RUNTIME_TS`]) has been
    /// emitted; deduped exactly as [`Self::range_runtime_emitted`].
    eq_runtime_emitted: bool,
    /// Set once the structural-comparison runtime ([`COMPARE_RUNTIME_TS`]) has
    /// been emitted in the single-module self-contained path. Deduped exactly as
    /// [`Self::eq_runtime_emitted`]. (Q-bounded-comparable-codegen.)
    compare_runtime_emitted: bool,
    /// Set once the display-string runtime ([`STR_RUNTIME_TS`]) has been emitted
    /// in the single-module self-contained path. (Q-displayable-interpolation-dispatch.)
    str_runtime_emitted: bool,
    /// User-enum-variant registry (DV14). Same role as the JS backend's: route
    /// a unit-variant reference to the `{enum}_{variant}` const, a struct/tuple
    /// construction to the factory, and recognise `RecordPat` arms as ADT.
    /// Built-in Optional/Result pre-seeds are filtered out where bespoke
    /// lowering applies. Pre-scanned across the reached modules.
    enum_variants: crate::generator::EnumVariantRegistry,
    /// Generic-type declaration registry: a record/enum/class name → its
    /// declared generic params. An `impl Box { ... }` block carries no generic
    /// params of its own (the `T` is declared on `record Box[T]`); this lets the
    /// declaration-merged `interface Box<T>` and the `self: Box<T>` param type
    /// recover them so the merge lands on the generic class. Pre-scanned across
    /// the reached modules (mirrors [`Self::enum_variants`]).
    generic_decls: crate::generator::GenericDeclRegistry,
    /// Trait-declaration registry: a trait name → its declared generic params
    /// and methods. Used at each `impl Trait for Type` site to recover the
    /// trait's *default* methods (those carrying a body) so they can be
    /// synthesized onto the implementing type's prototype — the trait interface
    /// alone declares only signatures, so a type relying on an inherited default
    /// would otherwise have no such method. Pre-scanned across the reached modules.
    trait_decls: crate::generator::TraitDeclRegistry,
    /// When `Some(target)`, a `Self` type (`TypeSelf`) renders as `target`
    /// rather than the default `this`. Set while emitting ANY `impl` method onto
    /// a concrete target — a synthesized trait default (`other: Self`) AND the
    /// impl's own inherent methods (`fn combine(self, ...) -> Self`) alike. Each
    /// emits as a free prototype function (`Target.prototype.m = function(...)`)
    /// where `this` is not a legal type annotation (`tsc` rejects it with
    /// TS2526), so the concrete target name must be substituted in both the
    /// prototype function and the matching merged-interface signature. Cleared
    /// (None) everywhere else, so trait-*interface* methods keep rendering `Self`
    /// as `this` (valid inside an interface member).
    trait_self_subst: Option<String>,
    /// Names of `public` (exported) top-level types. The declaration-merging
    /// `interface Target { ... }` an `impl` emits must be `export`ed exactly
    /// when the `Target` class is — TS requires all declarations in a merged
    /// declaration to agree on export-ness. Pre-scanned across the reached modules.
    exported_types: std::collections::HashSet<String>,
    /// The TS type a value-position expression is being assigned *into* (the
    /// declared type of a `let x: T = <value>`), when known. Set around the
    /// `LetBinding` value emit. An expression-position `match` lowers to an IIFE
    /// (`(() => { switch (s) { … } })()`); when the value is consumed into a
    /// typed binding this annotates the IIFE arrow's return type (`(() : T =>
    /// {…})()`) and — crucially — signals that a value-`switch` over a bare
    /// identifier scrutinee must be hoisted into a temp (`const __matchN = s;
    /// switch (__matchN) …`). Without the hoist, `switch (s)` narrows `s` to the
    /// case's literal type inside each arm, so an arm body re-referencing `s`
    /// (`s === <other-literal>`) trips TS2367 ("no overlap"). Hoisting means the
    /// switch narrows the temp while arm bodies still see the original (un-
    /// narrowed) `s`. `None` outside a typed value-binding context; restored
    /// after the value so it never leaks to a sibling/outer expression.
    current_expected_type: Option<String>,
    /// True in the **per-module native-import** emission path
    /// ([`TsGenerator::generate_project`], the sole real-build path). When set,
    /// the `Module` arm emits real ESM `import`/`import type` for cross-module
    /// references, records which shared-runtime helpers/types the module needs
    /// (instead of inlining them), and a trailing `export { … }` re-exports the
    /// module's enum-variant value names (every other declaration kind already
    /// exports inline). When clear, the module is emitted as a single
    /// self-contained file with its runtime preludes inlined — the
    /// [`TsGenerator::generate_module`] path used by unit tests.
    per_module: bool,
    /// In the per-module path, records that this module references the Optional /
    /// Result runtime *types* (`BockOption` / `BockResult`) — so they are emitted
    /// once into the shared `_bock_runtime.ts` and this module `import type`s them.
    needs_runtime_optional: bool,
    needs_runtime_result: bool,
    /// As above, for the concurrency / range / structural-equality runtime
    /// *values* (`__bockChannelNew` / `range` / `__bockEq`).
    needs_runtime_concurrency: bool,
    needs_runtime_range: bool,
    needs_runtime_eq: bool,
    /// As [`Self::needs_runtime_eq`], for the bounded-`Comparable`
    /// structural-comparison runtime (`__bockCompare`).
    /// (Q-bounded-comparable-codegen.)
    needs_runtime_compare: bool,
    /// As [`Self::needs_runtime_eq`], for the display-string runtime
    /// (`__bockStr`). (Q-displayable-interpolation-dispatch.)
    needs_runtime_str: bool,
    /// Implicit cross-module imports for the per-module path — names this module
    /// references but neither declares locally nor imports via an explicit `use`.
    /// Computed in `generate_project`; emitted as ESM imports by the `Module` arm.
    implicit_imports: Vec<crate::generator::ImplicitEsmImport>,
    /// Map of every reachable public symbol → declaring module + kind, used to
    /// spell an explicit `use`d name the way its declaration emits it.
    public_symbols: HashMap<String, crate::generator::EsmSymbol>,
    /// The declared dotted module-path of the file currently being emitted, or
    /// empty for the entry file (always `main.ts` at the build root). Drives the
    /// relative-specifier computation for every emitted `import`.
    self_module_path: String,
    /// Public enum-variant value names this module declares (`Color_Red`, …),
    /// re-exported in a trailing `export { … }`. Unlike records/classes/aliases
    /// (which export inline), enum-variant interfaces/consts/factories are emitted
    /// without `export`, so cross-module references need the trailing re-export.
    /// Computed in `generate_project`.
    enum_variant_exports: Vec<String>,
    /// Camel-cased record/class field names across the reachable program, used to
    /// disambiguate a method whose camelCased name collides with a field name
    /// (`core.error`'s `message` field + `message()` method). TS rejects a class
    /// field and a (declaration-merged) interface method sharing a name with a
    /// "Duplicate identifier" error, so the *method* is renamed (`messageMethod`)
    /// at the trait-interface signature, the merged-interface signature, the
    /// prototype attachment, the class-body method, and every call site via
    /// [`Self::ts_method_name`]; the field keeps its name. Pre-seeded program-wide
    /// by `generate_project` (and extended per-module by the `Module` arm for the
    /// single-module `generate_module` path). Shared policy with go/js/py.
    field_method_collisions: HashSet<String>,
    /// Active value-sink while a statement-position control-flow expression is
    /// being emitted (see [`ValueSink`] and [`Self::emit_value_in_stmt_pos`]).
    /// A `match` arm body emitted under this sink delivers its value through it
    /// (`return v` / `binding = v`) instead of the default `return v`, so an
    /// expression-position `match` containing a `return`/`break` arm lowers to a
    /// statement `switch` whose value-arms feed the binding. `None` everywhere
    /// else; saved/restored around each statement-position lowering so it never
    /// leaks into an unrelated (IIFE-lowered) match.
    value_sink: Option<ValueSink>,
    /// Per-loop result sink, pushed/popped alongside [`Self::loop_labels`]. When
    /// a `loop` is lowered in value position (`let r = loop { … break v … }`),
    /// the innermost entry holds the sink that `break v` writes into (`r = v;
    /// break;`). `None` for an ordinary statement-position loop, where `break v`
    /// has no value destination. Indexed by loop nesting, so an inner ordinary
    /// loop inside a value loop does not capture the outer sink.
    loop_value_sinks: Vec<Option<ValueSink>>,
    /// Failure tag of the *enclosing function's* result/optional return type,
    /// driving the `?` (`Propagate`) early-return guard. `"Err"` when the fn
    /// returns `Result[T, E]`, `"None"` when it returns `Optional[T]` / `T?`,
    /// `None` otherwise. Set in [`Self::emit_fn_decl`] / [`Self::emit_class_method`]
    /// from the declared return type and restored after the body, so the guard
    /// tests the single discriminant that actually exists on the value — which
    /// also lets TS narrow the success access (`._0`) to the payload type.
    current_fn_propagate_tag: Option<&'static str>,
    /// Per-TS-lexical-block stack of simple `let`/`const` binding state. Bock
    /// permits re-binding (`let x = …; let x = …`) which shadows the prior
    /// binding in the same scope; TS `const`/`let` forbid re-declaration in one
    /// block scope (TS2451). Each frame records the TS idents already declared in
    /// the block and, of those, which need `let` (because they are re-bound or
    /// assigned later). The first declaration of a re-bound name uses `let`;
    /// every subsequent binding of the same name emits a plain assignment
    /// (`x = …`) rather than a redeclaration. Mirrors the js backend (#217). See
    /// [`LetScope`].
    let_scopes: Vec<LetScope>,
}

/// One TS lexical block's `let`/`const` binding state — see
/// [`TsEmitCtx::let_scopes`].
#[derive(Default)]
struct LetScope {
    /// Simple TS idents already emitted as a declaration in this block.
    declared: HashSet<String>,
    /// Of the block's simple bindings, those that are re-bound or assigned and
    /// so must be declared with `let` (not `const`) at their first declaration.
    needs_let: HashSet<String>,
}

impl TsEmitCtx {
    fn new() -> Self {
        Self {
            buf: String::with_capacity(4096),
            indent: 0,
            effect_ops: HashMap::new(),
            current_handler_vars: HashMap::new(),
            fn_effects: HashMap::new(),
            composite_effects: HashMap::new(),
            record_names: HashSet::new(),
            class_fields: HashMap::new(),
            const_names: HashSet::new(),
            effect_names: HashSet::new(),
            cur_line: 1,
            cur_col: 1,
            scan_pos: 0,
            last_marked: None,
            mappings: Vec::new(),
            loop_labels: Vec::new(),
            switch_label_depth: 0,
            loop_label_counter: 0,
            match_temp_counter: 0,
            optional_runtime_emitted: false,
            result_runtime_emitted: false,
            concurrency_runtime_emitted: false,
            range_runtime_emitted: false,
            eq_runtime_emitted: false,
            compare_runtime_emitted: false,
            str_runtime_emitted: false,
            enum_variants: crate::generator::EnumVariantRegistry::new(),
            generic_decls: crate::generator::GenericDeclRegistry::new(),
            trait_decls: crate::generator::TraitDeclRegistry::new(),
            trait_self_subst: None,
            exported_types: std::collections::HashSet::new(),
            current_expected_type: None,
            per_module: false,
            needs_runtime_optional: false,
            needs_runtime_result: false,
            needs_runtime_concurrency: false,
            needs_runtime_range: false,
            needs_runtime_eq: false,
            needs_runtime_compare: false,
            needs_runtime_str: false,
            implicit_imports: Vec::new(),
            public_symbols: HashMap::new(),
            self_module_path: String::new(),
            enum_variant_exports: Vec::new(),
            field_method_collisions: HashSet::new(),
            value_sink: None,
            loop_value_sinks: Vec::new(),
            current_fn_propagate_tag: None,
            let_scopes: Vec::new(),
        }
    }

    /// Classify a function's declared return type into the failure tag its `?`
    /// operator early-returns: `Some("Err")` for `Result[…]`, `Some("None")` for
    /// `Optional[…]` / `T?`, `None` for anything else.
    fn propagate_tag_for_return(ret: Option<&AIRNode>) -> Option<&'static str> {
        match ret.map(|r| &r.kind) {
            Some(NodeKind::TypeOptional { .. }) => Some("None"),
            Some(NodeKind::TypeNamed { path, .. }) => {
                match path.segments.last().map(|s| s.name.as_str()) {
                    Some("Result") => Some("Err"),
                    Some("Optional") => Some("None"),
                    _ => None,
                }
            }
            _ => None,
        }
    }

    /// Disambiguate an *already-rendered* method member name against the
    /// program's field names: when the rendered name collides with a field name,
    /// append a `Method` suffix (`message` → `messageMethod`). Returns the name
    /// unchanged otherwise.
    ///
    /// TS renders method names two ways — declarations use the raw Bock name
    /// (`name.name`) while call sites use `to_camel_case` — so this helper takes
    /// whatever each site already produced and only adds the suffix, preserving
    /// each site's existing casing. For the field/method collisions this targets
    /// (single-word field names like `message`, where raw == camelCase) the two
    /// renderings agree, so the renamed method resolves at the trait-interface
    /// signature, the merged-interface signature, the prototype attachment, the
    /// class-body method, and every call site alike. Shared policy with go/js/py
    /// (see [`crate::generator::disambiguate_method_name`]).
    fn ts_method_name(&self, rendered: &str) -> String {
        crate::generator::disambiguate_method_name(
            rendered.to_string(),
            &self.field_method_collisions,
            "Method",
        )
    }

    fn finish(self) -> (String, Vec<SourceMapping>) {
        (self.buf, self.mappings)
    }

    /// Pre-seed the effect registries (`effect_ops`, `composite_effects`,
    /// `effect_names`) from every module's top-level `EffectDecl`s. The
    /// per-module path emits each module in its own context, so a bare op used in
    /// one module whose effect is declared in another must be recognised without
    /// having emitted the declaring module first. Mirrors how `enum_variants` /
    /// `trait_decls` are collected across the reached modules and the JS /
    /// Python backends' equivalents.
    fn seed_effect_registries(&mut self, modules: &[(&AIRModule, &std::path::Path)]) {
        for (module, _) in modules {
            let NodeKind::Module { items, .. } = &module.kind else {
                continue;
            };
            for item in items {
                let NodeKind::EffectDecl {
                    name,
                    components,
                    operations,
                    ..
                } = &item.kind
                else {
                    continue;
                };
                if !components.is_empty() {
                    let comp_names: Vec<String> = components
                        .iter()
                        .map(|tp| {
                            tp.segments
                                .last()
                                .map_or("effect".to_string(), |s| s.name.clone())
                        })
                        .collect();
                    self.composite_effects.insert(name.name.clone(), comp_names);
                    continue;
                }
                self.effect_names.insert(name.name.clone());
                for op in operations {
                    if let NodeKind::FnDecl { name: op_name, .. } = &op.kind {
                        self.effect_ops
                            .insert(op_name.name.clone(), name.name.clone());
                    }
                }
            }
        }
    }

    /// Emit the per-module ESM `import` statements at the top of the file: the
    /// shared-runtime import (Optional/Result types via `import type`,
    /// concurrency/range helpers via a value `import`), the explicit cross-module
    /// `use` imports, and the implicit prelude imports. Grouped one statement per
    /// source module, with the relative specifier computed from this file's
    /// declared module-path. ESM specifiers reference the *emitted* `.ts` source
    /// directly (resolved verbatim by node strip-types; accepted by `tsc` via
    /// `rewriteRelativeImportExtensions`, which rewrites it to `.js` on emit).
    fn emit_esm_imports(&mut self, imports: &[AIRNode]) -> Result<(), CodegenError> {
        // ESM specifiers reference the emitted `.ts` source directly (not a `.js`
        // that is never written). `node --experimental-strip-types` resolves
        // specifiers verbatim against files on disk — it does not rewrite `.js` →
        // `.ts` — so a `.js` specifier `ERR_MODULE_NOT_FOUND`s on any *value*
        // import (type-only imports are erased by the strip pass, so they happened
        // to work, but value imports of runtime helpers / cross-module functions
        // did not). A `.ts` specifier runs verbatim under node *and* type-checks
        // under `tsc` when `rewriteRelativeImportExtensions` is set (emitted into
        // the scaffolded `tsconfig.json`; see `scaffold.rs::tsconfig_json`) — that
        // flag also rewrites the specifier to `.js` on emit so the conformance
        // `tsc -p .` → `node main.js` plan still runs.
        let ext = "ts";

        // Shared runtime: type-only and value imports, split so a type name never
        // appears in a value `import` (which would be a runtime error if elided
        // away to nothing, and is cleaner under `--strict`).
        let mut type_names: Vec<&str> = Vec::new();
        if self.needs_runtime_optional {
            type_names.push("BockOption");
        }
        if self.needs_runtime_result {
            type_names.push("BockResult");
        }
        let mut value_names: Vec<&str> = Vec::new();
        if self.needs_runtime_concurrency {
            value_names.extend(["__bockChannelNew", "__bockSpawn"]);
        }
        if self.needs_runtime_range {
            value_names.extend(["range", "rangeInclusive"]);
        }
        if self.needs_runtime_eq {
            value_names.push("__bockEq");
        }
        if self.needs_runtime_compare {
            value_names.push("__bockCompare");
        }
        if self.needs_runtime_str {
            value_names.push("__bockStr");
        }
        if !type_names.is_empty() || !value_names.is_empty() {
            let spec = crate::generator::esm_relative_specifier(
                &self.self_module_path,
                RUNTIME_MODULE_TS,
                ext,
            );
            if !type_names.is_empty() {
                self.writeln(&format!(
                    "import type {{ {} }} from \"{spec}\";",
                    type_names.join(", ")
                ));
            }
            if !value_names.is_empty() {
                self.writeln(&format!(
                    "import {{ {} }} from \"{spec}\";",
                    value_names.join(", ")
                ));
            }
        }

        // Explicit `use` imports → real ESM imports. A `use`d *function* is
        // imported under its camelCased name; other kinds keep their raw name.
        // Accumulate cross-module imports grouped by declaring module-path, split
        // into value imports (`import { … }`) and type-only imports
        // (`import type { … }`) — a TS-only distinction so an enum *type*, trait
        // interface, or type alias never appears in a value import.
        let mut value_by_module: std::collections::BTreeMap<String, Vec<String>> =
            std::collections::BTreeMap::new();
        let mut type_by_module: std::collections::BTreeMap<String, Vec<String>> =
            std::collections::BTreeMap::new();

        for import in imports {
            if let NodeKind::ImportDecl { path, items } = &import.kind {
                let target_path = path
                    .segments
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<_>>()
                    .join(".");
                if target_path.is_empty() {
                    continue;
                }
                if let bock_ast::ImportItems::Named(named) = items {
                    for n in named {
                        // A `use`d runtime-prelude *value* name lowers inline and
                        // is never a real export of the declaring module.
                        if crate::generator::ESM_RUNTIME_PRELUDE_NAMES
                            .contains(&n.name.name.as_str())
                        {
                            continue;
                        }
                        let kind = self.public_symbols.get(&n.name.name).map(|s| s.kind);
                        let is_fn = matches!(kind, Some(crate::generator::EsmDeclKind::Function));
                        let src = ts_esm_emit_name(&n.name.name, is_fn);
                        let rendered = match &n.alias {
                            Some(alias) => {
                                let dst = ts_esm_emit_name(&alias.name, is_fn);
                                if dst == src {
                                    src
                                } else {
                                    format!("{src} as {dst}")
                                }
                            }
                            None => src,
                        };
                        let type_only = kind.is_some_and(|k| k.is_ts_type_only());
                        if type_only {
                            type_by_module.entry(target_path.clone()).or_default()
                        } else {
                            value_by_module.entry(target_path.clone()).or_default()
                        }
                        .push(rendered);
                    }
                }
                // `use Foo` / `use Foo.*` resolve via implicit imports by name.
            }
        }

        // Implicit imports: prelude-visible names referenced but not explicitly
        // `use`d, routed value vs type-only the same way.
        for imp in &self.implicit_imports {
            let rendered = ts_esm_emit_name(&imp.name, imp.is_fn());
            if imp.kind.is_ts_type_only() {
                type_by_module.entry(imp.module_path.clone()).or_default()
            } else {
                value_by_module.entry(imp.module_path.clone()).or_default()
            }
            .push(rendered);
        }

        for (module_path, mut names) in value_by_module {
            names.sort_unstable();
            names.dedup();
            let spec =
                crate::generator::esm_relative_specifier(&self.self_module_path, &module_path, ext);
            self.writeln(&format!(
                "import {{ {} }} from \"{spec}\";",
                names.join(", ")
            ));
        }
        for (module_path, mut names) in type_by_module {
            names.sort_unstable();
            names.dedup();
            let spec =
                crate::generator::esm_relative_specifier(&self.self_module_path, &module_path, ext);
            self.writeln(&format!(
                "import type {{ {} }} from \"{spec}\";",
                names.join(", ")
            ));
        }
        Ok(())
    }

    /// Emit the trailing `export { … }` for this module's public enum-variant
    /// value names (`Color_Red`, …). Every other public declaration kind exports
    /// inline in TS; enum-variant interfaces/consts/factories do not, so they are
    /// re-exported here for cross-module references. Emits nothing when there is
    /// nothing to re-export.
    fn emit_trailing_exports(&mut self) {
        if self.enum_variant_exports.is_empty() {
            return;
        }
        let mut names = self.enum_variant_exports.clone();
        names.sort_unstable();
        names.dedup();
        if !self.buf.is_empty() && !self.buf.ends_with('\n') {
            self.buf.push('\n');
        }
        self.writeln(&format!("export {{ {} }};", names.join(", ")));
    }

    /// Variant info for `path` when its last segment is a registered *user*
    /// enum variant (built-in Optional/Result pre-seeds excluded — those go
    /// through the bespoke tagged-object lowering).
    fn user_variant_for_path(
        &self,
        path: &bock_ast::TypePath,
    ) -> Option<&crate::generator::EnumVariantInfo> {
        let info = crate::generator::registered_variant(&self.enum_variants, path)?;
        if matches!(info.enum_name.as_str(), "Optional" | "Result") {
            return None;
        }
        Some(info)
    }

    /// As [`Self::user_variant_for_path`] but keyed by a bare identifier name.
    fn user_variant_for_name(&self, name: &str) -> Option<&crate::generator::EnumVariantInfo> {
        let info = self.enum_variants.get(name)?;
        if matches!(info.enum_name.as_str(), "Optional" | "Result") {
            return None;
        }
        Some(info)
    }

    /// If `value` is a *construction of a single user-enum variant* — a struct
    /// variant (`Open { … }`, a [`NodeKind::RecordConstruct`]), a unit variant
    /// (`Open`, a bare [`NodeKind::Identifier`]), or a tuple variant (`Open(…)`,
    /// a [`NodeKind::Call`] on a bare variant name) — return the *declaring
    /// enum's* name (the union type), else `None`.
    ///
    /// Used by [`Self::emit_stmt`] to widen the initialiser of a type-annotated
    /// `let`/`const` binding back to its declared union: `const g: Gate =
    /// Gate_Open(7)` otherwise narrows `g` to the construction variant
    /// (`Gate_Open`), and a later `match g` on the sibling variant fails `tsc
    /// --noEmit` with TS2678 (the narrowed literal `_tag` is "not comparable" to
    /// the sibling's). The declared annotation must win; widening the
    /// initialiser (`Gate_Open(7) as Gate`) defeats the const-init narrowing so
    /// the declared union type is what `g` carries at every use site.
    fn variant_construct_enum(&self, value: &AIRNode) -> Option<String> {
        match &value.kind {
            // Struct variant: `Open { level: 7 }`.
            NodeKind::RecordConstruct { path, spread, .. } if spread.is_none() => self
                .user_variant_for_path(path)
                .map(|i| i.enum_name.clone()),
            // Unit variant: a bare `Open`.
            NodeKind::Identifier { name } => self
                .user_variant_for_name(&name.name)
                .map(|i| i.enum_name.clone()),
            // Tuple variant: `Open(7)` — a call whose callee is a bare variant
            // name (the only call shape that constructs a variant; a method or
            // assoc call has a `FieldAccess` callee, not an `Identifier`).
            NodeKind::Call { callee, .. } => match &callee.kind {
                NodeKind::Identifier { name } => self
                    .user_variant_for_name(&name.name)
                    .map(|i| i.enum_name.clone()),
                _ => None,
            },
            _ => None,
        }
    }

    /// Whether a type-annotated binding's initialiser needs a widening cast to
    /// its declared type, i.e. `value` constructs a single variant of the enum
    /// the binding is declared as. The declared TS type string (`ty_ts`) must
    /// name exactly that enum's union — a binding annotated with an unrelated
    /// type, or one whose value is not a single-variant construction, is left
    /// untouched.
    fn binding_needs_union_widening(&self, value: &AIRNode, ty_ts: Option<&str>) -> bool {
        match (ty_ts, self.variant_construct_enum(value)) {
            (Some(declared), Some(enum_name)) => declared == enum_name,
            _ => false,
        }
    }

    /// Emit a `let`/`const` binding's initialiser `value` under the binding's
    /// declared TS type `ty_ts`, restoring the prior expected type afterwards so
    /// it never leaks to a sibling/nested expression.
    ///
    /// `ty_ts` is recorded as [`Self::current_expected_type`] for the value emit
    /// (so a value-position `match`/`if` IIFE annotates its arrow return and
    /// hoists a bare scrutinee — see [`Self::current_expected_type`]). When the
    /// value is a single-variant construction of the declared enum union, the
    /// emitted initialiser is widened with an `as <Union>` cast so the binding
    /// carries the declared union type rather than the narrower construction
    /// variant (see [`Self::variant_construct_enum`]).
    fn emit_let_value(
        &mut self,
        value: &AIRNode,
        ty_ts: Option<String>,
    ) -> Result<(), CodegenError> {
        // The widening cast (`Gate_Open(7) as Gate`) only applies when the
        // declared type names the enum the value constructs a variant of; an
        // unrelated annotation, or a non-construction value, emits unchanged.
        let widen_to = self
            .binding_needs_union_widening(value, ty_ts.as_deref())
            .then(|| ty_ts.clone())
            .flatten();
        let prev_expected = self.current_expected_type.take();
        self.current_expected_type = ty_ts;
        self.emit_expr(value)?;
        if let Some(union) = widen_to {
            let _ = write!(self.buf, " as {union}");
        }
        self.current_expected_type = prev_expected;
        Ok(())
    }

    /// Bring `cur_line` / `cur_col` up to date with everything appended to
    /// `buf` since the last sync.
    fn sync_pos(&mut self) {
        if self.scan_pos >= self.buf.len() {
            return;
        }
        let slice = &self.buf[self.scan_pos..];
        for ch in slice.chars() {
            if ch == '\n' {
                self.cur_line += 1;
                self.cur_col = 1;
            } else {
                self.cur_col += 1;
            }
        }
        self.scan_pos = self.buf.len();
    }

    fn mark_span(&mut self, span: Span) {
        if span.start == 0 && span.end == 0 {
            return;
        }
        self.sync_pos();
        let key = (self.cur_line, self.cur_col);
        if self.last_marked == Some(key) {
            return;
        }
        self.last_marked = Some(key);
        self.mappings.push(SourceMapping {
            gen_line: self.cur_line,
            gen_col: self.cur_col,
            src_line: 0,
            src_col: 0,
            src_offset: span.start as u32,
            src_file_id: span.file.0,
        });
    }

    fn indent_str(&self) -> String {
        "  ".repeat(self.indent)
    }

    fn write_indent(&mut self) {
        let indent = self.indent_str();
        self.buf.push_str(&indent);
    }

    fn writeln(&mut self, s: &str) {
        self.write_indent();
        self.buf.push_str(s);
        self.buf.push('\n');
    }

    // ── Prelude function mapping ──────────────────────────────────────────

    /// Emit an expression into a temporary buffer and return the string.
    fn expr_to_string(&mut self, node: &AIRNode) -> Result<String, CodegenError> {
        let start = self.buf.len();
        let saved_line = self.cur_line;
        let saved_col = self.cur_col;
        let saved_scan = self.scan_pos;
        let saved_marked = self.last_marked;
        let mappings_len = self.mappings.len();
        self.emit_expr(node)?;
        let s = self.buf[start..].to_string();
        self.buf.truncate(start);
        self.cur_line = saved_line;
        self.cur_col = saved_col;
        self.scan_pos = saved_scan;
        self.last_marked = saved_marked;
        self.mappings.truncate(mappings_len);
        Ok(s)
    }

    /// Map Bock prelude functions to TypeScript equivalents.
    fn map_prelude_call(
        &mut self,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<Option<String>, CodegenError> {
        let name = match &callee.kind {
            NodeKind::Identifier { name } => name.name.as_str(),
            _ => return Ok(None),
        };
        let arg_strs: Vec<String> = args
            .iter()
            .map(|a| self.expr_to_string(&a.value))
            .collect::<Result<_, _>>()?;
        let code = match name {
            "println" => {
                let a = arg_strs.first().map_or(String::new(), |s| s.clone());
                format!("console.log({a})")
            }
            "print" => {
                let a = arg_strs.first().map_or(String::new(), |s| s.clone());
                format!("process.stdout.write(String({a}))")
            }
            "debug" => {
                let a = arg_strs.first().map_or(String::new(), |s| s.clone());
                format!("console.debug({a})")
            }
            "assert" => {
                let a = arg_strs.first().map_or(String::new(), |s| s.clone());
                format!("if (!{a}) throw new Error(\"assertion failed\")")
            }
            "todo" => "throw new Error(\"not implemented\")".to_string(),
            "unreachable" => "throw new Error(\"unreachable\")".to_string(),
            "sleep" => {
                let a = arg_strs.first().map_or(String::new(), |s| s.clone());
                // Route through an installed `Clock` handler if one is in scope;
                // otherwise fall through to the host primitive (default).
                if let Some(handler) = self.clock_handler_var() {
                    format!("{handler}.sleep({a})")
                } else {
                    format!("new Promise<void>((__r) => setTimeout(__r, Math.floor(({a}) / 1e6)))")
                }
            }
            _ => return Ok(None),
        };
        Ok(Some(code))
    }

    /// Recognise `Duration.xxx(...)` / `Instant.xxx(...)` associated-function
    /// calls and emit inline arithmetic. Durations are plain numbers
    /// (nanoseconds); Instants are numbers representing ns since
    /// `performance.timeOrigin`. Returns `Ok(true)` if the call was emitted.
    fn try_emit_time_assoc_call(
        &mut self,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let NodeKind::FieldAccess { object, field } = &callee.kind else {
            return Ok(false);
        };
        let NodeKind::Identifier { name: type_name } = &object.kind else {
            return Ok(false);
        };
        let arg_strs: Vec<String> = args
            .iter()
            .map(|a| self.expr_to_string(&a.value))
            .collect::<Result<_, _>>()?;
        let arg0 = || arg_strs.first().cloned().unwrap_or_default();
        let code = match (type_name.name.as_str(), field.name.as_str()) {
            ("Duration", "zero") => "0".to_string(),
            ("Duration", "nanos") => arg0(),
            ("Duration", "micros") => format!("(({}) * 1000)", arg0()),
            ("Duration", "millis") => format!("(({}) * 1000000)", arg0()),
            ("Duration", "seconds") => format!("(({}) * 1000000000)", arg0()),
            ("Duration", "minutes") => format!("(({}) * 60000000000)", arg0()),
            ("Duration", "hours") => format!("(({}) * 3600000000000)", arg0()),
            ("Instant", "now") => {
                // Route through an installed `Clock` handler's `now_monotonic`
                // op if one is in scope; otherwise emit the host primitive.
                if let Some(handler) = self.clock_handler_var() {
                    format!("{handler}.now_monotonic()")
                } else {
                    "(performance.now() * 1000000)".to_string()
                }
            }
            _ => return Ok(false),
        };
        self.buf.push_str(&code);
        Ok(true)
    }

    /// Recognise `Channel.new()`, `spawn(...)`, and method calls on a
    /// channel value (`send`, `recv`, `close`) and emit the TS runtime
    /// helper equivalents.
    fn try_emit_concurrency_call(
        &mut self,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        if let NodeKind::Identifier { name } = &callee.kind {
            if name.name == "spawn" {
                self.buf.push_str("__bockSpawn(");
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(&arg.value)?;
                }
                self.buf.push(')');
                return Ok(true);
            }
        }
        let NodeKind::FieldAccess { object, field } = &callee.kind else {
            return Ok(false);
        };
        if let NodeKind::Identifier { name: type_name } = &object.kind {
            if type_name.name == "Channel" && field.name == "new" {
                self.buf.push_str("__bockChannelNew()");
                return Ok(true);
            }
        }
        if matches!(field.name.as_str(), "send" | "recv" | "close") {
            // First arg is the receiver duplicate (from desugaring) — skip.
            self.emit_expr(object)?;
            let _ = write!(self.buf, ".{}", field.name);
            self.buf.push('(');
            for (i, arg) in args.iter().skip(1).enumerate() {
                if i > 0 {
                    self.buf.push_str(", ");
                }
                self.emit_expr(&arg.value)?;
            }
            self.buf.push(')');
            return Ok(true);
        }
        Ok(false)
    }

    /// Recognise desugared method calls `Call(FieldAccess(recv, m), [recv, ...args])`
    /// on Duration/Instant values and emit inline arithmetic.
    ///
    /// `node` is the full `Call` AIR node, consulted only to *exclude* primitive
    /// receivers: [`is_time_method_name`] alone is ambiguous (`abs` is both
    /// `Duration.abs` and `Int.abs`/`Float.abs`), so when the checker has stamped
    /// `recv_kind = "Primitive:<Ty>"` this is a numeric method, not a time method —
    /// bail so [`Self::try_emit_numeric_method`] handles it.
    fn try_emit_time_desugared_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        if crate::generator::primitive_recv_kind(node).is_some() {
            return Ok(false);
        }
        let NodeKind::FieldAccess { object, field } = &callee.kind else {
            return Ok(false);
        };
        if let NodeKind::Identifier { name } = &object.kind {
            if matches!(name.name.as_str(), "Duration" | "Instant") {
                return Ok(false);
            }
        }
        if !is_time_method_name(&field.name) {
            return Ok(false);
        }
        let remaining: Vec<bock_air::AirArg> = args.iter().skip(1).cloned().collect();
        self.try_emit_time_method(object, &field.name, &remaining)
    }

    /// Recognise instance methods on Duration/Instant values and emit inline
    /// arithmetic.
    fn try_emit_time_method(
        &mut self,
        receiver: &AIRNode,
        method: &str,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let recv_str = self.expr_to_string(receiver)?;
        let arg_strs: Vec<String> = args
            .iter()
            .map(|a| self.expr_to_string(&a.value))
            .collect::<Result<_, _>>()?;
        let code = match method {
            "as_nanos" => format!("({recv_str})"),
            "as_millis" => format!("Math.floor(({recv_str}) / 1000000)"),
            "as_seconds" => format!("Math.floor(({recv_str}) / 1000000000)"),
            "is_zero" => format!("(({recv_str}) === 0)"),
            "is_negative" => format!("(({recv_str}) < 0)"),
            "abs" => format!("Math.abs({recv_str})"),
            "elapsed" => {
                // `instant.elapsed()` is derived: `now - instant`. Route the
                // "now" read through an installed `Clock` handler if in scope;
                // otherwise read the host monotonic clock (default).
                if let Some(handler) = self.clock_handler_var() {
                    format!("({handler}.now_monotonic() - ({recv_str}))")
                } else {
                    format!("((performance.now() * 1000000) - ({recv_str}))")
                }
            }
            "duration_since" => {
                let other = arg_strs.first().cloned().unwrap_or_default();
                format!("(({recv_str}) - ({other}))")
            }
            _ => return Ok(false),
        };
        self.buf.push_str(&code);
        Ok(true)
    }

    /// Emit Some/Ok/Err calls as tagged-object constructions, matching the
    /// representation used for user-defined enum variants. Returns true if
    /// the call was handled.
    fn try_emit_prelude_ctor(
        &mut self,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let name = match &callee.kind {
            NodeKind::Identifier { name } => name.name.as_str(),
            _ => return Ok(false),
        };
        if !matches!(name, "Some" | "Ok" | "Err") {
            return Ok(false);
        }
        let _ = write!(self.buf, "{{ _tag: \"{name}\" as const");
        if let Some(arg) = args.first() {
            self.buf.push_str(", _0: ");
            self.emit_expr(&arg.value)?;
        }
        self.buf.push_str(" }");
        Ok(true)
    }

    /// Q-prim-assoc: lower a primitive associated-conversion call
    /// (`Float.from(x)` / `Int.try_from(s)` / `String.from(c)`) to TS's native
    /// conversion. `from` is an infallible value coercion; `try_from` parses a
    /// `String` and returns the Bock `Result` tagged-object shape
    /// (`{ _tag: "Ok"/"Err" as const, _0: … }`), the `Err` payload a
    /// `ConvertError` (in scope via the `Result[T, ConvertError]` return-type
    /// import). The parse IIFE annotates its `string` param for strict mode.
    /// Returns `true` when handled.
    fn try_emit_primitive_conversion(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((target, method, arg)) =
            crate::generator::primitive_conversion_call(node, callee, args)
        else {
            return Ok(false);
        };
        let arg_str = self.expr_to_string(arg)?;
        let code = match (target, method) {
            ("Float" | "Int" | "String", "from") => format!("({arg_str})"),
            ("Int", "try_from") => format!(
                "((__s: string) => /^[+-]?[0-9]+$/.test(__s.trim()) \
                 ? {{ _tag: \"Ok\" as const, _0: Number.parseInt(__s.trim(), 10) }} \
                 : {{ _tag: \"Err\" as const, _0: new ConvertError({{ message: \
                 `cannot parse '${{__s}}' as Int` }}) }})({arg_str})"
            ),
            ("Float", "try_from") => format!(
                "((__s: string) => {{ const __t = __s.trim(); const __n = Number(__t); \
                 return (__t.length > 0 && !Number.isNaN(__n)) \
                 ? {{ _tag: \"Ok\" as const, _0: __n }} \
                 : {{ _tag: \"Err\" as const, _0: new ConvertError({{ message: \
                 `cannot parse '${{__s}}' as Float` }}) }}; }})({arg_str})"
            ),
            _ => return Ok(false),
        };
        self.buf.push_str(&code);
        Ok(true)
    }

    /// Emit a built-in `Optional`/`Result` method call to its TS form.
    ///
    /// Recognised via the checker's `recv_kind` annotation
    /// ([`crate::generator::desugared_optional_method`] /
    /// [`crate::generator::desugared_result_method`]). Both types use the tagged
    /// representation (`{ _tag, _0 }`), so the lowering is a ternary on `._tag`,
    /// wrapped in a *generic* arrow IIFE — `(<T,>(__c: BockOption<T>) => …)(recv)`
    /// / `(<T, E>(__c: BockResult<T, E>) => …)(recv)` — so the payload type is
    /// inferred from the receiver (strict-mode clean: no implicit `any`) and the
    /// receiver is evaluated exactly once. Returns `true` if handled.
    fn try_emit_container_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        if let Some((recv, method, rest)) =
            crate::generator::desugared_optional_method(node, callee, args)
        {
            self.emit_tagged_container_method(recv, method, rest, "Some", "<T,>", "BockOption<T>")?;
            return Ok(true);
        }
        if let Some((recv, method, rest)) =
            crate::generator::desugared_result_method(node, callee, args)
        {
            self.emit_tagged_container_method(
                recv,
                method,
                rest,
                "Ok",
                "<T, E>",
                "BockResult<T, E>",
            )?;
            return Ok(true);
        }
        Ok(false)
    }

    /// Lower a tagged-container method on `recv`. `present_tag` is the
    /// payload-carrying tag (`"Some"`/`"Ok"`); `type_params` / `param_ty` type
    /// the generic IIFE param (`<T,>` + `BockOption<T>`, or `<T, E>` +
    /// `BockResult<T, E>`).
    fn emit_tagged_container_method(
        &mut self,
        recv: &AIRNode,
        method: &str,
        rest: &[bock_air::AirArg],
        present_tag: &str,
        type_params: &str,
        param_ty: &str,
    ) -> Result<(), CodegenError> {
        // Pure tag tests read the receiver once → emit inline.
        match method {
            "is_some" | "is_ok" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                let _ = write!(self.buf, "._tag === \"{present_tag}\")");
                return Ok(());
            }
            "is_none" | "is_err" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                let _ = write!(self.buf, "._tag !== \"{present_tag}\")");
                return Ok(());
            }
            _ => {}
        }
        let _ = write!(self.buf, "(({type_params}(__c: {param_ty}) => ");
        match method {
            "unwrap" => {
                let _ = write!(
                    self.buf,
                    "__c._tag === \"{present_tag}\" ? __c._0 : (undefined as never)"
                );
            }
            "unwrap_or" => {
                let _ = write!(self.buf, "__c._tag === \"{present_tag}\" ? __c._0 : (");
                if let Some(d) = rest.first() {
                    self.emit_expr(&d.value)?;
                } else {
                    self.buf.push_str("undefined");
                }
                self.buf.push(')');
            }
            "map" => {
                // The callback's parameter type is the concrete payload type the
                // checker already validated; the generic IIFE param `T` is wider
                // (unconstrained), so feed the payload through `as any` to satisfy
                // strict mode without recovering the concrete type here.
                let _ = write!(
                    self.buf,
                    "__c._tag === \"{present_tag}\" ? {{ _tag: \"{present_tag}\" as const, _0: ("
                );
                if let Some(f) = rest.first() {
                    self.emit_expr(&f.value)?;
                } else {
                    self.buf.push_str("(x) => x");
                }
                self.buf.push_str(")(__c._0 as any) } : __c");
            }
            "flat_map" => {
                let _ = write!(self.buf, "__c._tag === \"{present_tag}\" ? (");
                if let Some(f) = rest.first() {
                    self.emit_expr(&f.value)?;
                } else {
                    self.buf.push_str("(x) => x");
                }
                self.buf.push_str(")(__c._0 as any) : __c");
            }
            "map_err" => {
                self.buf
                    .push_str("__c._tag === \"Ok\" ? __c : { _tag: \"Err\" as const, _0: (");
                if let Some(f) = rest.first() {
                    self.emit_expr(&f.value)?;
                } else {
                    self.buf.push_str("(x) => x");
                }
                self.buf.push_str(")(__c._0 as any) }");
            }
            _ => self.buf.push_str("(undefined as never)"),
        }
        self.buf.push_str(")(");
        self.emit_expr(recv)?;
        self.buf.push_str("))");
        Ok(())
    }

    /// Emit a read-only `List` built-in method call to its TS form.
    ///
    /// Mirrors the JS lowering but stays strict-mode clean: the
    /// `Optional`-returning methods (`get`/`first`/`last`/`index_of`) wrap the
    /// receiver in a *generic* arrow IIFE (`<T,>(__r: ReadonlyArray<T>, …):
    /// BockOption<T> => …`) so the element type `T` is inferred from the
    /// receiver and the result is the typed `BockOption<T>` union the `match`
    /// lowering narrows on `._tag`. The receiver is therefore evaluated exactly
    /// once and no parameter is implicitly `any`.
    fn try_emit_list_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest)) =
            crate::generator::desugared_list_method(node, callee, args)
        else {
            return Ok(false);
        };
        match method {
            "len" | "length" | "count" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").length");
            }
            "is_empty" => {
                self.buf.push_str("((");
                self.emit_expr(recv)?;
                self.buf.push_str(").length === 0)");
            }
            "get" => {
                let Some(idx) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<T,>(__r: ReadonlyArray<T>, __i: number): BockOption<T> => \
                     (__i >= 0 && __i < __r.length) ? \
                     { _tag: \"Some\" as const, _0: __r[__i] } : { _tag: \"None\" as const })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&idx.value)?;
                self.buf.push(')');
            }
            "first" => {
                self.buf.push_str(
                    "(<T,>(__r: ReadonlyArray<T>): BockOption<T> => __r.length > 0 ? \
                     { _tag: \"Some\" as const, _0: __r[0] } : { _tag: \"None\" as const })(",
                );
                self.emit_expr(recv)?;
                self.buf.push(')');
            }
            "last" => {
                self.buf.push_str(
                    "(<T,>(__r: ReadonlyArray<T>): BockOption<T> => __r.length > 0 ? \
                     { _tag: \"Some\" as const, _0: __r[__r.length - 1] } : \
                     { _tag: \"None\" as const })(",
                );
                self.emit_expr(recv)?;
                self.buf.push(')');
            }
            "contains" => {
                let Some(x) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").includes(");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "index_of" => {
                let Some(x) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<T,>(__r: ReadonlyArray<T>, __x: T): BockOption<number> => \
                     { const __i = __r.indexOf(__x); return __i >= 0 ? \
                     { _tag: \"Some\" as const, _0: __i } : { _tag: \"None\" as const }; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "concat" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").concat(");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "join" => {
                let Some(sep) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").join(");
                self.emit_expr(&sep.value)?;
                self.buf.push(')');
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Emit an in-place `List` mutator (`push`/`append`, DQ18) to its TS form.
    ///
    /// Recognised via [`crate::generator::desugared_list_mutating_method`].
    /// Bock's `List[T]` lowers to a mutable `Array<T>` (`T[]`), so `recv.push(x)`
    /// lowers directly. The checker types these as `Void` (statement position);
    /// the receiver is a `mut` lvalue (ownership-enforced), evaluated once.
    fn try_emit_list_mutating_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, _method, rest)) =
            crate::generator::desugared_list_mutating_method(node, callee, args)
        else {
            return Ok(false);
        };
        let Some(x) = rest.first() else {
            return Ok(false);
        };
        self.buf.push('(');
        self.emit_expr(recv)?;
        self.buf.push_str(").push(");
        self.emit_expr(&x.value)?;
        self.buf.push(')');
        Ok(true)
    }

    /// Emit a DQ30 in-place `List` mutator
    /// (`pop`/`remove_at`/`insert`/`reverse`/`set`) to its TS form.
    ///
    /// Mirrors the JS lowering (arrays are reference values, so the IIFE
    /// parameter aliases the receiver and mutations are caller-visible) but
    /// stays strict-mode clean: the IIFEs are *generic* arrows over a mutable
    /// `T[]` parameter (not the read-only methods' `ReadonlyArray<T>`), `pop`
    /// returns the typed `BockOption<T>` union (the `T | undefined` from
    /// native `.pop()` is narrowed by the length guard and asserted `as T`),
    /// and `remove_at`'s `splice(i, 1)[0]` is asserted `as T` for
    /// `noUncheckedIndexedAccess` robustness. The bounds checks throw with the
    /// normalized abort message `List.<op>: index <i> out of bounds (len <n>)`
    /// (the DQ23 zero-check convention); `set`'s check is load-bearing because
    /// native index-assign past the end silently extends the array.
    fn try_emit_list_inplace_mutator(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest)) =
            crate::generator::desugared_list_inplace_mutator(node, callee, args)
        else {
            return Ok(false);
        };
        match method {
            "pop" => {
                self.buf.push_str(
                    "(<T,>(__r: T[]): BockOption<T> => __r.length > 0 ? \
                     { _tag: \"Some\" as const, _0: __r.pop() as T } : \
                     { _tag: \"None\" as const })(",
                );
                self.emit_expr(recv)?;
                self.buf.push(')');
            }
            "remove_at" => {
                let Some(idx) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<T,>(__r: T[], __i: number): T => { \
                     if (__i < 0 || __i >= __r.length) { throw new Error(\
                     \"List.remove_at: index \" + __i + \" out of bounds (len \" + __r.length + \")\"); } \
                     return __r.splice(__i, 1)[0] as T; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&idx.value)?;
                self.buf.push(')');
            }
            "insert" => {
                let (Some(idx), Some(x)) = (rest.first(), rest.get(1)) else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<T,>(__r: T[], __i: number, __x: T): void => { \
                     if (__i < 0 || __i > __r.length) { throw new Error(\
                     \"List.insert: index \" + __i + \" out of bounds (len \" + __r.length + \")\"); } \
                     __r.splice(__i, 0, __x); })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&idx.value)?;
                self.buf.push_str(", ");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "reverse" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").reverse()");
            }
            "set" => {
                let (Some(idx), Some(x)) = (rest.first(), rest.get(1)) else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<T,>(__r: T[], __i: number, __x: T): void => { \
                     if (__i < 0 || __i >= __r.length) { throw new Error(\
                     \"List.set: index \" + __i + \" out of bounds (len \" + __r.length + \")\"); } \
                     __r[__i] = __x; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&idx.value)?;
                self.buf.push_str(", ");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Emit a functional (closure-taking) `List` built-in method call to its TS
    /// form.
    ///
    /// Recognised via [`crate::generator::desugared_list_functional_method`].
    /// Mirrors the JS lowering — native `map`/`filter`/`reduce`/`forEach`/`some`/
    /// `every`/`flatMap` with the closure passed *once* on the receiver array, so
    /// `tsc --strict --noImplicitAny` contextually types each callback parameter
    /// from the array's element type (the broken `recv.map(recv, cb)` form both
    /// double-passed the receiver *and* left the params implicitly `any`).
    /// `fold(init, cb)` maps to `reduce(cb, init)`; `find` wraps the native
    /// result into the tagged `BockOption`.
    fn try_emit_list_functional_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest)) =
            crate::generator::desugared_list_functional_method(node, callee, args)
        else {
            return Ok(false);
        };
        match method {
            "map" | "filter" | "for_each" | "any" | "all" | "flat_map" => {
                let Some(cb) = rest.first() else {
                    return Ok(false);
                };
                let native = match method {
                    "map" => "map",
                    "filter" => "filter",
                    "for_each" => "forEach",
                    "any" => "some",
                    "all" => "every",
                    "flat_map" => "flatMap",
                    _ => unreachable!(),
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                let _ = write!(self.buf, ").{native}(");
                self.emit_expr(&cb.value)?;
                self.buf.push(')');
            }
            "reduce" => {
                let Some(cb) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").reduce(");
                self.emit_expr(&cb.value)?;
                self.buf.push(')');
            }
            "fold" => {
                let (Some(init), Some(cb)) = (rest.first(), rest.get(1)) else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").reduce(");
                self.emit_expr(&cb.value)?;
                self.buf.push_str(", ");
                self.emit_expr(&init.value)?;
                self.buf.push(')');
            }
            "find" => {
                self.buf.push_str(
                    "(<T,>(__r: ReadonlyArray<T>, __p: (x: T) => boolean): BockOption<T> => \
                     { const __m = __r.find(__p); return __m === undefined ? \
                     { _tag: \"None\" as const } : { _tag: \"Some\" as const, _0: __m }; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                let Some(cb) = rest.first() else {
                    return Ok(false);
                };
                self.emit_expr(&cb.value)?;
                self.buf.push(')');
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Emit a built-in `Map[K, V]` method call to its TS form (native `Map`).
    ///
    /// Recognised via [`crate::generator::desugared_map_method`] (gated on
    /// `recv_kind = "Map"`) and wired *before* [`Self::try_emit_list_method`].
    /// Mirrors the JS lowering but types the generic IIFEs (`<K, V>` params,
    /// `BockOption<V>` return for `get`) so `tsc --strict` narrows correctly.
    /// `get` returns the tagged `Optional` rep (`{ _tag: "Some" as const, _0: v
    /// }` / `{ _tag: "None" as const }`); mutating methods (`set`/`delete`/
    /// `merge`) mutate in place and return the receiver. Returns `true` if
    /// handled.
    fn try_emit_map_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest)) = crate::generator::desugared_map_method(node, callee, args)
        else {
            return Ok(false);
        };
        match method {
            "len" | "length" | "count" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").size");
            }
            "is_empty" => {
                self.buf.push_str("((");
                self.emit_expr(recv)?;
                self.buf.push_str(").size === 0)");
            }
            "contains_key" => {
                let Some(k) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").has(");
                self.emit_expr(&k.value)?;
                self.buf.push(')');
            }
            "get" => {
                let Some(k) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __k: K): BockOption<V> => __m.has(__k) ? \
                     { _tag: \"Some\" as const, _0: __m.get(__k)! } : { _tag: \"None\" as const })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&k.value)?;
                self.buf.push(')');
            }
            "set" => {
                let (Some(k), Some(v)) = (rest.first(), rest.get(1)) else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __k: K, __v: V): Map<K, V> => \
                     { __m.set(__k, __v); return __m; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&k.value)?;
                self.buf.push_str(", ");
                self.emit_expr(&v.value)?;
                self.buf.push(')');
            }
            "delete" => {
                let Some(k) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __k: K): Map<K, V> => \
                     { __m.delete(__k); return __m; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&k.value)?;
                self.buf.push(')');
            }
            "merge" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __o: Map<K, V>): Map<K, V> => \
                     { for (const [__k, __v] of __o) __m.set(__k, __v); return __m; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "filter" => {
                let Some(f) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __f: (k: K, v: V) => boolean): Map<K, V> => \
                     { const __r = new Map<K, V>(); \
                     for (const [__k, __v] of __m) if (__f(__k, __v)) __r.set(__k, __v); \
                     return __r; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&f.value)?;
                self.buf.push(')');
            }
            "keys" => {
                self.buf.push_str("[...(");
                self.emit_expr(recv)?;
                self.buf.push_str(").keys()]");
            }
            "values" => {
                self.buf.push_str("[...(");
                self.emit_expr(recv)?;
                self.buf.push_str(").values()]");
            }
            "entries" | "to_list" => {
                self.buf.push_str("[...(");
                self.emit_expr(recv)?;
                self.buf.push_str(").entries()]");
            }
            "for_each" => {
                let Some(f) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<K, V>(__m: Map<K, V>, __f: (k: K, v: V) => void): void => \
                     { for (const [__k, __v] of __m) __f(__k, __v); })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&f.value)?;
                self.buf.push(')');
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Emit a built-in `Set[E]` method call to its TS form (native `Set`).
    ///
    /// Recognised via [`crate::generator::desugared_set_method`] (gated on
    /// `recv_kind = "Set"`) and wired *before* [`Self::try_emit_list_method`].
    /// Generic-typed IIFEs (`<E>` params) keep `tsc --strict` happy. Mutating
    /// methods (`add`/`remove`) mutate in place and return the receiver.
    fn try_emit_set_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest)) = crate::generator::desugared_set_method(node, callee, args)
        else {
            return Ok(false);
        };
        match method {
            "len" | "length" | "count" => {
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").size");
            }
            "is_empty" => {
                self.buf.push_str("((");
                self.emit_expr(recv)?;
                self.buf.push_str(").size === 0)");
            }
            "contains" => {
                let Some(x) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push('(');
                self.emit_expr(recv)?;
                self.buf.push_str(").has(");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "add" => {
                let Some(x) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__s: Set<E>, __x: E): Set<E> => { __s.add(__x); return __s; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "remove" => {
                let Some(x) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__s: Set<E>, __x: E): Set<E> => { __s.delete(__x); return __s; })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&x.value)?;
                self.buf.push(')');
            }
            "union" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__a: Set<E>, __b: Set<E>): Set<E> => new Set<E>([...__a, ...__b]))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "intersection" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__a: Set<E>, __b: Set<E>): Set<E> => \
                     new Set<E>([...__a].filter((__x) => __b.has(__x))))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "difference" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__a: Set<E>, __b: Set<E>): Set<E> => \
                     new Set<E>([...__a].filter((__x) => !__b.has(__x))))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "is_subset" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__a: Set<E>, __b: Set<E>): boolean => \
                     [...__a].every((__x) => __b.has(__x)))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "is_superset" => {
                let Some(o) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__a: Set<E>, __b: Set<E>): boolean => \
                     [...__b].every((__x) => __a.has(__x)))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&o.value)?;
                self.buf.push(')');
            }
            "filter" => {
                let Some(f) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__s: Set<E>, __f: (x: E) => boolean): Set<E> => \
                     new Set<E>([...__s].filter(__f)))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&f.value)?;
                self.buf.push(')');
            }
            "map" => {
                let Some(f) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__s: Set<E>, __f: (x: E) => E): Set<E> => \
                     new Set<E>([...__s].map(__f)))(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&f.value)?;
                self.buf.push(')');
            }
            "to_list" => {
                self.buf.push_str("[...(");
                self.emit_expr(recv)?;
                self.buf.push_str(")]");
            }
            "for_each" => {
                let Some(f) = rest.first() else {
                    return Ok(false);
                };
                self.buf.push_str(
                    "(<E>(__s: Set<E>, __f: (x: E) => void): void => \
                     { for (const __x of __s) __f(__x); })(",
                );
                self.emit_expr(recv)?;
                self.buf.push_str(", ");
                self.emit_expr(&f.value)?;
                self.buf.push(')');
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Lower a primitive trait-bridge method call (`compare`/`eq`/`to_string`/
    /// `display` on a primitive receiver) to its TS form.
    ///
    /// Mirrors the JS lowering, but uses `as const` tags so the ternary's type
    /// is the discriminated `Ordering` union `tsc` can narrow on `._tag` in the
    /// match. `eq` → `===`; `to_string`/`display` → `String(x)`.
    /// Lower a desugared `String` built-in method call (`recv_kind =
    /// "Primitive:String"`) to its native TypeScript string op. Wired into the
    /// `Call` arm *before* `try_emit_list_method` so a String receiver's
    /// `len`/`contains`/`is_empty` dispatch here, not through the List path.
    ///
    /// `len` is the Unicode SCALAR count (`[...s].length`, iterating by code
    /// point) per spec §18.3 — not `s.length` (UTF-16 code units). `byte_len` is
    /// the UTF-8 byte count via `TextEncoder`. `replace` replaces ALL occurrences
    /// (`replaceAll`). `split` returns a TS array, the List runtime rep.
    ///
    /// Gated on `recv_kind = "Primitive:String"` directly (not the cross-backend
    /// [`crate::generator::desugared_string_method`] subset) so TS can lower the
    /// wider resolved String surface — `slice`/`substring`/`char_at`/`index_of`/
    /// `repeat`/`reverse`/`trim_start`/`trim_end` — to native ops, matching the
    /// Rust backend. The emitted forms are kept type-clean under `--strict`: the
    /// IIFE params are annotated (`number`/`string`) so no implicit `any` arises,
    /// and `char_at`/`index_of` return the typed `BockOption<…>` union (`{ _tag:
    /// "Some" as const, _0: v }` / `{ _tag: "None" as const }`).
    fn try_emit_string_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        if crate::generator::primitive_recv_kind(node) != Some("String") {
            return Ok(false);
        }
        let Some((recv, field, rest)) = crate::generator::desugared_self_call(callee, args) else {
            return Ok(false);
        };
        let method = field.name.as_str();
        let recv_str = self.expr_to_string(recv)?;
        let arg0 = |this: &mut Self| -> Result<Option<String>, CodegenError> {
            rest.first()
                .map(|a| this.expr_to_string(&a.value))
                .transpose()
        };
        let code = match method {
            "len" | "length" | "count" => format!("[...({recv_str})].length"),
            "byte_len" => format!("new TextEncoder().encode({recv_str}).length"),
            "is_empty" => format!("(({recv_str}).length === 0)"),
            "to_upper" => format!("({recv_str}).toUpperCase()"),
            "to_lower" => format!("({recv_str}).toLowerCase()"),
            "trim" => format!("({recv_str}).trim()"),
            "trim_start" => format!("({recv_str}).trimStart()"),
            "trim_end" => format!("({recv_str}).trimEnd()"),
            "reverse" => format!("[...({recv_str})].reverse().join('')"),
            "to_string" | "display" => format!("String({recv_str})"),
            "repeat" => {
                let Some(n) = arg0(self)? else {
                    return Ok(false);
                };
                format!("({recv_str}).repeat({n})")
            }
            "contains" => {
                let Some(p) = arg0(self)? else {
                    return Ok(false);
                };
                format!("({recv_str}).includes({p})")
            }
            "starts_with" => {
                let Some(p) = arg0(self)? else {
                    return Ok(false);
                };
                format!("({recv_str}).startsWith({p})")
            }
            "ends_with" => {
                let Some(p) = arg0(self)? else {
                    return Ok(false);
                };
                format!("({recv_str}).endsWith({p})")
            }
            "replace" => {
                let Some(from) = arg0(self)? else {
                    return Ok(false);
                };
                let Some(to) = rest
                    .get(1)
                    .map(|a| self.expr_to_string(&a.value))
                    .transpose()?
                else {
                    return Ok(false);
                };
                format!("({recv_str}).replaceAll({from}, {to})")
            }
            "split" => {
                let Some(sep) = arg0(self)? else {
                    return Ok(false);
                };
                format!("({recv_str}).split({sep})")
            }
            // `slice`/`substring(start, end)`: scalar-index half-open substring
            // (spec §18.3 — indices count Unicode scalars). Iterate by code point.
            "slice" | "substring" => {
                let Some(start) = arg0(self)? else {
                    return Ok(false);
                };
                let Some(end) = rest
                    .get(1)
                    .map(|a| self.expr_to_string(&a.value))
                    .transpose()?
                else {
                    return Ok(false);
                };
                format!("[...({recv_str})].slice({start}, {end}).join('')")
            }
            // `char_at(i)` returns `Optional[Char]` — `None` when out of range.
            "char_at" => {
                let Some(i) = arg0(self)? else {
                    return Ok(false);
                };
                self.needs_runtime_optional = true;
                format!(
                    "((__s: string[], __i: number): BockOption<string> => __i >= 0 && __i < __s.length ? {{ _tag: \"Some\" as const, _0: __s[__i] }} : {{ _tag: \"None\" as const }})([...({recv_str})], {i})"
                )
            }
            // `index_of(needle)` returns `Optional[Int]` — the scalar index of the
            // first match, or `None`. TS `indexOf` is a UTF-16 code-unit offset, so
            // convert it to a scalar index via the code-point prefix length.
            "index_of" => {
                let Some(p) = arg0(self)? else {
                    return Ok(false);
                };
                self.needs_runtime_optional = true;
                format!(
                    "((__s: string, __p: string): BockOption<number> => {{ const __b = __s.indexOf(__p); return __b >= 0 ? {{ _tag: \"Some\" as const, _0: [...__s.slice(0, __b)].length }} : {{ _tag: \"None\" as const }}; }})({recv_str}, {p})"
                )
            }
            _ => return Ok(false),
        };
        self.buf.push_str(&code);
        Ok(true)
    }

    /// Lower a desugared numeric/`Char`/`Bool` primitive method (`recv_kind =
    /// "Primitive:Int" | "Primitive:Float" | "Primitive:Char" | "Primitive:Bool"`)
    /// to its native TypeScript form. Covers the conversion and math methods the
    /// checker resolves on the scalar primitives — `to_float`/`to_int`/`abs`/`min`/
    /// `max`/`clamp`/`floor`/`ceil`/`round`/`sqrt`/… — none of which exist as
    /// methods on a TS `number`/`boolean`/string-char. Wired into the `Call` arm
    /// alongside [`Self::try_emit_string_method`], before the generic
    /// desugared-self-call fall-through (which would emit `n.to_float(n)`).
    /// `compare`/`eq`/`to_string`/`display`/`hash_code` stay on the primitive
    /// *bridge* path. The emitted forms are type-clean (`number` in, `number` out).
    fn try_emit_numeric_method(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let prim = match crate::generator::primitive_recv_kind(node) {
            Some(p @ ("Int" | "Float" | "Char" | "Bool")) => p,
            _ => return Ok(false),
        };
        let Some((recv, field, rest)) = crate::generator::desugared_self_call(callee, args) else {
            return Ok(false);
        };
        let method = field.name.as_str();
        let recv_str = self.expr_to_string(recv)?;
        let arg = |this: &mut Self, i: usize| -> Result<Option<String>, CodegenError> {
            rest.get(i)
                .map(|a| this.expr_to_string(&a.value))
                .transpose()
        };
        let code = match (prim, method) {
            // Conversions. Both `Int` and `Float` are a TS `number`; `to_int`
            // truncates toward zero (Bock `Float.to_int`).
            ("Int", "to_float") => format!("({recv_str})"),
            ("Float", "to_int") => format!("Math.trunc({recv_str})"),
            ("Char", "to_int") => format!("(({recv_str}).codePointAt(0) ?? 0)"),
            ("Bool", "to_int") => format!("(({recv_str}) ? 1 : 0)"),
            // Int math.
            ("Int", "abs") => format!("Math.abs({recv_str})"),
            ("Int" | "Float", "min") => {
                let Some(o) = arg(self, 0)? else {
                    return Ok(false);
                };
                format!("Math.min({recv_str}, {o})")
            }
            ("Int" | "Float", "max") => {
                let Some(o) = arg(self, 0)? else {
                    return Ok(false);
                };
                format!("Math.max({recv_str}, {o})")
            }
            ("Int" | "Float", "clamp") => {
                let (Some(lo), Some(hi)) = (arg(self, 0)?, arg(self, 1)?) else {
                    return Ok(false);
                };
                format!("Math.min(Math.max({recv_str}, {lo}), {hi})")
            }
            ("Int", "shift_left") => {
                let Some(o) = arg(self, 0)? else {
                    return Ok(false);
                };
                format!("(({recv_str}) << ({o}))")
            }
            ("Int", "shift_right") => {
                let Some(o) = arg(self, 0)? else {
                    return Ok(false);
                };
                format!("(({recv_str}) >> ({o}))")
            }
            // Float math.
            ("Float", "abs") => format!("Math.abs({recv_str})"),
            ("Float", "floor") => format!("Math.floor({recv_str})"),
            ("Float", "ceil") => format!("Math.ceil({recv_str})"),
            ("Float", "round") => format!("Math.round({recv_str})"),
            ("Float", "sqrt") => format!("Math.sqrt({recv_str})"),
            ("Float", "is_nan") => format!("Number.isNaN({recv_str})"),
            ("Float", "is_infinite") => format!("(!Number.isFinite({recv_str}))"),
            // Bool.
            ("Bool", "negate") => format!("(!({recv_str}))"),
            // Char (a one-code-point TS string).
            ("Char", "to_upper") => format!("({recv_str}).toUpperCase()"),
            ("Char", "to_lower") => format!("({recv_str}).toLowerCase()"),
            ("Char", "is_alpha") => format!("(/\\p{{L}}/u.test({recv_str}))"),
            ("Char", "is_digit") => format!("(/[0-9]/.test({recv_str}))"),
            ("Char", "is_whitespace") => format!("(/\\s/.test({recv_str}))"),
            _ => return Ok(false),
        };
        self.buf.push_str(&code);
        Ok(true)
    }

    fn try_emit_primitive_bridge(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest, prim)) =
            crate::generator::primitive_bridge_call(node, callee, args)
        else {
            return Ok(false);
        };
        self.emit_bridge_method(recv, method, rest, Some(prim))
    }

    /// Lower a sealed-core-trait bridge method on a *bounded generic type
    /// variable* (`a.eq(b)` / `a.compare(b)` inside `eq_check[T: Equatable]`) to
    /// its TS form (GAP-C). The method body is identical to the `Primitive:<Ty>`
    /// bridge; the `<T extends Equatable>` bound is separately dropped at the
    /// signature (see `generic_params_to_ts`). Fires only when the bound trait is
    /// sealed-core and NOT a user-declared trait.
    fn try_emit_trait_bound_bridge(
        &mut self,
        node: &AIRNode,
        callee: &AIRNode,
        args: &[bock_air::AirArg],
    ) -> Result<bool, CodegenError> {
        let Some((recv, method, rest, _tr)) =
            crate::generator::trait_bound_bridge_call(node, callee, args, &self.trait_decls)
        else {
            return Ok(false);
        };
        // DQ29: unlike the `Primitive:<Ty>` bridge (whose receiver is a known
        // scalar, where `===` is correct), a bounded `T: Equatable` receiver
        // may be instantiated with a RECORD — `===` would be reference
        // identity — so `a.eq(b)` lowers through the `__bockEq` structural
        // helper, which falls back to `===` for primitives.
        if method == "eq" {
            let Some(other) = rest.first() else {
                return Ok(false);
            };
            let recv_str = self.expr_to_string(recv)?;
            let other = self.expr_to_string(&other.value)?;
            let _ = write!(self.buf, "__bockEq({recv_str}, {other})");
            return Ok(true);
        }
        // Q-bounded-comparable-codegen: a bounded `T: Comparable` `compare`
        // receiver may be instantiated with a RECORD whose ordering lives in its
        // own `compare` method — the native `<`/`===` ternary the
        // `emit_bridge_method` `compare` arm emits is correct ONLY for a
        // primitive instantiation (object `<` coerces to `NaN`; `===` is
        // reference identity). Route through `__bockCompare`, which calls the
        // value's `compare` method when present and falls back to the native
        // ternary for primitives.
        if method == "compare" {
            let Some(other) = rest.first() else {
                return Ok(false);
            };
            let recv_str = self.expr_to_string(recv)?;
            let other = self.expr_to_string(&other.value)?;
            self.needs_runtime_compare = true;
            let _ = write!(self.buf, "__bockCompare({recv_str}, {other})");
            return Ok(true);
        }
        self.emit_bridge_method(recv, method, rest, None)
    }

    /// Shared body of the primitive / trait-bound bridges: emit the native TS form
    /// of `compare` (the `Ordering` ternary), `eq` (`===`), or `to_string`/
    /// `display` (`String(..)`).
    ///
    /// `widen_prim` is the receiver's primitive type name (`"Int"`, `"Float"`,
    /// …) when this is the concrete `Primitive:<Ty>` bridge, or `None` for the
    /// trait-bound bridge (whose receiver is a generic `T`). When present, the
    /// `eq` arm widens the receiver with a `as <ts-type>` assertion before
    /// `===`: two distinct *literal* operands (`(3).eq(4)`) would otherwise be
    /// inferred as the literal types `3`/`4`, which `tsc` rejects under
    /// `strictNullChecks` as TS2367 ("this comparison appears to be
    /// unintentional because the types '3' and '4' have no overlap"). The cast
    /// widens the `3` to `number`, so the comparison is between `number` and a
    /// literal — overlapping, hence accepted — while the runtime `===` is
    /// unchanged. (Q-ts-primitive-eq-literal-overlap.)
    fn emit_bridge_method(
        &mut self,
        recv: &AIRNode,
        method: &str,
        rest: &[bock_air::AirArg],
        widen_prim: Option<&str>,
    ) -> Result<bool, CodegenError> {
        let recv_str = self.expr_to_string(recv)?;
        match method {
            "compare" => {
                let Some(other) = rest.first() else {
                    return Ok(false);
                };
                let other = self.expr_to_string(&other.value)?;
                let _ = write!(
                    self.buf,
                    "(({recv_str}) < ({other}) ? {{ _tag: \"Less\" as const }} : \
                     (({recv_str}) === ({other}) ? {{ _tag: \"Equal\" as const }} : \
                     {{ _tag: \"Greater\" as const }}))"
                );
            }
            "eq" => {
                let Some(other) = rest.first() else {
                    return Ok(false);
                };
                let other = self.expr_to_string(&other.value)?;
                // Widen the receiver to its primitive TS type so two distinct
                // literal operands (`(3).eq(4)`) compare as `number === 3`
                // rather than the literal-only `3 === 4` (TS2367). See the
                // method doc-comment.
                if let Some(prim) = widen_prim {
                    let ts_ty = self.map_type_name(prim);
                    let _ = write!(self.buf, "(({recv_str} as {ts_ty}) === ({other}))");
                } else {
                    let _ = write!(self.buf, "(({recv_str}) === ({other}))");
                }
            }
            "to_string" | "display" => {
                let _ = write!(self.buf, "String({recv_str})");
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    // ── Type emission ────────────────────────────────────────────────────────

    /// Emit a type expression from an AIR type node to a TS type string.
    fn type_to_ts(&self, node: &AIRNode) -> String {
        match &node.kind {
            NodeKind::TypeNamed { path, args } => {
                let name = path
                    .segments
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<_>>()
                    .join(".");
                let ts_name = self.map_type_name(&name);
                if args.is_empty() {
                    ts_name
                } else {
                    let arg_strs: Vec<String> = args.iter().map(|a| self.type_to_ts(a)).collect();
                    format!("{ts_name}<{}>", arg_strs.join(", "))
                }
            }
            NodeKind::TypeTuple { elems } => {
                let elem_strs: Vec<String> = elems.iter().map(|e| self.type_to_ts(e)).collect();
                format!("[{}]", elem_strs.join(", "))
            }
            NodeKind::TypeFunction { params, ret, .. } => {
                let param_strs: Vec<String> = params
                    .iter()
                    .enumerate()
                    .map(|(i, p)| format!("arg{i}: {}", self.type_to_ts(p)))
                    .collect();
                format!("({}) => {}", param_strs.join(", "), self.type_to_ts(ret))
            }
            NodeKind::TypeOptional { inner } => {
                // `T?` lowers to the tagged Optional runtime union, not `T |
                // null`: the value is `{ _tag: "Some", _0: v }` / `{ _tag:
                // "None" }`, so the type must describe that. See
                // `OPTIONAL_RUNTIME_TS`.
                format!("BockOption<{}>", self.type_to_ts(inner))
            }
            NodeKind::TypeSelf => self
                .trait_self_subst
                .clone()
                .unwrap_or_else(|| "this".into()),
            _ => "unknown".into(),
        }
    }

    /// Map Bock type names to TS equivalents.
    /// True when the real `core.compare.Ordering` enum is reachable in this
    /// program (its `Less` variant is a registered user enum variant). When
    /// `core.compare` is `use`d, the actual `Ordering` union type is emitted and
    /// imported; otherwise the prelude form (a bare structural `{ _tag: … }`
    /// union) is used. Mirrors the rust/go backends.
    fn ordering_enum_reachable(&self) -> bool {
        self.enum_variants
            .get("Less")
            .is_some_and(|info| info.enum_name == "Ordering")
    }

    fn map_type_name(&self, name: &str) -> String {
        match name {
            "Int" => "number".into(),
            "Float" => "number".into(),
            "Bool" => "boolean".into(),
            "String" => "string".into(),
            // Bock `Char` has no distinct TS runtime type; a Char literal
            // (`'A'`) emits as a single-character string and every Char method
            // (`to_upper`, `is_alpha`, …) is implemented as a string op, so the
            // type maps to `string` for consistency.
            "Char" => "string".into(),
            "Void" | "Unit" => "void".into(),
            "List" => "Array".into(),
            "Map" => "Map".into(),
            "Set" => "Set".into(),
            "Any" => "any".into(),
            "Never" => "never".into(),
            // `Result[T, E]` lowers to the tagged-union runtime type, mirroring
            // `Optional[T]` → `BockOption<T>` (see `RESULT_RUNTIME_TS`).
            "Result" => "BockResult".into(),
            // The spelled-out `Optional[T]` (a named type application, distinct
            // from the `T?` shorthand handled by the `TypeOptional` arm) must
            // also lower to the tagged runtime union `BockOption<T>`, matching
            // the emitted `{ _tag: "Some", _0: v }` / `{ _tag: "None" }` value
            // representation. Without this it emitted a bare `Optional<T>`
            // (TS2304, undefined name).
            "Optional" => "BockOption".into(),
            // §18.3.1 builtin time types: a `Duration` value is stored as a
            // signed-nanosecond `number`, and an `Instant` likewise lowers to a
            // `number` (`performance.now() * 1e6`). They are NOT user-defined
            // types, so as annotations (e.g. on a `Clock` handler's
            // `now_monotonic()` / `sleep(duration: Duration)`) they must render
            // `number`, not the undefined identifiers `Duration`/`Instant`.
            "Duration" | "Instant" => "number".into(),
            // The prelude `Ordering` enum: when the real `core.compare.Ordering`
            // is NOT reachable (no `use core.compare`), its variants lower to a
            // bare structural tagged union (`{ _tag: "Less" }` …), so a
            // `-> Ordering` annotation must render that union — the bare
            // `Ordering` is an undefined TS name (TS2304). When the enum IS
            // reachable the imported `Ordering` union type is in scope and keeps
            // its name. (Q-prelude-impl-missing-import.)
            "Ordering" if !self.ordering_enum_reachable() => {
                "({ _tag: \"Less\" } | { _tag: \"Equal\" } | { _tag: \"Greater\" })".into()
            }
            other => other.into(),
        }
    }

    /// Emit an AST TypeExpr to a TS type string (for record fields).
    fn ast_type_to_ts(&self, ty: &TypeExpr) -> String {
        match ty {
            TypeExpr::Named { path, args, .. } => {
                let name = path
                    .segments
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<_>>()
                    .join(".");
                let ts_name = self.map_type_name(&name);
                if args.is_empty() {
                    ts_name
                } else {
                    let arg_strs: Vec<String> =
                        args.iter().map(|a| self.ast_type_to_ts(a)).collect();
                    format!("{ts_name}<{}>", arg_strs.join(", "))
                }
            }
            TypeExpr::Tuple { elems, .. } => {
                let elem_strs: Vec<String> = elems.iter().map(|e| self.ast_type_to_ts(e)).collect();
                format!("[{}]", elem_strs.join(", "))
            }
            TypeExpr::Function { params, ret, .. } => {
                let param_strs: Vec<String> = params
                    .iter()
                    .enumerate()
                    .map(|(i, p)| format!("arg{i}: {}", self.ast_type_to_ts(p)))
                    .collect();
                format!(
                    "({}) => {}",
                    param_strs.join(", "),
                    self.ast_type_to_ts(ret)
                )
            }
            TypeExpr::Optional { inner, .. } => {
                // See the `TypeOptional` arm of `type_to_ts`: the tagged
                // Optional union must match the emitted tagged-object value.
                format!("BockOption<{}>", self.ast_type_to_ts(inner))
            }
            TypeExpr::SelfType { .. } => "this".into(),
        }
    }

    /// Emit generic parameter list: `<T, U extends Foo>`.
    /// Resolve the generic params that apply to an `impl` target: the impl's own
    /// params when present (`impl[T] Box[T] { ... }`), else the params declared
    /// on the target record/enum (`impl Box { ... }` where `T` lives on
    /// `record Box[T]`). Empty for a non-generic target.
    fn impl_target_generics(
        &self,
        impl_params: &[bock_ast::GenericParam],
        target_name: &str,
    ) -> Vec<bock_ast::GenericParam> {
        if !impl_params.is_empty() {
            return impl_params.to_vec();
        }
        self.generic_decls
            .get(target_name)
            .cloned()
            .unwrap_or_default()
    }

    /// Render a *use-site* generic argument list (`<T>`, `<T, U>`) — the bare
    /// param names, no `extends` bounds — for a type reference like `Box<T>`.
    /// Empty string for no params.
    fn generic_param_args(&self, params: &[bock_ast::GenericParam]) -> String {
        if params.is_empty() {
            return String::new();
        }
        let names: Vec<&str> = params.iter().map(|p| p.name.name.as_str()).collect();
        format!("<{}>", names.join(", "))
    }

    /// Render the combined generic-parameter declaration for an impl method's
    /// prototype function: the target type's params (with bounds) followed by
    /// the method's own params. Used because the prototype assignment lives
    /// outside the class, so its function must re-declare the class's `<T>`.
    fn merge_generic_params_to_ts(
        &self,
        target_params: &[bock_ast::GenericParam],
        method_params: &[bock_ast::GenericParam],
    ) -> String {
        let mut merged = target_params.to_vec();
        merged.extend(method_params.iter().cloned());
        self.generic_params_to_ts(&merged)
    }

    fn generic_params_to_ts(&self, params: &[bock_ast::GenericParam]) -> String {
        if params.is_empty() {
            return String::new();
        }
        let items: Vec<String> = params
            .iter()
            .map(|p| {
                // Drop a compiler-provided sealed-core bound (`Equatable`/…) with no
                // user `impl`: TS has no such type, so `<T extends Equatable>` fails
                // `tsc` with TS2304 (GAP-C). The method is lowered to a native
                // operator (`===`/comparison) by `try_emit_trait_bound_bridge`, so
                // an unconstrained `<T>` is correct. A user-declared trait of the
                // same name keeps its `extends` bound.
                let bounds: Vec<String> = p
                    .bounds
                    .iter()
                    .map(|b| {
                        b.segments
                            .iter()
                            .map(|s| s.name.as_str())
                            .collect::<Vec<_>>()
                            .join(".")
                    })
                    .filter(|name| {
                        !crate::generator::is_unimplemented_sealed_core_trait(
                            name,
                            &self.trait_decls,
                        )
                    })
                    .collect();
                if bounds.is_empty() {
                    p.name.name.clone()
                } else {
                    format!("{} extends {}", p.name.name, bounds.join(" & "))
                }
            })
            .collect();
        format!("<{}>", items.join(", "))
    }

    /// Use-site type-argument list for a generic declaration: just the
    /// parameter names (`<T>`, `<T, U>`), with no `extends` bounds. This is the
    /// form a *reference* to the generic type takes (e.g. a variant interface
    /// named inside its enum's union alias, or a constructor factory's return
    /// type), as distinct from [`Self::generic_params_to_ts`], which is the
    /// *declaration* form that carries the bounds.
    ///
    /// Mismatching the two — declaring `interface Box_Full<T>` but referencing
    /// it as a bare `Box_Full` in the union alias `type Box<T> = Box_Full | …`
    /// — fails `tsc` with TS2314 ("Generic type requires N type argument(s)"),
    /// because the alias body supplies the wrong type-argument arity. Both the
    /// union alias and the variant factories must reference each variant
    /// interface at its declared arity, which this helper supplies.
    fn generic_args_to_ts(&self, params: &[bock_ast::GenericParam]) -> String {
        if params.is_empty() {
            return String::new();
        }
        let items: Vec<String> = params.iter().map(|p| p.name.name.clone()).collect();
        format!("<{}>", items.join(", "))
    }

    // ── Top-level dispatch ──────────────────────────────────────────────────

    fn emit_node(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        self.mark_span(node.span);
        match &node.kind {
            NodeKind::Module { items, imports, .. } => {
                // Field/method name-collision set (camelCased). Pre-seeded
                // program-wide by `generate_project` so a call site in one file
                // agrees with the renamed method declared in another; extended
                // here so the single-module `generate_module` path (no pre-seed)
                // is also covered.
                self.field_method_collisions
                    .extend(crate::generator::collect_record_field_names(
                        node,
                        to_camel_case,
                    ));
                if self.per_module {
                    // Per-module native-import path (the real build): each module
                    // is emitted to its own `.ts` file and the runtime
                    // types/helpers live in the shared `_bock_runtime.ts`. Record
                    // which the module references; `generate_project` emits them
                    // once into the shared module, and `emit_esm_imports` imports
                    // them here.
                    if module_uses_optional(items) {
                        self.needs_runtime_optional = true;
                    }
                    if module_uses_result(items) {
                        self.needs_runtime_result = true;
                    }
                    if module_uses_concurrency(items) {
                        self.needs_runtime_concurrency = true;
                    }
                    if module_uses_range(items) {
                        self.needs_runtime_range = true;
                    }
                    if module_uses_eq(items) {
                        self.needs_runtime_eq = true;
                    }
                    if module_uses_compare(items) {
                        self.needs_runtime_compare = true;
                    }
                    if module_uses_str(items) {
                        self.needs_runtime_str = true;
                    }
                    self.emit_esm_imports(imports)?;
                } else {
                    // Single-module self-contained emit (`generate_module`, used
                    // by unit tests): the module's runtime preludes are inlined
                    // into this one file and `ImportDecl`s are dropped. Each
                    // prelude is inlined at most once, gated on a ctx flag (a
                    // duplicate `type Option<T>` would be a TS redeclaration).
                    if !self.optional_runtime_emitted && module_uses_optional(items) {
                        self.buf.push_str(OPTIONAL_RUNTIME_TS);
                        self.buf.push('\n');
                        self.optional_runtime_emitted = true;
                    }
                    if !self.result_runtime_emitted && module_uses_result(items) {
                        self.buf.push_str(RESULT_RUNTIME_TS);
                        self.buf.push('\n');
                        self.result_runtime_emitted = true;
                    }
                    if !self.concurrency_runtime_emitted && module_uses_concurrency(items) {
                        self.buf.push_str(CONCURRENCY_RUNTIME_TS);
                        self.buf.push('\n');
                        self.concurrency_runtime_emitted = true;
                    }
                    if !self.range_runtime_emitted && module_uses_range(items) {
                        self.buf.push_str(RANGE_RUNTIME_TS);
                        self.buf.push('\n');
                        self.range_runtime_emitted = true;
                    }
                    if !self.compare_runtime_emitted && module_uses_compare(items) {
                        self.buf.push_str(COMPARE_RUNTIME_TS);
                        self.buf.push('\n');
                        self.compare_runtime_emitted = true;
                    }
                    if !self.str_runtime_emitted && module_uses_str(items) {
                        self.buf.push_str(STR_RUNTIME_TS);
                        self.buf.push('\n');
                        self.str_runtime_emitted = true;
                    }
                    if !self.eq_runtime_emitted && module_uses_eq(items) {
                        self.buf.push_str(EQ_RUNTIME_TS);
                        self.buf.push('\n');
                        self.eq_runtime_emitted = true;
                    }
                }
                // `@test` functions are transpiled separately into Vitest/Jest
                // test files (project mode, §20.6.2 — see `generate_tests`), never
                // into the runtime module tree: their `expect(...)` assertion DSL
                // has no runtime definition in the emitted source.
                let mut first = true;
                for item in items.iter() {
                    if crate::generator::fn_is_test(item) {
                        continue;
                    }
                    if !first {
                        self.buf.push('\n');
                    }
                    first = false;
                    self.emit_node(item)?;
                }
                // Per-module path: re-export enum-variant values (everything else
                // exports inline). Emitted once after all items.
                if self.per_module {
                    self.emit_trailing_exports();
                }
                Ok(())
            }
            NodeKind::ImportDecl { .. } => {
                // Resolved by the real ESM imports emitted up front by
                // `emit_esm_imports` (per-module path), or dropped entirely in
                // the single-module self-contained path. Either way a no-op here.
                Ok(())
            }
            NodeKind::FnDecl {
                visibility,
                is_async,
                name,
                generic_params,
                params,
                return_type,
                effect_clause,
                where_clause,
                body,
                ..
            } => {
                // Fold any `where`-clause trait bounds onto the generic params so
                // the `<T extends Bound>` constraint is emitted for a
                // `where`-bounded fn — local or imported (the imported fn is
                // emitted in its own module file with its reconstructed
                // `where`-clause, PR #286).
                let merged = crate::generator::merge_where_bounds_into_generics(
                    generic_params,
                    where_clause,
                );
                self.emit_fn_decl(
                    *visibility,
                    *is_async,
                    &name.name,
                    &merged,
                    params,
                    return_type.as_deref(),
                    effect_clause,
                    body,
                    false,
                )
            }
            NodeKind::RecordDecl {
                visibility,
                name,
                generic_params,
                fields,
                ..
            } => {
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                self.record_names.insert(name.name.clone());
                if fields.is_empty() {
                    self.writeln(&format!("{export}class {}{generics} {{}}", name.name));
                } else {
                    self.writeln(&format!("{export}class {}{generics} {{", name.name));
                    self.indent += 1;
                    for f in fields {
                        let ty = self.ast_type_to_ts(&f.ty);
                        self.writeln(&format!("{}: {};", f.name.name, ty));
                    }
                    let init_fields: Vec<String> = fields
                        .iter()
                        .map(|f| format!("{}: {}", f.name.name, self.ast_type_to_ts(&f.ty)))
                        .collect();
                    let destructure: Vec<&str> =
                        fields.iter().map(|f| f.name.name.as_str()).collect();
                    self.writeln(&format!(
                        "constructor({{ {} }}: {{ {} }}) {{",
                        destructure.join(", "),
                        init_fields.join("; "),
                    ));
                    self.indent += 1;
                    for fname in &destructure {
                        self.writeln(&format!("this.{fname} = {fname};"));
                    }
                    self.indent -= 1;
                    self.writeln("}");
                    self.indent -= 1;
                    self.writeln("}");
                }
                Ok(())
            }
            NodeKind::EnumDecl {
                visibility,
                name,
                generic_params,
                variants,
                ..
            } => {
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                // Use-site type-argument list (`<T>`, no bounds) for referencing
                // each variant interface inside the union alias. The variant
                // interfaces are declared as `Box_Full<T>` / `Box_Empty<T>`
                // (carrying `generics`), so the alias body must reference them
                // at the same arity or `tsc` rejects with TS2314.
                let type_args = self.generic_args_to_ts(generic_params);

                // Emit discriminated union type
                let variant_names: Vec<String> = variants
                    .iter()
                    .filter_map(|v| {
                        if let NodeKind::EnumVariant { name: vn, .. } = &v.kind {
                            Some(format!("{}_{}{type_args}", name.name, vn.name))
                        } else {
                            None
                        }
                    })
                    .collect();
                if !variant_names.is_empty() {
                    self.writeln(&format!(
                        "{export}type {}{generics} = {};",
                        name.name,
                        variant_names.join(" | "),
                    ));
                    self.buf.push('\n');
                }

                // Emit interface + factory for each variant
                for variant in variants {
                    self.emit_enum_variant(&name.name, generic_params, variant)?;
                }
                Ok(())
            }
            NodeKind::ClassDecl {
                visibility,
                name,
                generic_params,
                fields,
                methods,
                ..
            } => {
                // Register the class's positional field order so a `class`
                // literal lowers to `new Name(...)` (see `class_fields`). A
                // pre-pass already seeds this across the reachable set; re-record
                // here so the single-module emit path is correct even when the
                // pre-pass is not run.
                self.class_fields.insert(
                    name.name.clone(),
                    fields.iter().map(|f| f.name.name.clone()).collect(),
                );
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                self.writeln(&format!("{export}class {}{generics} {{", name.name));
                self.indent += 1;
                // Fields
                for f in fields {
                    let ty = self.ast_type_to_ts(&f.ty);
                    self.writeln(&format!("{}: {};", f.name.name, ty));
                }
                if !fields.is_empty() {
                    self.buf.push('\n');
                }
                // Constructor
                let ctor_params: Vec<String> = fields
                    .iter()
                    .map(|f| format!("{}: {}", f.name.name, self.ast_type_to_ts(&f.ty)))
                    .collect();
                self.writeln(&format!("constructor({}) {{", ctor_params.join(", ")));
                self.indent += 1;
                for f in fields {
                    self.writeln(&format!("this.{} = {};", f.name.name, f.name.name));
                }
                self.indent -= 1;
                self.writeln("}");
                // Methods
                for method in methods {
                    self.buf.push('\n');
                    self.emit_class_method(method)?;
                }
                self.indent -= 1;
                self.writeln("}");
                Ok(())
            }
            NodeKind::TraitDecl {
                visibility,
                name,
                generic_params,
                methods,
                ..
            } => {
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                // The trait-self type: the interface name applied to its own
                // generic params, e.g. `Comparable<T>` for `trait Comparable[T]`.
                // The leading `self` param of every trait method is typed to
                // this (it is the receiver), and a bare `other: Self` resolves to
                // it too — without a type, `tsc --strict` flags `self` as an
                // implicit `any` (Q-ts-codegen). Mirrors how an `ImplBlock` types
                // `self` as the impl target.
                let trait_self_ty =
                    format!("{}{}", name.name, self.generic_param_args(generic_params));
                self.writeln(&format!("{export}interface {}{generics} {{", name.name));
                self.indent += 1;
                for (i, method) in methods.iter().enumerate() {
                    if i > 0 {
                        self.buf.push('\n');
                    }
                    if let NodeKind::FnDecl {
                        name,
                        generic_params: method_generics,
                        params,
                        return_type,
                        ..
                    } = &method.kind
                    {
                        let m_generics = self.generic_params_to_ts(method_generics);
                        let param_list = self.collect_trait_typed_params(params, &trait_self_ty);
                        let ret = return_type
                            .as_ref()
                            .map(|r| self.type_to_ts(r))
                            .unwrap_or_else(|| "void".into());
                        self.writeln(&format!(
                            "{}{m_generics}({}): {};",
                            self.ts_method_name(&name.name),
                            param_list.join(", "),
                            ret,
                        ));
                    }
                }
                self.indent -= 1;
                self.writeln("}");
                Ok(())
            }
            NodeKind::ImplBlock {
                generic_params,
                trait_path,
                trait_args,
                target,
                methods,
                ..
            } => {
                let target_base = self.type_expr_to_string(target);
                // The target's generic params — from the impl's own list when
                // present, else from the record/enum decl (`impl Box { ... }`
                // where `T` is declared on `record Box[T]`). `target_name` is
                // `Box<T>`, used for the merged interface head and the
                // `self: Box<T>` receiver param. Each prototype function
                // re-declares `<T>` (it is a free function outside the class
                // scope) via `merge_generic_params_to_ts`.
                let target_params = self.impl_target_generics(generic_params, &target_base);
                let target_name =
                    format!("{target_base}{}", self.generic_param_args(&target_params));
                // Trait default methods (codegen-completeness P2): for an
                // `impl Trait for Type` block, the trait's default methods that
                // this impl does not override must also be attached to the
                // target's prototype — the trait interface declares only their
                // signatures. We synthesize them exactly like the impl's own
                // methods (same interface sig + prototype function); a default
                // body that calls another trait method via `self.other()`
                // resolves through the same merged interface.
                let default_methods: Vec<AIRNode> = trait_path
                    .as_ref()
                    .map(|tp| {
                        crate::generator::inherited_default_methods(&self.trait_decls, tp, methods)
                    })
                    .unwrap_or_default();
                // Each entry carries whether it is a *synthesized default*
                // method (`true`). The `Self` type renders as the concrete
                // target (`trait_self_subst`) rather than `this` for ALL impl
                // methods — synthesized trait defaults AND the impl's own
                // inherent methods alike — since each emits as a free prototype
                // function (`Target.prototype.m = function(...): Self`) where
                // `this` is not a valid type annotation (TS2526). The boolean is
                // still threaded for clarity / future per-kind handling.
                let all_methods: Vec<(&AIRNode, bool)> = methods
                    .iter()
                    .map(|m| (m, false))
                    .chain(default_methods.iter().map(|m| (m, true)))
                    .collect();
                // Methods are attached via `Target.prototype.m = function(...)`.
                // For `tsc` to accept `p.m(...)` at call sites, the class type
                // must declare those members. We emit a declaration-merging
                // `interface Target { ... }` whose signatures mirror the
                // prototype functions exactly — crucially including the leading
                // `self` parameter (the AIR lowerer prepends the receiver as the
                // first argument and keeps `self` as a declared param, so the
                // call site is `p.m(p, ...)`). The untyped `self` param is typed
                // as the impl target, which also removes the implicit-`any`
                // error inside each method body.
                let mut iface_sigs: Vec<String> = Vec::new();
                for (method, _is_default) in &all_methods {
                    // Associated functions (no `self`, e.g. a `From` impl's
                    // `from`) are static members, declared via a merged
                    // `namespace` below — not instance methods on the interface.
                    if crate::generator::is_associated_impl_method(method, &self.effect_ops) {
                        continue;
                    }
                    if let NodeKind::FnDecl {
                        is_async,
                        name,
                        generic_params,
                        params,
                        return_type,
                        effect_clause,
                        ..
                    } = &method.kind
                    {
                        // `Self` → the concrete target for every impl method (see
                        // `all_methods`). The merged-interface signature MUST
                        // match the prototype function's signature exactly, so the
                        // same substitution is applied in both loops; a mismatch
                        // (e.g. `this` here, `Target` there) is a declaration-merge
                        // error.
                        let prev_subst = self.trait_self_subst.take();
                        self.trait_self_subst = Some(target_name.clone());
                        let generics = self.generic_params_to_ts(generic_params);
                        let mut all_params = self.collect_impl_typed_params(params, &target_name);
                        if let Some(ep) = self.effects_param(effect_clause) {
                            all_params.push(ep);
                        }
                        let ret_str = build_ts_return_type(
                            *is_async,
                            return_type.as_deref().map(|r| self.type_to_ts(r)),
                        );
                        self.trait_self_subst = prev_subst;
                        iface_sigs.push(format!(
                            "{}{generics}({}){ret_str};",
                            self.ts_method_name(&name.name),
                            all_params.join(", "),
                        ));
                    }
                }
                // The declaration-merging `interface` must be `export`ed exactly
                // when the target `class` is — TS rejects a merged declaration
                // whose members disagree on export-ness (TS2395).
                let iface_export = if self.exported_types.contains(&target_base) {
                    "export "
                } else {
                    ""
                };
                // A §18.2 prelude (compiler-sealed) trait with no user `trait`
                // decl — `Comparable`/`Equatable`/`Displayable`/`Hashable` used
                // without a `use core.compare` — emits NO TS interface, so an
                // `interface Foo extends Comparable` references an undefined name
                // (TS2304). Treat such an impl like a trait-less one: emit the
                // concrete method signatures on the merged interface, but with no
                // `extends` clause (TS dispatches the method by structural typing,
                // and `Ordering` maps to its runtime form via `type_to_ts`).
                // (Q-prelude-impl-missing-import.)
                let prelude_trait = trait_path.as_ref().is_some_and(|tp| {
                    tp.segments.last().is_some_and(|seg| {
                        crate::generator::is_unimplemented_sealed_core_trait(
                            &seg.name,
                            &self.trait_decls,
                        )
                    })
                });
                if let Some(tp) = trait_path.as_ref().filter(|_| !prelude_trait) {
                    let trait_base = tp
                        .segments
                        .iter()
                        .map(|s| s.name.as_str())
                        .collect::<Vec<_>>()
                        .join(".");
                    // The trait may itself be generic (`trait P[T]`), emitted as
                    // `interface P<T>`. The `extends` clause must carry the
                    // impl's trait type arguments (`impl P[T] for R[T]` →
                    // `extends P<T>`); without them `tsc` rejects with TS2314
                    // ("Generic type 'P<T>' requires 1 type argument(s)"). The
                    // args are type-expression AIR nodes; render each to its TS
                    // form. Empty `trait_args` ⇒ a non-generic trait, no `<...>`.
                    let trait_name = if trait_args.is_empty() {
                        trait_base
                    } else {
                        let arg_strs: Vec<String> =
                            trait_args.iter().map(|a| self.type_to_ts(a)).collect();
                        format!("{trait_base}<{}>", arg_strs.join(", "))
                    };
                    // An impl whose methods are *all associated* (no instance
                    // methods — e.g. `From`, whose only method `from(value)` takes
                    // no `self`) contributes no merged-interface members, and its
                    // trait carries no instance contract for `new Target()` to
                    // satisfy. Skip the `interface … extends Trait` entirely: an
                    // empty `extends Trait` body would still reference the trait
                    // interface, which may not be in scope (a prelude trait like
                    // `From` is not emitted into the consuming module).
                    if iface_sigs.is_empty() {
                        self.writeln(&format!("// impl {trait_name} for {target_name}"));
                    } else {
                        // Declaration merging: `extends Trait` keeps
                        // `new Target()` assignable to the trait's interface
                        // type, while the concrete signatures (with `self`) make
                        // `p.m(p)` resolve.
                        self.writeln(&format!(
                            "{iface_export}interface {target_name} extends {trait_name} {{"
                        ));
                        self.indent += 1;
                        for sig in &iface_sigs {
                            self.writeln(sig);
                        }
                        self.indent -= 1;
                        self.writeln("}");
                        self.writeln(&format!("// impl {trait_name} for {target_name}"));
                    }
                } else if iface_sigs.is_empty() {
                    self.writeln(&format!("// impl {target_name}"));
                } else {
                    self.writeln(&format!("{iface_export}interface {target_name} {{"));
                    self.indent += 1;
                    for sig in &iface_sigs {
                        self.writeln(sig);
                    }
                    self.indent -= 1;
                    self.writeln("}");
                    self.writeln(&format!("// impl {target_name}"));
                }
                for (method, _is_default) in &all_methods {
                    // Associated functions are emitted as merged-`namespace`
                    // static members below, not prototype instance methods.
                    if crate::generator::is_associated_impl_method(method, &self.effect_ops) {
                        continue;
                    }
                    if let NodeKind::FnDecl {
                        is_async,
                        name,
                        generic_params,
                        params,
                        return_type,
                        effect_clause,
                        body,
                        ..
                    } = &method.kind
                    {
                        // Every impl method emits as a free prototype function
                        // (`Target.prototype.m = function(...)`), where `this` is
                        // not a valid type. So a `Self` type — whether in a
                        // synthesized trait default (`other: Self`) or the impl's
                        // own inherent method (`fn combine(self, ...) -> Self`) —
                        // must render as the concrete target. This matches the
                        // merged-interface signature emitted above.
                        let prev_subst = self.trait_self_subst.take();
                        self.trait_self_subst = Some(target_name.clone());
                        let async_kw = if *is_async { "async " } else { "" };
                        // The prototype assignment lives outside the class scope,
                        // so the function itself must re-declare the target's
                        // generic params (`function<T>(self: Box<T>): T`) — they
                        // are NOT in scope from the class. Merge them with the
                        // method's own generics. The `.prototype` reference uses
                        // the *bare* type name (`Box.prototype`, never
                        // `Box<T>.prototype`, which is not valid TS).
                        let generics =
                            self.merge_generic_params_to_ts(&target_params, generic_params);
                        let param_list = self.collect_impl_typed_params(params, &target_name);
                        let effects_param = self.effects_param(effect_clause);
                        let mut all_params = param_list;
                        if let Some(ep) = effects_param {
                            all_params.push(ep);
                        }
                        let ret_str = build_ts_return_type(
                            *is_async,
                            return_type.as_deref().map(|r| self.type_to_ts(r)),
                        );
                        self.writeln(&format!(
                            "{target_base}.prototype.{} = {async_kw}function{generics}({}){ret_str} {{",
                            self.ts_method_name(&name.name),
                            all_params.join(", "),
                        ));
                        self.indent += 1;
                        let old_handler_vars = self.current_handler_vars.clone();
                        let expanded = self.expand_effect_names(effect_clause);
                        for ename in &expanded {
                            self.current_handler_vars
                                .insert(ename.clone(), to_camel_case(ename));
                        }
                        self.emit_block_body(body)?;
                        self.current_handler_vars = old_handler_vars;
                        self.indent -= 1;
                        self.writeln("};");
                        // Restore after the whole method (signature + body) is
                        // emitted, so any `Self` annotation in the body also
                        // resolves to the concrete target.
                        self.trait_self_subst = prev_subst;
                    }
                }
                // Associated functions (`Type.method(...)`, no `self`) are static
                // members. A merged `namespace Target { export function m(...) }`
                // both declares the static on `typeof Target` (so `tsc` accepts
                // the `Target.m(...)` call) and provides the implementation —
                // unlike a bare `Target.m = function(...)` assignment, which tsc
                // rejects (TS2339, the property is undeclared on the class type).
                let assoc_methods: Vec<&AIRNode> = all_methods
                    .iter()
                    .filter(|(m, _)| {
                        crate::generator::is_associated_impl_method(m, &self.effect_ops)
                    })
                    .map(|(m, _)| *m)
                    .collect();
                if !assoc_methods.is_empty() {
                    let ns_export = if self.exported_types.contains(&target_base) {
                        "export "
                    } else {
                        ""
                    };
                    self.writeln(&format!("{ns_export}namespace {target_base} {{"));
                    self.indent += 1;
                    for method in assoc_methods {
                        if let NodeKind::FnDecl {
                            is_async,
                            name,
                            generic_params,
                            params,
                            return_type,
                            effect_clause,
                            body,
                            ..
                        } = &method.kind
                        {
                            let prev_subst = self.trait_self_subst.take();
                            self.trait_self_subst = Some(target_name.clone());
                            let async_kw = if *is_async { "async " } else { "" };
                            let generics =
                                self.merge_generic_params_to_ts(&target_params, generic_params);
                            let param_list = self.collect_impl_typed_params(params, &target_name);
                            let effects_param = self.effects_param(effect_clause);
                            let mut all_params = param_list;
                            if let Some(ep) = effects_param {
                                all_params.push(ep);
                            }
                            let ret_str = build_ts_return_type(
                                *is_async,
                                return_type.as_deref().map(|r| self.type_to_ts(r)),
                            );
                            self.writeln(&format!(
                                "export {async_kw}function {}{generics}({}){ret_str} {{",
                                self.ts_method_name(&name.name),
                                all_params.join(", "),
                            ));
                            self.indent += 1;
                            let old_handler_vars = self.current_handler_vars.clone();
                            let expanded = self.expand_effect_names(effect_clause);
                            for ename in &expanded {
                                self.current_handler_vars
                                    .insert(ename.clone(), to_camel_case(ename));
                            }
                            self.emit_block_body(body)?;
                            self.current_handler_vars = old_handler_vars;
                            self.indent -= 1;
                            self.writeln("}");
                            self.trait_self_subst = prev_subst;
                        }
                    }
                    self.indent -= 1;
                    self.writeln("}");
                }
                Ok(())
            }
            NodeKind::EffectDecl {
                visibility,
                name,
                generic_params,
                components,
                operations,
                ..
            } => {
                if !components.is_empty() {
                    let comp_names: Vec<String> = components
                        .iter()
                        .map(|tp| {
                            tp.segments
                                .last()
                                .map_or("effect".to_string(), |s| s.name.clone())
                        })
                        .collect();
                    self.writeln(&format!(
                        "// composite effect {} = {}",
                        name.name,
                        comp_names.join(" + ")
                    ));
                    self.composite_effects.insert(name.name.clone(), comp_names);
                    return Ok(());
                }
                // Record effect operations for Call → handler.op rewriting.
                for op in operations {
                    if let NodeKind::FnDecl { name: op_name, .. } = &op.kind {
                        self.effect_ops
                            .insert(op_name.name.clone(), name.name.clone());
                    }
                }
                self.effect_names.insert(name.name.clone());
                // Effects → TS interface
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                self.writeln(&format!("{export}interface {}{generics} {{", name.name));
                self.indent += 1;
                for op in operations {
                    if let NodeKind::FnDecl {
                        name,
                        params,
                        return_type,
                        ..
                    } = &op.kind
                    {
                        let param_list = self.collect_typed_params(params);
                        let ret = return_type
                            .as_ref()
                            .map(|r| self.type_to_ts(r))
                            .unwrap_or_else(|| "void".into());
                        self.writeln(&format!(
                            "{}({}): {};",
                            name.name,
                            param_list.join(", "),
                            ret,
                        ));
                    }
                }
                self.indent -= 1;
                self.writeln("}");
                Ok(())
            }
            NodeKind::TypeAlias {
                visibility,
                name,
                generic_params,
                ty,
                ..
            } => {
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let generics = self.generic_params_to_ts(generic_params);
                let ty_str = self.type_to_ts(ty);
                self.writeln(&format!("{export}type {}{generics} = {ty_str};", name.name));
                Ok(())
            }
            NodeKind::ConstDecl {
                visibility,
                name,
                ty,
                value,
                ..
            } => {
                let export = if matches!(visibility, Visibility::Public) {
                    "export "
                } else {
                    ""
                };
                let ty_str = self.type_to_ts(ty);
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}{export}const {}: {ty_str} = ", name.name);
                self.emit_expr(value)?;
                self.buf.push_str(";\n");
                Ok(())
            }
            NodeKind::ModuleHandle { effect, handler } => {
                let effect_name = effect.segments.last().map_or("effect", |s| s.name.as_str());
                let var_name = format!("__{}", to_camel_case(effect_name));
                let type_name = effect_name;
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}const {var_name}: {type_name} = ");
                self.emit_expr(handler)?;
                self.buf.push_str(";\n");
                // Register as ambient handler so same-module calls pick it up.
                self.current_handler_vars
                    .insert(effect_name.to_string(), var_name);
                Ok(())
            }
            NodeKind::PropertyTest { name, body, .. } => {
                self.writeln(&format!("// property test: {name}"));
                self.writeln("// (property tests are not emitted in TS output)");
                let _ = body;
                Ok(())
            }
            // Statement / expression nodes at top level:
            NodeKind::LetBinding { .. }
            | NodeKind::If { .. }
            | NodeKind::For { .. }
            | NodeKind::While { .. }
            | NodeKind::Loop { .. }
            | NodeKind::Return { .. }
            | NodeKind::Break { .. }
            | NodeKind::Continue
            | NodeKind::Guard { .. }
            | NodeKind::Match { .. }
            | NodeKind::Block { .. }
            | NodeKind::HandlingBlock { .. }
            | NodeKind::Assign { .. } => self.emit_stmt(node),
            // A bare `expr?` statement (`save_task(task)?`): the Ok/Some payload
            // is discarded, but the `?` still early-returns the Err/None from the
            // enclosing fn. Lower the early-return guard and drop the payload.
            NodeKind::Propagate { expr } => {
                self.emit_propagate(expr)?;
                Ok(())
            }
            // Expression nodes that appear as statements:
            _ => {
                self.write_indent();
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
                Ok(())
            }
        }
    }

    // ── Function declarations ───────────────────────────────────────────────

    #[allow(clippy::too_many_arguments)]
    fn emit_fn_decl(
        &mut self,
        visibility: Visibility,
        is_async: bool,
        name: &str,
        generic_params: &[bock_ast::GenericParam],
        params: &[AIRNode],
        return_type: Option<&AIRNode>,
        effect_clause: &[bock_ast::TypePath],
        body: &AIRNode,
        _is_method: bool,
    ) -> Result<(), CodegenError> {
        let export = if matches!(visibility, Visibility::Public) {
            "export "
        } else {
            ""
        };
        let async_kw = if is_async { "async " } else { "" };
        let generics = self.generic_params_to_ts(generic_params);
        let param_list = self.collect_typed_params(params);
        let effects_param = self.effects_param(effect_clause);
        let mut all_params = param_list;
        if let Some(ep) = effects_param {
            all_params.push(ep);
        }
        let ret_str = build_ts_return_type(is_async, return_type.map(|r| self.type_to_ts(r)));
        if !effect_clause.is_empty() {
            let effect_names = self.expand_effect_names(effect_clause);
            self.fn_effects.insert(name.to_string(), effect_names);
        }
        let ts_name = ts_value_ident(name);
        self.writeln(&format!(
            "{export}{async_kw}function {ts_name}{generics}({}){ret_str} {{",
            all_params.join(", "),
        ));
        self.indent += 1;
        let old_handler_vars = self.current_handler_vars.clone();
        let expanded = self.expand_effect_names(effect_clause);
        for ename in &expanded {
            self.current_handler_vars
                .insert(ename.clone(), to_camel_case(ename));
        }
        let prev_prop_tag = self.current_fn_propagate_tag;
        self.current_fn_propagate_tag = Self::propagate_tag_for_return(return_type);
        self.emit_fn_body_seeded(params, body)?;
        self.current_fn_propagate_tag = prev_prop_tag;
        self.current_handler_vars = old_handler_vars;
        self.indent -= 1;
        self.writeln("}");
        Ok(())
    }

    fn emit_class_method(&mut self, method: &AIRNode) -> Result<(), CodegenError> {
        if let NodeKind::FnDecl {
            is_async,
            name,
            generic_params,
            params,
            return_type,
            effect_clause,
            body,
            ..
        } = &method.kind
        {
            let async_kw = if *is_async { "async " } else { "" };
            let generics = self.generic_params_to_ts(generic_params);
            let param_list = self.collect_typed_params(params);
            let effects_param = self.effects_param(effect_clause);
            let mut all_params = param_list;
            if let Some(ep) = effects_param {
                all_params.push(ep);
            }
            let ret_str = build_ts_return_type(
                *is_async,
                return_type.as_deref().map(|r| self.type_to_ts(r)),
            );
            let method_name = self.ts_method_name(&to_camel_case(&name.name));
            self.writeln(&format!(
                "{async_kw}{method_name}{generics}({}){ret_str} {{",
                all_params.join(", "),
            ));
            self.indent += 1;
            let old_handler_vars = self.current_handler_vars.clone();
            let expanded = self.expand_effect_names(effect_clause);
            for ename in &expanded {
                self.current_handler_vars
                    .insert(ename.clone(), to_camel_case(ename));
            }
            let prev_prop_tag = self.current_fn_propagate_tag;
            self.current_fn_propagate_tag = Self::propagate_tag_for_return(return_type.as_deref());
            self.emit_fn_body_seeded(params, body)?;
            self.current_fn_propagate_tag = prev_prop_tag;
            self.current_handler_vars = old_handler_vars;
            self.indent -= 1;
            self.writeln("}");
        }
        Ok(())
    }

    /// Collect a lambda's parameters, typing any *un-annotated* param as `any`.
    ///
    /// Bock lambdas usually omit param types (`(x) => …`); the AIR carries no
    /// inferred type, so an un-annotated emit (`(x) =>`) is an implicit `any`
    /// that `tsc --strict` (`noImplicitAny`) rejects (TS7006). An explicit `any`
    /// is always accepted and never loses correctness — at a contextually-typed
    /// call site (`.filter((m) => …)`) TS would have inferred `m` anyway, and the
    /// explicit annotation is compatible; at an un-contextual site (`const f =
    /// (x) => …`) it is the only thing that type-checks. Params that *do* carry a
    /// declared type keep it.
    fn collect_lambda_params(&self, params: &[AIRNode]) -> Vec<String> {
        params
            .iter()
            .filter_map(|p| {
                let NodeKind::Param { pattern, ty, .. } = &p.kind else {
                    return None;
                };
                let name = self.pattern_to_binding_name(pattern);
                let ty_str = match ty {
                    Some(t) => format!(": {}", self.type_to_ts(t)),
                    None => ": any".to_string(),
                };
                Some(format!("{name}{ty_str}"))
            })
            .collect()
    }

    /// Collect typed parameter names: `name: Type`.
    fn collect_typed_params(&self, params: &[AIRNode]) -> Vec<String> {
        params
            .iter()
            .filter_map(|p| {
                if let NodeKind::Param {
                    pattern,
                    ty,
                    default,
                } = &p.kind
                {
                    let name = self.pattern_to_binding_name(pattern);
                    let ty_str = ty
                        .as_ref()
                        .map(|t| format!(": {}", self.type_to_ts(t)))
                        .unwrap_or_default();
                    if let Some(def) = default {
                        let mut ctx = TsEmitCtx::new();
                        ctx.indent = self.indent;
                        ctx.enum_variants = self.enum_variants.clone();
                        if ctx.emit_expr_to_string(def).is_ok() {
                            let (def_str, _) = ctx.finish();
                            return Some(format!("{name}{ty_str} = {def_str}"));
                        }
                    }
                    Some(format!("{name}{ty_str}"))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Collect typed parameters for an `impl` method, typing an untyped
    /// receiver (`self`) parameter as the impl target.
    ///
    /// Bock impl methods declare `self` with no type annotation
    /// (`fn sum(self)`), and the AIR lowerer keeps it as a real parameter while
    /// prepending the receiver at call sites (`p.sum(p)`). Without a type, `tsc`
    /// flags `self` as implicit `any`; we substitute the target type so the
    /// method body (`self.x`) and the declaration-merged interface both
    /// type-check. Non-`self` params, and a `self` that already carries an
    /// explicit type, are handled exactly as [`Self::collect_typed_params`].
    fn collect_impl_typed_params(&self, params: &[AIRNode], target_name: &str) -> Vec<String> {
        params
            .iter()
            .filter_map(|p| {
                let NodeKind::Param {
                    pattern,
                    ty,
                    default,
                } = &p.kind
                else {
                    return None;
                };
                let name = self.pattern_to_binding_name(pattern);
                let ty_str = match ty {
                    Some(t) => format!(": {}", self.type_to_ts(t)),
                    None if name == "self" => format!(": {target_name}"),
                    None => String::new(),
                };
                if let Some(def) = default {
                    let mut ctx = TsEmitCtx::new();
                    ctx.indent = self.indent;
                    ctx.enum_variants = self.enum_variants.clone();
                    if ctx.emit_expr_to_string(def).is_ok() {
                        let (def_str, _) = ctx.finish();
                        return Some(format!("{name}{ty_str} = {def_str}"));
                    }
                }
                Some(format!("{name}{ty_str}"))
            })
            .collect()
    }

    /// Collect typed parameters for a **trait declaration** method, typing an
    /// untyped receiver (`self`) as the trait's own interface type
    /// (`trait_self_ty`, e.g. `Comparable<T>`).
    ///
    /// A trait method declares `self` with no annotation (`fn compare(self,
    /// other: Self)`); the AIR lowerer keeps it as a real leading parameter. In
    /// the emitted interface the untyped `self` would otherwise be `tsc
    /// --strict`'s implicit `any`. Typing it to the trait-self type makes the
    /// interface method signature well-typed and keeps it compatible (via
    /// declaration-merging method bivariance) with the concrete `self: Target`
    /// the `ImplBlock` arm emits. A `self` that already carries an explicit type,
    /// and all non-`self` params, are handled exactly as
    /// [`Self::collect_typed_params`] (where a `Self` annotation maps to `this`,
    /// the implementing type — correct for `other: Self`).
    fn collect_trait_typed_params(&self, params: &[AIRNode], trait_self_ty: &str) -> Vec<String> {
        params
            .iter()
            .filter_map(|p| {
                let NodeKind::Param {
                    pattern,
                    ty,
                    default,
                } = &p.kind
                else {
                    return None;
                };
                let name = self.pattern_to_binding_name(pattern);
                let ty_str = match ty {
                    Some(t) => format!(": {}", self.type_to_ts(t)),
                    None if name == "self" => format!(": {trait_self_ty}"),
                    None => String::new(),
                };
                if let Some(def) = default {
                    let mut ctx = TsEmitCtx::new();
                    ctx.indent = self.indent;
                    ctx.enum_variants = self.enum_variants.clone();
                    if ctx.emit_expr_to_string(def).is_ok() {
                        let (def_str, _) = ctx.finish();
                        return Some(format!("{name}{ty_str} = {def_str}"));
                    }
                }
                Some(format!("{name}{ty_str}"))
            })
            .collect()
    }

    fn emit_expr_to_string(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        self.emit_expr(node)
    }

    /// Expand effect names, replacing composite effects with their components.
    fn expand_effect_names(&self, effects: &[bock_ast::TypePath]) -> Vec<String> {
        let mut result = Vec::new();
        for tp in effects {
            let name = tp
                .segments
                .last()
                .map_or("effect".to_string(), |s| s.name.clone());
            if let Some(components) = self.composite_effects.get(&name) {
                result.extend(components.iter().cloned());
            } else {
                result.push(name);
            }
        }
        result
    }

    /// The in-scope `Clock` effect handler variable, if one is installed.
    ///
    /// When `Some`, the `Clock` time operations (`Instant.now`, `sleep`,
    /// `elapsed`) are routed through the handler instead of inlining the host
    /// primitive (Q-clock-handler-routing, §18.3.1/§18.4); when `None`, no
    /// handler is in scope and the default host primitive is emitted.
    fn clock_handler_var(&self) -> Option<&str> {
        self.current_handler_vars.get("Clock").map(String::as_str)
    }

    /// Effects → typed destructured parameter object: `{ log, clock }: { log: Log, clock: Clock }`.
    fn effects_param(&self, effects: &[bock_ast::TypePath]) -> Option<String> {
        if effects.is_empty() {
            return None;
        }
        let expanded = self.expand_effect_names(effects);
        if expanded.is_empty() {
            return None;
        }
        let names: Vec<String> = expanded.iter().map(|n| to_camel_case(n)).collect();
        let type_entries: Vec<String> = expanded
            .iter()
            .zip(names.iter())
            .map(|(orig, camel)| format!("{camel}: {orig}"))
            .collect();
        Some(format!(
            "{{ {} }}: {{ {} }}",
            names.join(", "),
            type_entries.join(", ")
        ))
    }

    /// Build a `{ effect: handler_var, ... }` argument for calling an effectful function.
    fn build_effects_call_arg_ts(&self, fn_name: &str) -> Option<String> {
        let effects = self.fn_effects.get(fn_name)?;
        let entries: Vec<String> = effects
            .iter()
            .filter_map(|e| {
                let handler_var = self.current_handler_vars.get(e)?;
                let param_name = to_camel_case(e);
                Some(format!("{param_name}: {handler_var}"))
            })
            .collect();
        if entries.is_empty() {
            return None;
        }
        Some(format!("{{ {} }}", entries.join(", ")))
    }

    // ── Enum variant interfaces + factories ──────────────────────────────────

    fn emit_enum_variant(
        &mut self,
        enum_name: &str,
        generic_params: &[bock_ast::GenericParam],
        variant: &AIRNode,
    ) -> Result<(), CodegenError> {
        if let NodeKind::EnumVariant { name, payload } = &variant.kind {
            let vname = &name.name;
            let generics = self.generic_params_to_ts(generic_params);
            // Use-site type-argument list (`<T>`, no bounds) for the variant's
            // *references* — its constructor-factory return type, and (for a
            // unit variant) its `const` annotation. Declaring the interface
            // `Box_Full<T>` but returning a bare `Box_Full` from the factory
            // fails `tsc` with TS2314; the return type must carry the same args.
            let type_args = self.generic_args_to_ts(generic_params);
            // Default-parameter form of the generic params, so a generic *unit*
            // variant — whose type param is phantom (unused in the variant
            // body) — can be both referenced with explicit args inside the
            // union alias (`Box_Empty<T>`) AND named with zero args on its
            // frozen `const` (`const Box_Empty: Box_Empty`). Without the
            // `= unknown` default the zero-arg const annotation fails TS2314.
            let unit_generics = if generic_params.is_empty() {
                String::new()
            } else {
                let items: Vec<String> = generic_params
                    .iter()
                    .map(|p| format!("{} = unknown", p.name.name))
                    .collect();
                format!("<{}>", items.join(", "))
            };
            let qualified = format!("{enum_name}_{vname}");

            match payload {
                EnumVariantPayload::Unit => {
                    // Interface for unit variant
                    self.writeln(&format!(
                        "interface {qualified}{unit_generics} {{ readonly _tag: \"{vname}\"; }}"
                    ));
                    self.writeln(&format!(
                        "const {qualified}: {qualified} = Object.freeze({{ _tag: \"{vname}\" as const }});"
                    ));
                }
                EnumVariantPayload::Struct(fields) => {
                    // Interface for struct variant
                    self.writeln(&format!("interface {qualified}{generics} {{"));
                    self.indent += 1;
                    self.writeln(&format!("readonly _tag: \"{vname}\";"));
                    for f in fields {
                        let ty = self.ast_type_to_ts(&f.ty);
                        self.writeln(&format!("readonly {}: {};", f.name.name, ty));
                    }
                    self.indent -= 1;
                    self.writeln("}");
                    let field_params: Vec<String> = fields
                        .iter()
                        .map(|f| format!("{}: {}", f.name.name, self.ast_type_to_ts(&f.ty)))
                        .collect();
                    let field_names: Vec<&str> =
                        fields.iter().map(|f| f.name.name.as_str()).collect();
                    self.writeln(&format!(
                        "function {qualified}{generics}({}): {qualified}{type_args} {{",
                        field_params.join(", "),
                    ));
                    self.indent += 1;
                    self.writeln(&format!(
                        "return {{ _tag: \"{vname}\" as const, {} }};",
                        field_names.join(", "),
                    ));
                    self.indent -= 1;
                    self.writeln("}");
                }
                EnumVariantPayload::Tuple(elems) => {
                    // Interface for tuple variant
                    self.writeln(&format!("interface {qualified}{generics} {{"));
                    self.indent += 1;
                    self.writeln(&format!("readonly _tag: \"{vname}\";"));
                    for (i, elem) in elems.iter().enumerate() {
                        let ty = self.type_to_ts(elem);
                        self.writeln(&format!("readonly _{i}: {ty};"));
                    }
                    self.indent -= 1;
                    self.writeln("}");
                    let param_decls: Vec<String> = elems
                        .iter()
                        .enumerate()
                        .map(|(i, e)| format!("_{i}: {}", self.type_to_ts(e)))
                        .collect();
                    let param_names: Vec<String> =
                        (0..elems.len()).map(|i| format!("_{i}")).collect();
                    self.writeln(&format!(
                        "function {qualified}{generics}({}): {qualified}{type_args} {{",
                        param_decls.join(", "),
                    ));
                    self.indent += 1;
                    self.writeln(&format!(
                        "return {{ _tag: \"{vname}\" as const, {} }};",
                        param_names
                            .iter()
                            .enumerate()
                            .map(|(i, p)| format!("_{i}: {p}"))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                    self.indent -= 1;
                    self.writeln("}");
                }
            }
        }
        Ok(())
    }

    // ── Statements ──────────────────────────────────────────────────────────

    fn emit_stmt(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        self.mark_span(node.span);
        match &node.kind {
            NodeKind::LetBinding {
                is_mut,
                pattern,
                ty,
                value,
                ..
            } => {
                let kw = if *is_mut { "let" } else { "const" };
                let binding = self.pattern_to_ts_destructure(pattern);
                let ty_ts = ty.as_ref().map(|t| self.type_to_ts(t));
                let ty_str = ty_ts.as_ref().map(|t| format!(": {t}")).unwrap_or_default();
                // Declare-only temp from the shared value-CF hoist: emit a bare
                // `let name;` (no initialiser); the relocated control flow assigns
                // it on every non-diverging path.
                if node.metadata.contains_key(crate::generator::DECL_ONLY_META) {
                    let ind = self.indent_str();
                    let _ = writeln!(self.buf, "{ind}let {binding}{ty_str};");
                    return Ok(());
                }
                // `let name = expr?` — the `?` unwraps the Ok/Some payload and
                // early-returns the Err/None from the enclosing fn. Lower the
                // unwrap in statement position (a temp + early-return guard),
                // then bind `name` to the payload access. See `emit_propagate`.
                if let NodeKind::Propagate { expr } = &value.kind {
                    if let NodeKind::BindPat { name, .. } = &pattern.kind {
                        let ts_name = ts_value_ident(&name.name);
                        let access = self.emit_propagate(expr)?;
                        let kw = if *is_mut || self.simple_let_needs_let(&ts_name) {
                            "let"
                        } else {
                            "const"
                        };
                        if self.simple_let_redeclared(&ts_name) {
                            let ind = self.indent_str();
                            let _ = writeln!(self.buf, "{ind}{ts_name} = {access};");
                        } else {
                            self.mark_simple_let_declared(&ts_name);
                            let ind = self.indent_str();
                            let _ = writeln!(self.buf, "{ind}{kw} {ts_name}{ty_str} = {access};");
                        }
                        return Ok(());
                    }
                    // A non-simple destructuring binding over a `?` value: unwrap
                    // into a temp, then destructure from it.
                    let access = self.emit_propagate(expr)?;
                    let ind = self.indent_str();
                    let _ = writeln!(self.buf, "{ind}{kw} {binding}{ty_str} = {access};");
                    return Ok(());
                }
                // A simple `let name = …` is subject to TS redeclaration rules
                // (TS2451). Bock allows re-binding the same name in one scope
                // (shadowing); TS does not, so the second-and-later binding of a
                // simple name becomes a plain assignment, and the first
                // declaration uses `let` (not `const`) when the name is later
                // re-bound/assigned. Mirrors the js backend (#217). The `?`
                // unwrap (`Propagate`) value takes a separate statement-form path
                // above, so it is excluded here.
                if let NodeKind::BindPat { name, .. } = &pattern.kind {
                    if !matches!(value.kind, NodeKind::Propagate { .. }) {
                        let ts_name = ts_value_ident(&name.name);
                        if self.simple_let_redeclared(&ts_name) {
                            let ind = self.indent_str();
                            let _ = write!(self.buf, "{ind}{ts_name} = ");
                            self.emit_let_value(value, ty_ts)?;
                            self.buf.push_str(";\n");
                            return Ok(());
                        }
                        if !self.value_needs_stmt_form(value) {
                            let needs_let = *is_mut || self.simple_let_needs_let(&ts_name);
                            let kw = if needs_let { "let" } else { "const" };
                            self.mark_simple_let_declared(&ts_name);
                            let ind = self.indent_str();
                            let _ = write!(self.buf, "{ind}{kw} {ts_name}{ty_str} = ");
                            self.emit_let_value(value, ty_ts)?;
                            self.buf.push_str(";\n");
                            return Ok(());
                        }
                    }
                }
                // A control-flow initialiser with no TS expression form (a `loop`,
                // or a value `if`/`match` with a `return`/`break` arm) is lowered
                // in statement position: declare the binding `let`, then emit the
                // control flow assigning into it. The original binding must be
                // `let` (not `const`) so the arms can assign it (cluster-1 fix).
                if self.value_needs_stmt_form(value) {
                    let ind = self.indent_str();
                    // A plain identifier binding can be reassigned; a destructuring
                    // pattern cannot be split, so this path only applies to simple
                    // bindings (the only shape these examples produce).
                    let _ = writeln!(self.buf, "{ind}let {binding}{ty_str};");
                    return self.emit_value_in_stmt_pos(value, &ValueSink::Assign(binding));
                }
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}{kw} {binding}{ty_str} = ");
                // `emit_let_value` records the binding's declared type as the
                // expected type for the value (so a value-position `match`/`if`
                // IIFE annotates its arrow return and hoists a bare-identifier
                // scrutinee — see `current_expected_type`) and, for a
                // single-variant enum construction, widens the initialiser to the
                // declared union so the binding does not narrow to the
                // construction variant (TS2678 on a later sibling-variant match).
                self.emit_let_value(value, ty_ts)?;
                self.buf.push_str(";\n");
                Ok(())
            }
            NodeKind::If {
                let_pattern,
                condition,
                then_block,
                else_block,
            } => {
                if let Some(pat) = let_pattern {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}if (");
                    self.emit_expr(condition)?;
                    self.buf.push_str(" != null) {\n");
                    self.indent += 1;
                    let binding = self.pattern_to_ts_destructure(pat);
                    self.writeln(&format!("const {binding} = "));
                    self.emit_block_body(then_block)?;
                    self.indent -= 1;
                } else {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}if (");
                    self.emit_expr(condition)?;
                    self.buf.push_str(") {\n");
                    self.indent += 1;
                    self.emit_block_body(then_block)?;
                    self.indent -= 1;
                }
                if let Some(else_b) = else_block {
                    if matches!(else_b.kind, NodeKind::If { .. }) {
                        let ind = self.indent_str();
                        let _ = write!(self.buf, "{ind}}} else ");
                        self.emit_stmt(else_b)?;
                        return Ok(());
                    }
                    self.writeln("} else {");
                    self.indent += 1;
                    self.emit_block_body(else_b)?;
                    self.indent -= 1;
                }
                self.writeln("}");
                Ok(())
            }
            NodeKind::For {
                pattern,
                iterable,
                body,
            } => {
                let binding = self.pattern_to_ts_destructure(pattern);
                self.emit_loop_label_prefix(body);
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}for (const {binding} of ");
                self.emit_expr(iterable)?;
                self.buf.push_str(") {\n");
                self.indent += 1;
                self.emit_loop_body(body)?;
                self.indent -= 1;
                self.writeln("}");
                self.pop_loop_frame();
                Ok(())
            }
            NodeKind::While { condition, body } => {
                self.emit_loop_label_prefix(body);
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}while (");
                self.emit_expr(condition)?;
                self.buf.push_str(") {\n");
                self.indent += 1;
                self.emit_loop_body(body)?;
                self.indent -= 1;
                self.writeln("}");
                self.pop_loop_frame();
                Ok(())
            }
            NodeKind::Loop { body } => {
                self.emit_loop_label_prefix(body);
                self.writeln("while (true) {");
                self.indent += 1;
                self.emit_loop_body(body)?;
                self.indent -= 1;
                self.writeln("}");
                self.pop_loop_frame();
                Ok(())
            }
            NodeKind::Return { value } => {
                if let Some(val) = value {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}return ");
                    self.emit_expr(val)?;
                    self.buf.push_str(";\n");
                } else {
                    self.writeln("return;");
                }
                Ok(())
            }
            NodeKind::Break { value } => {
                if let Some(val) = value {
                    // In a value-position loop (`let r = loop { … break v … }`),
                    // `break v` delivers the loop's value through the loop sink
                    // (`r = v;`) before breaking. Without a sink (an ordinary
                    // statement loop) the value is dropped — emit it as a comment
                    // so it remains visible but inert.
                    if let Some(sink) = self.innermost_loop_value_sink() {
                        self.emit_sink_value(val, &sink)?;
                    } else {
                        let ind = self.indent_str();
                        let _ = write!(self.buf, "{ind}/* break value: ");
                        self.emit_expr(val)?;
                        self.buf.push_str(" */\n");
                    }
                }
                if self.switch_label_depth > 0 {
                    if let Some(label) = self.innermost_loop_label() {
                        self.writeln(&format!("break {label};"));
                        return Ok(());
                    }
                }
                self.writeln("break;");
                Ok(())
            }
            NodeKind::Continue => {
                if self.switch_label_depth > 0 {
                    if let Some(label) = self.innermost_loop_label() {
                        self.writeln(&format!("continue {label};"));
                        return Ok(());
                    }
                }
                self.writeln("continue;");
                Ok(())
            }
            NodeKind::Guard {
                let_pattern,
                condition,
                else_block,
            } => {
                if let Some(pat) = let_pattern {
                    // `guard (let pat = expr) else { … }`: evaluate `expr` once,
                    // run the else (which must diverge) when `pat` does not
                    // match, then bind `pat`'s names into the *enclosing* scope
                    // so they are in scope for the statements after the guard.
                    // Mirrors the js lowering (#217).
                    self.match_temp_counter += 1;
                    let tmp = format!("__guard{}", self.match_temp_counter);
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}const {tmp} = ");
                    self.emit_expr(condition)?;
                    self.buf.push_str(";\n");
                    let test = self.pattern_test_ts(pat, &tmp);
                    // A bare bind / wildcard pattern always matches → no `if`.
                    if !test.is_empty() {
                        let ind = self.indent_str();
                        let _ = writeln!(self.buf, "{ind}if (!({test})) {{");
                        self.indent += 1;
                        self.emit_block_body(else_block)?;
                        self.indent -= 1;
                        self.writeln("}");
                    }
                    // Bindings land in the enclosing scope (no nested block), so
                    // they are visible to the statements following the guard.
                    self.pattern_binds_ts(pat, &tmp)?;
                } else {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}if (!(");
                    self.emit_expr(condition)?;
                    self.buf.push_str(")) {\n");
                    self.indent += 1;
                    self.emit_block_body(else_block)?;
                    self.indent -= 1;
                    self.writeln("}");
                }
                Ok(())
            }
            NodeKind::Match { scrutinee, arms } => self.emit_match(scrutinee, arms, false),
            NodeKind::Block { stmts, tail } => {
                // A statement-position block is its own TS `{}` lexical scope, so
                // it gets its own `let` scope frame (a name re-bound inside is
                // independent of the enclosing block's bindings).
                self.writeln("{");
                self.indent += 1;
                self.enter_let_scope(node);
                for s in stmts {
                    self.emit_node(s)?;
                }
                if let Some(t) = tail {
                    self.write_indent();
                    self.emit_expr(t)?;
                    self.buf.push_str(";\n");
                }
                self.leave_let_scope();
                self.indent -= 1;
                self.writeln("}");
                Ok(())
            }
            NodeKind::HandlingBlock { handlers, body } => {
                // handling block → scoped handler instantiation. The emitted
                // `{ … }` is its own TS lexical block, so it gets a fresh `let`
                // scope frame: a name first bound in one `handling` block and
                // re-bound in a *sibling* `handling` block is two independent
                // declarations (each block-scoped), not a redeclaration. Without
                // a fresh frame the redeclaration tracker would carry the prior
                // block's `declared` set into this one and rewrite the second
                // `let x = …` into a bare `x = …` — a name that went out of
                // scope when the first block closed (TS2304 / strict-mode
                // ReferenceError).
                self.writeln("{");
                self.indent += 1;
                self.enter_let_scope(body);
                let old_handler_vars = self.current_handler_vars.clone();
                for h in handlers {
                    let effect_name = h
                        .effect
                        .segments
                        .last()
                        .map_or("effect", |s| s.name.as_str());
                    let var_name = format!("__{}", to_camel_case(effect_name));
                    let type_name = effect_name;
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}const {var_name}: {type_name} = ");
                    self.emit_expr(&h.handler)?;
                    self.buf.push_str(";\n");
                    self.current_handler_vars
                        .insert(effect_name.to_string(), var_name);
                }
                if let NodeKind::Block { stmts, tail } = &body.kind {
                    for s in stmts {
                        self.emit_node(s)?;
                    }
                    if let Some(t) = tail {
                        self.write_indent();
                        self.emit_expr(t)?;
                        self.buf.push_str(";\n");
                    }
                } else {
                    self.emit_stmt(body)?;
                }
                self.current_handler_vars = old_handler_vars;
                self.leave_let_scope();
                self.indent -= 1;
                self.writeln("}");
                Ok(())
            }
            NodeKind::Assign { op, target, value } => {
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}");
                self.emit_expr(target)?;
                let op_str = match op {
                    AssignOp::Assign => "=",
                    AssignOp::AddAssign => "+=",
                    AssignOp::SubAssign => "-=",
                    AssignOp::MulAssign => "*=",
                    AssignOp::DivAssign => "/=",
                    AssignOp::RemAssign => "%=",
                };
                let _ = write!(self.buf, " {op_str} ");
                self.emit_expr(value)?;
                self.buf.push_str(";\n");
                Ok(())
            }
            _ => {
                self.write_indent();
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
                Ok(())
            }
        }
    }

    /// Lower the `?` propagation operator (`inner?`) in statement position.
    ///
    /// Emits a temp holding `inner` once, then an early-return guard that
    /// returns the temp unchanged from the enclosing fn when the value is the
    /// failure variant (`Err` for `Result`, `None` for `Optional`), and returns
    /// the *access expression* for the success payload (`__propN._0`) so the
    /// caller can bind/use the unwrapped value. The runtime representation is a
    /// tagged object (`{ _tag, _0 }`) shared with `match`/method lowering, so the
    /// same guard covers both container kinds: the failure value *is* the temp
    /// (an `Err`/`None`), so `return __propN` propagates it as-is, and the
    /// payload is always `._0`. Implements the standard Rust-like `?` semantics
    /// (early-return on failure, unwrap on success).
    fn emit_propagate(&mut self, inner: &AIRNode) -> Result<String, CodegenError> {
        self.match_temp_counter += 1;
        let tmp = format!("__prop{}", self.match_temp_counter);
        let ind = self.indent_str();
        let _ = write!(self.buf, "{ind}const {tmp} = ");
        self.emit_expr(inner)?;
        self.buf.push_str(";\n");
        // Failure variant → propagate the container unchanged. When the enclosing
        // fn's return type tells us the failure tag (`Err` for `Result`, `None`
        // for `Optional`), test that single discriminant: it is a real member of
        // the value's tag union, so TS both accepts the comparison *and* narrows
        // the success access (`{tmp}._0`) to the payload type after the guard.
        let test = match self.current_fn_propagate_tag {
            Some(tag) => format!("{tmp}._tag === \"{tag}\""),
            // Unknown container kind (no typed return) → fall back to testing
            // both failure tags with the `._tag` widened to `string`, so the
            // (always-false but legal) cross-container arm does not trip a TS2367
            // "no overlap" error. This path forgoes narrowing; the typed-return
            // path above (which every example hits) keeps it.
            None => {
                format!("({tmp}._tag as string) === \"Err\" || ({tmp}._tag as string) === \"None\"")
            }
        };
        let ind = self.indent_str();
        let _ = writeln!(self.buf, "{ind}if ({test}) {{");
        self.indent += 1;
        let ind = self.indent_str();
        // `as never` lets the `Err`/`None` container satisfy the fn's declared
        // return type without re-narrowing it here (the value is already the
        // correct container shape; the cast only quiets the structural check).
        let _ = writeln!(self.buf, "{ind}return {tmp} as never;");
        self.indent -= 1;
        self.writeln("}");
        Ok(format!("{tmp}._0"))
    }

    // ── Expressions ─────────────────────────────────────────────────────────

    fn emit_expr(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        self.mark_span(node.span);
        match &node.kind {
            NodeKind::Literal { lit } => {
                match lit {
                    Literal::Int(s) => self.buf.push_str(s),
                    Literal::Float(s) => self.buf.push_str(s),
                    Literal::Bool(b) => self.buf.push_str(if *b { "true" } else { "false" }),
                    Literal::Char(s) => {
                        self.buf.push('\'');
                        self.buf.push_str(s);
                        self.buf.push('\'');
                    }
                    Literal::String(s) => {
                        self.buf.push('"');
                        self.buf.push_str(&escape_js_string(s));
                        self.buf.push('"');
                    }
                    Literal::Unit => self.buf.push_str("undefined"),
                }
                Ok(())
            }
            NodeKind::Identifier { name } => {
                if name.name == "None" {
                    self.buf.push_str("{ _tag: \"None\" as const }");
                } else if let Some(variant) = crate::generator::ordering_variant(&name.name) {
                    // Prelude `Ordering` variant → an inline tagged object (the
                    // self-contained representation the primitive-bridge
                    // `compare` and the `_tag`-switch match also use).
                    let _ = write!(self.buf, "{{ _tag: \"{variant}\" as const }}");
                } else if let Some(enum_name) = self
                    .user_variant_for_name(&name.name)
                    .map(|i| i.enum_name.clone())
                {
                    // A bare unit-variant reference (`Red`) → the frozen
                    // `{enum}_{variant}` const.
                    let _ = write!(self.buf, "{enum_name}_{}", name.name);
                } else if self.const_names.contains(&name.name) {
                    // A module-scope `const` is emitted verbatim at its
                    // declaration; spell its use site identically (the
                    // `to_camel_case` transform would mangle `FIZZ_NUM` → `fizzNUM`).
                    self.buf.push_str(&name.name);
                } else {
                    self.buf.push_str(&ts_value_ident(&name.name));
                }
                Ok(())
            }
            NodeKind::BinaryOp { op, left, right } => {
                // `+` on two `List[T]` operands is concatenation: spread both into
                // a fresh array (`[...a, ...b]`). TS rejects `+` on `T[]`
                // (`Operator '+' cannot be applied to T[]`); the spread preserves
                // the element type.
                if matches!(op, BinOp::Add) && crate::generator::is_list_concat(node, left, right) {
                    self.buf.push_str("[...");
                    self.emit_expr(left)?;
                    self.buf.push_str(", ...");
                    self.emit_expr(right)?;
                    self.buf.push(']');
                    return Ok(());
                }
                // Integer `/` and `%` (DQ23, §3.6): TS `/` is float division and
                // `Math.trunc(a / 0)` yields `Infinity` rather than aborting, so
                // lower to a self-contained IIFE that aborts on a zero divisor and
                // truncates toward zero. TS `%` already takes the dividend's sign,
                // so the remainder needs only the zero-abort. Arrow parameters are
                // `number`-annotated for strict mode; both operands are passed as
                // arguments so each is evaluated exactly once.
                if matches!(op, BinOp::Div | BinOp::Rem) && crate::generator::is_int_arith(node) {
                    let body = if matches!(op, BinOp::Div) {
                        "Math.trunc(__a / __b)"
                    } else {
                        "__a % __b"
                    };
                    self.buf.push_str("((__a: number, __b: number): number => { if (__b === 0) { throw new Error(\"integer division or modulo by zero\"); } return ");
                    self.buf.push_str(body);
                    self.buf.push_str("; })(");
                    self.emit_expr(left)?;
                    self.buf.push_str(", ");
                    self.emit_expr(right)?;
                    self.buf.push(')');
                    return Ok(());
                }
                // Ordering operators on a user `Comparable` type lower through
                // `compare` (TS rejects `<` on two objects at compile time, and the
                // runtime would coerce to `NaN`). Reads the tagged `Ordering` off
                // `._tag`, mirroring how a hand-written `a.compare(b)` lowers (the
                // receiver is passed as both the method receiver and the explicit
                // `self` argument).
                if crate::generator::is_user_compare(node) {
                    if let Some((tag, is_eq)) = crate::generator::user_compare_variant(*op) {
                        let recv = self.expr_to_string(left)?;
                        let other = self.expr_to_string(right)?;
                        let eq = if is_eq { "===" } else { "!==" };
                        let _ = write!(
                            self.buf,
                            "(({recv}).compare({recv}, {other})._tag {eq} \"{tag}\")"
                        );
                        return Ok(());
                    }
                }
                // DQ29 (§18.5 structural Equatable): a stamped `==`/`!=`
                // cannot use native `===` (reference identity on objects).
                // The `"impl"` lane dispatches through the explicit
                // `impl Equatable`'s `eq` (receiver doubled as the explicit
                // `self` argument, matching the method-call lowering —
                // Q-js-user-equality-reference, #339); the structural lanes
                // lower through the `__bockEq` runtime helper.
                if matches!(op, BinOp::Eq | BinOp::Ne) {
                    if let Some(kind) = crate::generator::user_eq_kind(node) {
                        let recv = self.expr_to_string(left)?;
                        let other = self.expr_to_string(right)?;
                        let neg = if *op == BinOp::Ne { "!" } else { "" };
                        if kind == "impl" {
                            let _ = write!(self.buf, "{neg}(({recv}).eq({recv}, {other}))");
                        } else {
                            let _ = write!(self.buf, "{neg}__bockEq({recv}, {other})");
                        }
                        return Ok(());
                    }
                }
                self.buf.push('(');
                self.emit_expr(left)?;
                let op_str = match op {
                    BinOp::Add => " + ",
                    BinOp::Sub => " - ",
                    BinOp::Mul => " * ",
                    BinOp::Div => " / ",
                    BinOp::Rem => " % ",
                    BinOp::Pow => " ** ",
                    BinOp::Eq => " === ",
                    BinOp::Ne => " !== ",
                    BinOp::Lt => " < ",
                    BinOp::Le => " <= ",
                    BinOp::Gt => " > ",
                    BinOp::Ge => " >= ",
                    BinOp::And => " && ",
                    BinOp::Or => " || ",
                    BinOp::BitAnd => " & ",
                    BinOp::BitOr => " | ",
                    BinOp::BitXor => " ^ ",
                    BinOp::Compose => " /* >> */ ",
                    BinOp::Is => " instanceof ",
                };
                self.buf.push_str(op_str);
                self.emit_expr(right)?;
                self.buf.push(')');
                Ok(())
            }
            NodeKind::UnaryOp { op, operand } => {
                let op_str = match op {
                    UnaryOp::Neg => "-",
                    UnaryOp::Not => "!",
                    UnaryOp::BitNot => "~",
                };
                self.buf.push_str(op_str);
                self.emit_expr(operand)?;
                Ok(())
            }
            NodeKind::Call { callee, args, .. } => {
                if let Some(code) = self.map_prelude_call(callee, args)? {
                    self.buf.push_str(&code);
                    return Ok(());
                }
                if self.try_emit_prelude_ctor(callee, args)? {
                    return Ok(());
                }
                if self.try_emit_time_assoc_call(callee, args)? {
                    return Ok(());
                }
                if self.try_emit_time_desugared_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_concurrency_call(callee, args)? {
                    return Ok(());
                }
                // Map/Set dispatch precedes the List recogniser so the
                // overlapping method names route by `recv_kind`, not by name.
                if self.try_emit_map_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_set_method(node, callee, args)? {
                    return Ok(());
                }
                // String method dispatch runs *before* the List recogniser so the
                // overlapping `len`/`contains`/`is_empty` names route by the
                // checker's `recv_kind = "Primitive:String"`, not by name alone.
                if self.try_emit_string_method(node, callee, args)? {
                    return Ok(());
                }
                // Numeric/Char/Bool primitive methods (`to_float`/`abs`/`sqrt`/…)
                // likewise route by the checker's `recv_kind = "Primitive:Int|…"`
                // before the generic fall-through, which would emit `n.to_float(n)`.
                if self.try_emit_numeric_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_list_mutating_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_list_inplace_mutator(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_list_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_list_functional_method(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_primitive_bridge(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_trait_bound_bridge(node, callee, args)? {
                    return Ok(());
                }
                if self.try_emit_container_method(node, callee, args)? {
                    return Ok(());
                }
                // Rewrite bare effect operation calls: log(...) → handler.log(...)
                if let NodeKind::Identifier { name } = &callee.kind {
                    if let Some(effect_name) = self.effect_ops.get(&name.name).cloned() {
                        if let Some(handler_var) =
                            self.current_handler_vars.get(&effect_name).cloned()
                        {
                            let _ = write!(self.buf, "{}.{}", handler_var, name.name);
                            self.buf.push('(');
                            for (i, arg) in args.iter().enumerate() {
                                if i > 0 {
                                    self.buf.push_str(", ");
                                }
                                self.emit_expr(&arg.value)?;
                            }
                            self.buf.push(')');
                            return Ok(());
                        }
                    }
                }
                // Q-prim-assoc: a primitive associated-conversion call
                // (`Float.from(x)` / `Int.try_from(s)` / `String.from(c)`)
                // lowers to TS's native conversion, NOT the static-member form
                // below (`Float.from` is undefined on the host `number`).
                if self.try_emit_primitive_conversion(node, callee, args)? {
                    return Ok(());
                }
                // An associated-function call (`Type.method(args)` — stamped by
                // the lowerer, no `self` prepended) resolves to the merged
                // `namespace Type { export function method(...) }` static member.
                // Emit `Type.method(args)` with the type name preserved (it names
                // the namespace/class, not a value); the generic fall-through
                // would camel-case it into a non-existent value.
                if crate::generator::is_associated_call(node) {
                    if let NodeKind::FieldAccess { object, field } = &callee.kind {
                        if let NodeKind::Identifier { name: type_name } = &object.kind {
                            let _ = write!(
                                self.buf,
                                "{}.{}",
                                type_name.name,
                                self.ts_method_name(&field.name)
                            );
                            self.buf.push('(');
                            for (i, arg) in args.iter().enumerate() {
                                if i > 0 {
                                    self.buf.push_str(", ");
                                }
                                self.emit_expr(&arg.value)?;
                            }
                            self.buf.push(')');
                            return Ok(());
                        }
                    }
                }
                // A trait/record method call lowers to `Call(FieldAccess(recv,
                // method), [recv, ...])` (the receiver is re-passed as `self`,
                // sharing the receiver's NodeId — see `desugared_self_call`).
                // When the method name collides with a field name, the *method*
                // was renamed at its declaration (`<name>Method`); rename the
                // call's member access to match so it resolves. A genuine field
                // *read* (bare `FieldAccess`, not in call position) and a
                // field-closure call `(p.f)(x)` (distinct receiver nodes) keep
                // the field name. Shared policy with go/js/py. The prototype
                // function takes an explicit `self`, so all `args` are kept.
                if let NodeKind::FieldAccess { object, field } = &callee.kind {
                    if crate::generator::desugared_self_call(callee, args).is_some() {
                        // The prototype/merged-interface declarations spell the
                        // method with the raw Bock name, so disambiguate the call
                        // against the raw name to match (and the generic
                        // fall-through emits the field raw too).
                        let renamed = self.ts_method_name(&field.name);
                        if renamed != field.name {
                            self.emit_expr(object)?;
                            let _ = write!(self.buf, ".{renamed}");
                            self.buf.push('(');
                            for (i, arg) in args.iter().enumerate() {
                                if i > 0 {
                                    self.buf.push_str(", ");
                                }
                                self.emit_expr(&arg.value)?;
                            }
                            self.buf.push(')');
                            return Ok(());
                        }
                    }
                }
                // Pass handler args to effectful function calls.
                let effects_arg = if let NodeKind::Identifier { name } = &callee.kind {
                    self.build_effects_call_arg_ts(&name.name)
                } else {
                    None
                };
                self.emit_callee(callee)?;
                self.buf.push('(');
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(&arg.value)?;
                }
                if let Some(ea) = effects_arg {
                    if !args.is_empty() {
                        self.buf.push_str(", ");
                    }
                    self.buf.push_str(&ea);
                }
                self.buf.push(')');
                Ok(())
            }
            NodeKind::MethodCall {
                receiver,
                method,
                args,
                ..
            } => {
                if self.try_emit_time_method(receiver, &method.name, args)? {
                    return Ok(());
                }
                self.emit_expr(receiver)?;
                let _ = write!(
                    self.buf,
                    ".{}",
                    self.ts_method_name(&to_camel_case(&method.name))
                );
                self.buf.push('(');
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(&arg.value)?;
                }
                self.buf.push(')');
                Ok(())
            }
            NodeKind::FieldAccess { object, field } => {
                self.emit_expr(object)?;
                let _ = write!(self.buf, ".{}", field.name);
                Ok(())
            }
            NodeKind::Index { object, index } => {
                self.emit_expr(object)?;
                self.buf.push('[');
                self.emit_expr(index)?;
                self.buf.push(']');
                Ok(())
            }
            NodeKind::Lambda { params, body } => {
                let param_list = self.collect_lambda_params(params);
                let _ = write!(self.buf, "({}) => ", param_list.join(", "));
                if matches!(body.kind, NodeKind::Block { .. }) {
                    self.buf.push_str("{\n");
                    self.indent += 1;
                    // A lambda body is a fresh function-body tail context: its
                    // tail is the lambda's return value, so clear any active
                    // statement-position sink (e.g. a `Discard` from an enclosing
                    // loop body) for the duration of the body.
                    let prev_sink = self.value_sink.take();
                    let r = self.emit_block_body(body);
                    self.value_sink = prev_sink;
                    r?;
                    self.indent -= 1;
                    self.write_indent();
                    self.buf.push('}');
                } else {
                    self.emit_expr(body)?;
                }
                Ok(())
            }
            NodeKind::Pipe { left, right } => self.emit_pipe(left, right),
            NodeKind::Compose { left, right } => {
                // `f >> g` → `((x: any) => g(f(x)))`. A composed callee
                // (`left`/`right`) that is itself a `Compose`/`Lambda` must be
                // parenthesized: a bare arrow `(x) => …` followed by `(x)` parses
                // as `(x) => (…(x))`, binding the call to the arrow's body rather
                // than invoking the arrow. `emit_callee` wraps those forms. In
                // practice the AIR lowers `>>` to a `Lambda` before codegen (so
                // chained `>>` reaches the `Call` arm, not here), making this a
                // defensive fall-through.
                let _ = write!(self.buf, "((x: any) => ");
                self.emit_callee(right)?;
                self.buf.push('(');
                self.emit_callee(left)?;
                self.buf.push_str("(x)))");
                Ok(())
            }
            NodeKind::Await { expr } => {
                self.buf.push_str("(await ");
                self.emit_expr(expr)?;
                self.buf.push(')');
                Ok(())
            }
            NodeKind::Propagate { expr } => {
                // `expr?` in *expression* position (nested inside a larger
                // expression). Early-return has no expression form in TS, so the
                // statement-position lowerings (LetBinding value, bare statement,
                // block tail — see `emit_propagate`) handle the common cases. Here
                // we can only unwrap the payload (`._0`); the Err/None branch is
                // *not* propagated, so this is a partial lowering. The examples in
                // scope never hit it (their `?` is always statement-positioned).
                // Tracked as OPEN: nested expression-position `?`.
                self.buf.push('(');
                self.emit_expr(expr)?;
                self.buf.push_str(")._0");
                Ok(())
            }
            NodeKind::Range { lo, hi, inclusive } => {
                if *inclusive {
                    self.buf.push_str("rangeInclusive(");
                } else {
                    self.buf.push_str("range(");
                }
                self.emit_expr(lo)?;
                self.buf.push_str(", ");
                self.emit_expr(hi)?;
                self.buf.push(')');
                Ok(())
            }
            NodeKind::RecordConstruct {
                path,
                fields,
                spread,
            } => {
                // A struct-variant construction (`Circle { radius: 2.0 }`) →
                // the `{enum}_{variant}(field, ..)` factory, in field decl
                // order. Plain records keep their object/class form.
                let struct_variant = if spread.is_none() {
                    self.user_variant_for_path(path).and_then(|info| {
                        if let crate::generator::VariantPayloadKind::Struct(field_order) =
                            &info.payload
                        {
                            Some((info.enum_name.clone(), field_order.clone()))
                        } else {
                            None
                        }
                    })
                } else {
                    None
                };
                if let Some((enum_name, field_order)) = struct_variant {
                    let variant = path.segments.last().map_or("", |s| s.name.as_str());
                    let _ = write!(self.buf, "{enum_name}_{variant}(");
                    for (i, fname) in field_order.iter().enumerate() {
                        if i > 0 {
                            self.buf.push_str(", ");
                        }
                        let supplied = fields.iter().find(|f| &f.name.name == fname);
                        match supplied.and_then(|f| f.value.as_ref()) {
                            Some(val) => self.emit_expr(val)?,
                            None => self.buf.push_str(&ts_value_ident(fname)),
                        }
                    }
                    self.buf.push(')');
                    return Ok(());
                }
                let type_name = path.segments.last().map(|s| s.name.as_str()).unwrap_or("");
                // A Bock `class` lowers to a *positional* `constructor(a, b)`
                // (unlike a record's destructured `constructor({ a, b })`), so a
                // class literal must construct as `new T(a_value, b_value)` with
                // values ordered by the *declared* field order — not the literal's
                // field order, and not a bare object literal (whose inherent/trait
                // methods are not on the object-literal type, so `tsc` rejects the
                // method call). Falls through to the record/object path only when
                // this is not a known class.
                if let Some(field_order) = self.class_fields.get(type_name).cloned() {
                    let _ = write!(self.buf, "new {type_name}(");
                    for (i, fname) in field_order.iter().enumerate() {
                        if i > 0 {
                            self.buf.push_str(", ");
                        }
                        let supplied = fields.iter().find(|f| &f.name.name == fname);
                        match supplied.and_then(|f| f.value.as_ref()) {
                            Some(val) => self.emit_expr(val)?,
                            // A field present in the literal as shorthand
                            // (`T { label }` ≡ `T { label: label }`) — the RHS is
                            // a value reference; otherwise (field omitted, only
                            // possible with a `..base` spread) read it off `base`.
                            None if supplied.is_some() => {
                                self.buf.push_str(&ts_value_ident(fname));
                            }
                            None => match spread {
                                Some(sp) => {
                                    self.emit_expr(sp)?;
                                    let _ = write!(self.buf, ".{}", ts_value_ident(fname));
                                }
                                None => self.buf.push_str("undefined"),
                            },
                        }
                    }
                    self.buf.push(')');
                    return Ok(());
                }
                let is_class = self.record_names.contains(type_name);
                if is_class {
                    let _ = write!(self.buf, "new {type_name}(");
                    if fields.is_empty() && spread.is_none() {
                        self.buf.push(')');
                        return Ok(());
                    }
                }
                if let Some(sp) = spread {
                    self.buf.push_str("{ ...");
                    self.emit_expr(sp)?;
                    if !fields.is_empty() {
                        self.buf.push_str(", ");
                    }
                } else {
                    self.buf.push_str("{ ");
                }
                for (i, f) in fields.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    if let Some(val) = &f.value {
                        let _ = write!(self.buf, "{}: ", f.name.name);
                        self.emit_expr(val)?;
                    } else {
                        self.buf.push_str(&f.name.name);
                    }
                }
                self.buf.push_str(" }");
                if is_class {
                    self.buf.push(')');
                }
                Ok(())
            }
            NodeKind::ListLiteral { elems } => {
                self.buf.push('[');
                for (i, e) in elems.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(e)?;
                }
                self.buf.push(']');
                Ok(())
            }
            NodeKind::MapLiteral { entries } => {
                self.buf.push_str("new Map([");
                for (i, entry) in entries.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.buf.push('[');
                    self.emit_expr(&entry.key)?;
                    self.buf.push_str(", ");
                    self.emit_expr(&entry.value)?;
                    self.buf.push(']');
                }
                self.buf.push_str("])");
                Ok(())
            }
            NodeKind::SetLiteral { elems } => {
                self.buf.push_str("new Set([");
                for (i, e) in elems.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(e)?;
                }
                self.buf.push_str("])");
                Ok(())
            }
            NodeKind::TupleLiteral { elems } => {
                // TS tuples are arrays with typed positions.
                self.buf.push('[');
                for (i, e) in elems.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(e)?;
                }
                self.buf.push(']');
                Ok(())
            }
            NodeKind::Interpolation { parts } => {
                self.buf.push('`');
                for part in parts {
                    match part {
                        AirInterpolationPart::Literal(s) => {
                            self.buf.push_str(&escape_template_literal(s));
                        }
                        AirInterpolationPart::Expr(expr) => {
                            // Q-displayable-interpolation-dispatch: render through
                            // `__bockStr` so a user value with a `Displayable`
                            // impl (its `to_string` method) shows via that method,
                            // not `[object Object]`. Primitives fall back to
                            // native `String(x)`.
                            self.needs_runtime_str = true;
                            self.buf.push_str("${__bockStr(");
                            self.emit_expr(expr)?;
                            self.buf.push_str(")}");
                        }
                    }
                }
                self.buf.push('`');
                Ok(())
            }
            NodeKind::Placeholder => {
                self.buf.push('_');
                Ok(())
            }
            NodeKind::Unreachable => {
                self.buf
                    .push_str("(() => { throw new Error(\"unreachable\"); })()");
                Ok(())
            }
            NodeKind::ResultConstruct { variant, value } => {
                // Use the `_0` payload key — the same shape the surface
                // `Ok(..)`/`Err(..)` construction (`try_emit_prelude_ctor`) emits
                // and the `Result` match reads — so construction and match agree
                // (the old `value`/`error` keys were never read by the match).
                let tag = match variant {
                    ResultVariant::Ok => "Ok",
                    ResultVariant::Err => "Err",
                };
                let _ = write!(self.buf, "{{ _tag: \"{tag}\" as const, _0: ");
                if let Some(v) = value {
                    self.emit_expr(v)?;
                } else {
                    self.buf.push_str("undefined");
                }
                self.buf.push_str(" }");
                Ok(())
            }
            NodeKind::Assign { op, target, value } => {
                self.emit_expr(target)?;
                let op_str = match op {
                    AssignOp::Assign => " = ",
                    AssignOp::AddAssign => " += ",
                    AssignOp::SubAssign => " -= ",
                    AssignOp::MulAssign => " *= ",
                    AssignOp::DivAssign => " /= ",
                    AssignOp::RemAssign => " %= ",
                };
                self.buf.push_str(op_str);
                self.emit_expr(value)?;
                Ok(())
            }
            NodeKind::If {
                condition,
                then_block,
                else_block,
                ..
            } => {
                // Ternary for expression-position if.
                self.buf.push('(');
                self.emit_expr(condition)?;
                self.buf.push_str(" ? ");
                self.emit_block_as_expr(then_block)?;
                self.buf.push_str(" : ");
                if let Some(eb) = else_block {
                    self.emit_block_as_expr(eb)?;
                } else {
                    self.buf.push_str("undefined");
                }
                self.buf.push(')');
                Ok(())
            }
            NodeKind::Block { stmts, tail } => {
                // IIFE. The IIFE body is its own TS lexical scope, so it gets its
                // own `let` scope frame — a name re-bound across two *sibling*
                // IIFEs (e.g. two arms of an expression-position `match`) is two
                // independent declarations, not a redeclaration.
                self.buf.push_str("(() => {\n");
                self.indent += 1;
                self.enter_let_scope(node);
                for s in stmts {
                    self.emit_node(s)?;
                }
                if let Some(t) = tail {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}return ");
                    self.emit_expr(t)?;
                    self.buf.push_str(";\n");
                }
                self.leave_let_scope();
                self.indent -= 1;
                self.write_indent();
                self.buf.push_str("})()");
                Ok(())
            }
            NodeKind::Match { scrutinee, arms } => {
                // Expression-position match → IIFE. When the value is consumed
                // into a typed binding (`let x: T = match …`), annotate the
                // arrow's return type (`(() : T => {…})()`) so a `T` distinct
                // from the enclosing function's inferred return is respected, and
                // force-hoist a bare-identifier scrutinee so `switch (s)` does not
                // narrow `s` to the case literal inside arm bodies (TS2367). The
                // expected type is taken here so it scopes to this IIFE only and
                // does not leak into the (separately typed) arm-body expressions.
                let expected = self.current_expected_type.take();
                let arrow_ret = expected
                    .as_deref()
                    .map(|t| format!(" : {t}"))
                    .unwrap_or_default();
                let force_hoist = expected.is_some();
                let _ = write!(self.buf, "((){arrow_ret} => {{");
                self.buf.push('\n');
                self.indent += 1;
                // The IIFE arrow returns the matched arm's value, so its arm
                // bodies deliver through a `Return` sink — *not* whatever
                // statement-position sink is active outside (a `Discard` from an
                // enclosing loop/statement context, or an `Assign` from an outer
                // statement-form lowering). Reset for the IIFE body, restore after
                // so the outer sink is untouched.
                let prev_sink = self.value_sink.replace(ValueSink::Return);
                let r = self.emit_match(scrutinee, arms, force_hoist);
                self.value_sink = prev_sink;
                r?;
                self.indent -= 1;
                self.write_indent();
                self.buf.push_str("})()");
                self.current_expected_type = expected;
                Ok(())
            }
            // Ownership: erase
            NodeKind::Move { expr }
            | NodeKind::Borrow { expr }
            | NodeKind::MutableBorrow { expr } => self.emit_expr(expr),
            // Effect operation invocation
            NodeKind::EffectOp {
                effect,
                operation,
                args,
            } => {
                let effect_name = effect.segments.last().map_or("effect", |s| s.name.as_str());
                let _ = write!(
                    self.buf,
                    "{}.{}",
                    to_camel_case(effect_name),
                    operation.name
                );
                self.buf.push('(');
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    self.emit_expr(&arg.value)?;
                }
                self.buf.push(')');
                Ok(())
            }
            // Type expressions in expression position: emit the TS type
            NodeKind::TypeNamed { .. }
            | NodeKind::TypeTuple { .. }
            | NodeKind::TypeFunction { .. }
            | NodeKind::TypeOptional { .. }
            | NodeKind::TypeSelf => {
                let ty_str = self.type_to_ts(node);
                let _ = write!(self.buf, "/* {ty_str} */");
                Ok(())
            }
            NodeKind::EffectRef { path } => {
                let name = path
                    .segments
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<_>>()
                    .join(".");
                self.buf.push_str(&name);
                Ok(())
            }
            NodeKind::Error => {
                self.buf.push_str("/* error */");
                Ok(())
            }
            _ => {
                self.buf.push_str("/* unsupported */");
                Ok(())
            }
        }
    }

    // ── Match → switch ──────────────────────────────────────────────────────

    /// Lower a `match`. `force_hoist` requests that even a bare-identifier
    /// scrutinee be hoisted into a single `const __matchN = …;` temp before the
    /// `switch` — set for an expression-position match consumed into a typed
    /// binding, so the `switch` narrows the temp (not the original binding) and
    /// arm bodies re-referencing the scrutinee do not trip TS2367. Statement-
    /// position calls pass `false`, preserving the inline `switch (s)` fast-path.
    fn emit_match(
        &mut self,
        scrutinee: &AIRNode,
        arms: &[AIRNode],
        force_hoist: bool,
    ) -> Result<(), CodegenError> {
        // Guards, or-patterns, tuple patterns, and nested constructor/record
        // patterns cannot be expressed by the flat `switch` below. Lower those
        // to an if/else-if chain. Additive: the proven Optional / Result /
        // user-enum / value `switch` fast-path is kept for everything else (see
        // `match_needs_ifchain`). The if-chain already casts the scrutinee root
        // to `as any`, which itself defeats the TS2367 narrowing, so `force_hoist`
        // is irrelevant there.
        if crate::generator::match_needs_ifchain(arms) {
            return self.emit_match_ifchain(scrutinee, arms);
        }

        // ADT (dispatch on `._tag`) when any arm is a constructor pattern or a
        // record pattern naming a registered enum variant. The record-pattern
        // case is the struct-payload variant the prior `ConstructorPat`-only
        // check missed (DV14).
        let is_adt = arms.iter().any(|arm| {
            let NodeKind::MatchArm { pattern, .. } = &arm.kind else {
                return false;
            };
            match &pattern.kind {
                NodeKind::ConstructorPat { .. } => true,
                NodeKind::RecordPat { path, .. } => self.user_variant_for_path(path).is_some(),
                _ => false,
            }
        });

        // Hoist a non-trivial scrutinee into a single `const __matchN = …;` so it
        // is evaluated once and TS narrowing on `__matchN._tag` reaches the
        // payload access `__matchN._0` in the arm bodies. A bare identifier is
        // already a stable reference — normally left inline. But `force_hoist`
        // (an expression-position value match) hoists it too, so `switch
        // (__matchN)` narrows the temp rather than the original binding, keeping
        // arm bodies that re-reference the scrutinee free of TS2367.
        let temp = if matches!(scrutinee.kind, NodeKind::Identifier { .. }) && !force_hoist {
            None
        } else {
            self.match_temp_counter += 1;
            let name = format!("__match{}", self.match_temp_counter);
            let ind = self.indent_str();
            let _ = write!(self.buf, "{ind}const {name} = ");
            self.emit_expr(scrutinee)?;
            self.buf.push_str(";\n");
            Some(name)
        };

        let ind = self.indent_str();
        let _ = write!(self.buf, "{ind}switch (");
        self.emit_scrutinee_ref(scrutinee, temp.as_deref())?;
        if is_adt {
            self.buf.push_str("._tag) {\n");
        } else {
            self.buf.push_str(") {\n");
        }
        self.indent += 1;
        self.switch_label_depth += 1;
        for arm in arms {
            self.emit_match_arm(arm, is_adt, scrutinee, temp.as_deref())?;
        }
        self.switch_label_depth -= 1;
        self.indent -= 1;
        self.writeln("}");
        Ok(())
    }

    /// Emit a reference to the match scrutinee: the hoisted temp name when one
    /// was introduced, else the scrutinee expression inline (a bare identifier).
    fn emit_scrutinee_ref(
        &mut self,
        scrutinee: &AIRNode,
        temp: Option<&str>,
    ) -> Result<(), CodegenError> {
        match temp {
            Some(name) => {
                self.buf.push_str(name);
                Ok(())
            }
            None => self.emit_expr(scrutinee),
        }
    }

    /// Render the scrutinee reference (hoisted temp name, else the inline
    /// scrutinee expression) to a `String` instead of straight to `self.buf`,
    /// by swapping in a scratch buffer for the duration. Used by the ADT-arm
    /// payload bindings to build the narrowing cast around the reference.
    fn scrutinee_ref_string(
        &mut self,
        scrutinee: &AIRNode,
        temp: Option<&str>,
    ) -> Result<String, CodegenError> {
        let saved = std::mem::take(&mut self.buf);
        let result = self.emit_scrutinee_ref(scrutinee, temp);
        let rendered = std::mem::replace(&mut self.buf, saved);
        result.map(|()| rendered)
    }

    /// Wrap a scrutinee reference in a discriminated-union narrowing cast so a
    /// constructor/record arm's payload binding is pinned to the matched
    /// variant's member type — `(<ref> as Extract<typeof <ref>, { _tag:
    /// "<variant>" }>)`.
    ///
    /// TS narrows `s` to the matched member inside a reachable `case "<variant>":`
    /// arm, so `s._0` is the payload type. But narrowing is control-flow-scoped:
    /// when an earlier statement-position `match` has every arm `return`, TS
    /// marks the rest of the function unreachable and stops narrowing, so a later
    /// arm's bare `s._0` widens back to the full union payload and tripping
    /// TS2345 (e.g. `T | E` passed to a `T` parameter — the task-api blocker).
    /// `Extract<typeof s, { _tag: "<variant>" }>` selects the matched member
    /// structurally, independent of reachability, so the binding never widens.
    /// `Extract` on a non-union or `any` scrutinee is a no-op / `any`, and on a
    /// non-matching member yields `never` (whose `._N` assigns anywhere), so the
    /// cast is sound for every ADT scrutinee shape.
    fn narrowing_cast(scrutinee_ref: &str, variant: &str) -> String {
        format!("({scrutinee_ref} as Extract<typeof {scrutinee_ref}, {{ _tag: \"{variant}\" }}>)")
    }

    /// Emit a TS label before a loop iff a contained statement-arm `match`
    /// needs to `break`/`continue` the loop. Pair with [`Self::pop_loop_frame`].
    /// Also pushes a `None` loop result-sink frame; a value-position loop (see
    /// [`Self::emit_value_in_stmt_pos`]) overwrites it with [`Self::set_loop_value_sink`].
    fn emit_loop_label_prefix(&mut self, body: &AIRNode) {
        if crate::generator::loop_needs_break_label(body) {
            self.loop_label_counter += 1;
            let label = format!("__bockLoop{}", self.loop_label_counter);
            self.writeln(&format!("{label}:"));
            self.loop_labels.push(Some(label));
        } else {
            self.loop_labels.push(None);
        }
        self.loop_value_sinks.push(None);
    }

    /// Pop the loop frame pushed by [`Self::emit_loop_label_prefix`] (both the
    /// label and the result-sink entry).
    fn pop_loop_frame(&mut self) {
        self.loop_labels.pop();
        self.loop_value_sinks.pop();
    }

    /// Set the innermost loop's result sink — where `break v` writes the loop's
    /// value (`<binding> = v;` / `return v;`). Called right after
    /// [`Self::emit_loop_label_prefix`] for a value-position loop.
    fn set_loop_value_sink(&mut self, sink: ValueSink) {
        if let Some(top) = self.loop_value_sinks.last_mut() {
            *top = Some(sink);
        }
    }

    /// The innermost loop's result sink, if it is a value-position loop.
    fn innermost_loop_value_sink(&self) -> Option<ValueSink> {
        self.loop_value_sinks.last().and_then(Clone::clone)
    }

    /// Label of the innermost loop, if one was allocated.
    fn innermost_loop_label(&self) -> Option<&str> {
        self.loop_labels.last().and_then(|l| l.as_deref())
    }

    fn emit_match_arm(
        &mut self,
        arm: &AIRNode,
        is_adt: bool,
        scrutinee: &AIRNode,
        temp: Option<&str>,
    ) -> Result<(), CodegenError> {
        if let NodeKind::MatchArm {
            pattern,
            guard,
            body,
        } = &arm.kind
        {
            match &pattern.kind {
                NodeKind::WildcardPat => {
                    self.writeln("default: {");
                }
                NodeKind::BindPat { name, is_mut } if !is_adt => {
                    self.writeln("default: {");
                    self.indent += 1;
                    // A `mut x =>` arm reassigns the binding in its body, so it
                    // must be `let` — emitting `const` trips TS2588 ("cannot
                    // assign to a constant").
                    let kw = if *is_mut { "let" } else { "const" };
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}{kw} {} = ", name.name);
                    self.emit_scrutinee_ref(scrutinee, temp)?;
                    self.buf.push_str(";\n");
                    self.indent -= 1;
                }
                NodeKind::LiteralPat { lit } => {
                    let ind = self.indent_str();
                    let _ = write!(self.buf, "{ind}case ");
                    match lit {
                        Literal::Int(s) => self.buf.push_str(s),
                        Literal::Float(s) => self.buf.push_str(s),
                        Literal::Bool(b) => self.buf.push_str(if *b { "true" } else { "false" }),
                        Literal::Char(s) => {
                            self.buf.push('\'');
                            self.buf.push_str(s);
                            self.buf.push('\'');
                        }
                        Literal::String(s) => {
                            self.buf.push('"');
                            self.buf.push_str(&escape_js_string(s));
                            self.buf.push('"');
                        }
                        Literal::Unit => self.buf.push_str("undefined"),
                    }
                    self.buf.push_str(": {\n");
                }
                NodeKind::ConstructorPat { path, fields } => {
                    let variant_name = path.segments.last().map_or("_", |s| s.name.as_str());
                    self.writeln(&format!("case \"{variant_name}\": {{"));
                    if !fields.is_empty() {
                        self.indent += 1;
                        // Cast the scrutinee to the matched variant member so each
                        // payload binding stays the variant's payload type even in
                        // control-flow-unreachable arms (see `narrowing_cast`).
                        let scrut_ref = self.scrutinee_ref_string(scrutinee, temp)?;
                        let cast = Self::narrowing_cast(&scrut_ref, variant_name);
                        for (i, field) in fields.iter().enumerate() {
                            let binding = self.pattern_to_binding_name(field);
                            let ind = self.indent_str();
                            let _ = writeln!(self.buf, "{ind}const {binding} = {cast}._{i};");
                        }
                        self.indent -= 1;
                    }
                }
                NodeKind::RecordPat { path, fields, .. } => {
                    let variant_name = path.segments.last().map_or("_", |s| s.name.as_str());
                    if is_adt {
                        self.writeln(&format!("case \"{variant_name}\": {{"));
                    } else {
                        self.writeln("default: {");
                    }
                    if !fields.is_empty() {
                        self.indent += 1;
                        // For a struct-payload enum variant (`is_adt`), pin each
                        // field binding to the matched member via the narrowing
                        // cast so it survives control-flow-unreachable arms (see
                        // `narrowing_cast`). A non-ADT record destructure binds off
                        // the un-narrowed scrutinee as before.
                        let scrut_ref = self.scrutinee_ref_string(scrutinee, temp)?;
                        let access = if is_adt {
                            Self::narrowing_cast(&scrut_ref, variant_name)
                        } else {
                            scrut_ref
                        };
                        for f in fields {
                            let field_name = &f.name.name;
                            let binding = match &f.pattern {
                                Some(pat) => self.pattern_to_binding_name(pat),
                                None => field_name.clone(),
                            };
                            let ind = self.indent_str();
                            let _ =
                                writeln!(self.buf, "{ind}const {binding} = {access}.{field_name};");
                        }
                        self.indent -= 1;
                    }
                }
                _ => {
                    self.writeln("default: {");
                }
            }

            self.indent += 1;
            if let Some(g) = guard {
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}if (!(");
                self.emit_expr(g)?;
                self.buf.push_str(")) break;\n");
            }
            self.emit_block_body(body)?;
            self.writeln("break;");
            self.indent -= 1;
            self.writeln("}");
        }
        Ok(())
    }

    // ── Match → if/else-if chain (guards, or-/tuple/nested patterns) ──────────

    /// Lower a `match` whose arms cannot be expressed by a flat `switch` (see
    /// [`crate::generator::match_needs_ifchain`]) to an `if (<test>) { <binds>;
    /// <body> } else if …` chain. Mirrors the JS lowering; the only difference
    /// is that TS access paths into the scrutinee are cast through `as any` so a
    /// nested access (`__matchN._0._tag`) typechecks without relying on
    /// discriminated-union narrowing flowing through `&&`.
    fn emit_match_ifchain(
        &mut self,
        scrutinee: &AIRNode,
        arms: &[AIRNode],
    ) -> Result<(), CodegenError> {
        // Single-evaluation root. A bare identifier is stable; anything else is
        // hoisted into `__matchN`. The access root the tests/binds descend from
        // is cast to `any` so nested field access typechecks under `tsc`.
        let root: String = if let NodeKind::Identifier { name } = &scrutinee.kind {
            format!("({} as any)", name.name)
        } else {
            self.match_temp_counter += 1;
            let name = format!("__match{}", self.match_temp_counter);
            let ind = self.indent_str();
            let _ = write!(self.buf, "{ind}const {name} = ");
            self.emit_expr(scrutinee)?;
            self.buf.push_str(";\n");
            format!("({name} as any)")
        };

        let mut first = true;
        let mut closed = false;
        let arm_count = arms.len();
        for (idx, arm) in arms.iter().enumerate() {
            let NodeKind::MatchArm {
                pattern,
                guard,
                body,
            } = &arm.kind
            else {
                continue;
            };
            let test = self.pattern_test_ts(pattern, &root);
            let is_catch_all = matches!(
                pattern.kind,
                NodeKind::WildcardPat | NodeKind::BindPat { .. }
            );
            let is_last = idx + 1 == arm_count;
            // See the JS lowering: an unguarded catch-all *or* the final
            // unguarded arm becomes the unconditional `else`, closing the chain
            // so a value-returning function typechecks under `tsc`.
            let unconditional = guard.is_none() && (is_catch_all || is_last);
            let ind = self.indent_str();
            if unconditional {
                if first {
                    let _ = writeln!(self.buf, "{ind}{{");
                } else {
                    let _ = writeln!(self.buf, "{ind}else {{");
                }
                closed = true;
            } else {
                let mut cond = if test.is_empty() {
                    "true".to_string()
                } else {
                    test
                };
                if let Some(g) = guard {
                    let g_str = self.expr_to_string(g)?;
                    let binds = self.pattern_binds_to_string_ts(pattern, &root);
                    let guard_test = if binds.is_empty() {
                        format!("({g_str})")
                    } else {
                        format!("(() => {{ {binds}return ({g_str}); }})()")
                    };
                    if cond == "true" {
                        cond = guard_test;
                    } else {
                        cond = format!("{cond} && {guard_test}");
                    }
                }
                if first {
                    let _ = writeln!(self.buf, "{ind}if ({cond}) {{");
                } else {
                    let _ = writeln!(self.buf, "{ind}else if ({cond}) {{");
                }
            }
            first = false;
            self.indent += 1;
            self.pattern_binds_ts(pattern, &root)?;
            self.emit_block_body(body)?;
            self.indent -= 1;
            self.writeln("}");
        }
        if !closed && !first {
            self.writeln("else { throw new Error(\"non-exhaustive match\"); }");
        }
        Ok(())
    }

    /// Build the boolean test that selects `pat` against the TS expression
    /// `access` (already `any`-typed by the caller). Mirrors `pattern_test_js`.
    fn pattern_test_ts(&self, pat: &AIRNode, access: &str) -> String {
        match &pat.kind {
            NodeKind::WildcardPat | NodeKind::BindPat { .. } => String::new(),
            NodeKind::LiteralPat { lit } => {
                format!("{access} === {}", ts_literal(lit))
            }
            NodeKind::ConstructorPat { path, fields } => {
                let variant = path.segments.last().map_or("_", |s| s.name.as_str());
                let mut tests = vec![format!("{access}._tag === \"{variant}\"")];
                for (i, field) in fields.iter().enumerate() {
                    let sub = self.pattern_test_ts(field, &format!("{access}._{i}"));
                    if !sub.is_empty() {
                        tests.push(sub);
                    }
                }
                tests.join(" && ")
            }
            NodeKind::RecordPat { path, fields, .. } => {
                let variant = path.segments.last().map_or("_", |s| s.name.as_str());
                let mut tests = Vec::new();
                if self.user_variant_for_path(path).is_some() {
                    tests.push(format!("{access}._tag === \"{variant}\""));
                }
                for f in fields {
                    if let Some(p) = &f.pattern {
                        let sub = self.pattern_test_ts(p, &format!("{access}.{}", f.name.name));
                        if !sub.is_empty() {
                            tests.push(sub);
                        }
                    }
                }
                if tests.is_empty() {
                    String::new()
                } else {
                    tests.join(" && ")
                }
            }
            NodeKind::TuplePat { elems } => {
                let mut tests = vec![format!("Array.isArray({access})")];
                for (i, e) in elems.iter().enumerate() {
                    let sub = self.pattern_test_ts(e, &format!("{access}[{i}]"));
                    if !sub.is_empty() {
                        tests.push(sub);
                    }
                }
                tests.join(" && ")
            }
            NodeKind::ListPat { elems, rest } => {
                // `[a, b]` requires an array of exactly len(elems); `[a, ..rest]`
                // requires at least len(elems). Element sub-patterns are tested
                // positionally; the rest binds the slice and adds no test.
                // Mirrors `pattern_test_js`.
                let n = elems.len();
                let len_test = if rest.is_some() {
                    format!("{access}.length >= {n}")
                } else {
                    format!("{access}.length === {n}")
                };
                let mut tests = vec![format!("Array.isArray({access})"), len_test];
                for (i, e) in elems.iter().enumerate() {
                    let sub = self.pattern_test_ts(e, &format!("{access}[{i}]"));
                    if !sub.is_empty() {
                        tests.push(sub);
                    }
                }
                tests.join(" && ")
            }
            NodeKind::RangePat { lo, hi, inclusive } => {
                // `lo..hi` → `access >= lo && access < hi`; `lo..=hi` uses `<=`.
                // Mirrors `pattern_test_js`.
                let lo_s = range_bound_to_ts(lo);
                let hi_s = range_bound_to_ts(hi);
                let upper = if *inclusive { "<=" } else { "<" };
                format!("{access} >= {lo_s} && {access} {upper} {hi_s}")
            }
            NodeKind::OrPat { alternatives } => {
                let alts: Vec<String> = alternatives
                    .iter()
                    .map(|a| {
                        let t = self.pattern_test_ts(a, access);
                        if t.is_empty() {
                            "true".to_string()
                        } else {
                            format!("({t})")
                        }
                    })
                    .collect();
                alts.join(" || ")
            }
            _ => String::new(),
        }
    }

    /// Emit the `const <name> = <access…>;` bindings introduced by `pat`.
    /// Mirrors `pattern_binds_js`.
    fn pattern_binds_ts(&mut self, pat: &AIRNode, access: &str) -> Result<(), CodegenError> {
        match &pat.kind {
            // Skip a self-binding (`const n = n` / `const n = (n as any)`): when
            // an arm's bind name equals the scrutinee access — e.g.
            // `match n { n if … }`, whose if-chain root is the `(n as any)` cast —
            // the name already refers to the value. Emitting `const n = (n as any)`
            // shadows the parameter and the RHS reads the just-declared `const`
            // (TS2448, used before declaration). The guard lets such a binding
            // fall through to the no-op `_` arm.
            NodeKind::BindPat { name, .. } if !ts_bind_is_self_reference(&name.name, access) => {
                let ind = self.indent_str();
                let _ = writeln!(
                    self.buf,
                    "{ind}const {} = {access};",
                    ts_value_ident(&name.name)
                );
            }
            NodeKind::ConstructorPat { fields, .. } => {
                for (i, field) in fields.iter().enumerate() {
                    self.pattern_binds_ts(field, &format!("{access}._{i}"))?;
                }
            }
            NodeKind::RecordPat { fields, .. } => {
                for f in fields {
                    let field_access = format!("{access}.{}", f.name.name);
                    match &f.pattern {
                        Some(p) => self.pattern_binds_ts(p, &field_access)?,
                        None => {
                            let ind = self.indent_str();
                            let _ =
                                writeln!(self.buf, "{ind}const {} = {field_access};", f.name.name);
                        }
                    }
                }
            }
            NodeKind::TuplePat { elems } => {
                for (i, e) in elems.iter().enumerate() {
                    self.pattern_binds_ts(e, &format!("{access}[{i}]"))?;
                }
            }
            NodeKind::ListPat { elems, rest } => {
                for (i, e) in elems.iter().enumerate() {
                    self.pattern_binds_ts(e, &format!("{access}[{i}]"))?;
                }
                // `..rest` binds the remaining elements as a slice; a bare `..`
                // (RestPat) or absent rest binds nothing. Mirrors `pattern_binds_js`.
                if let Some(r) = rest {
                    if let NodeKind::BindPat { name, .. } = &r.kind {
                        let ind = self.indent_str();
                        let _ = writeln!(
                            self.buf,
                            "{ind}const {} = {access}.slice({});",
                            ts_value_ident(&name.name),
                            elems.len()
                        );
                    }
                }
            }
            NodeKind::OrPat { alternatives } => {
                if let Some(first) = alternatives.first() {
                    self.pattern_binds_ts(first, access)?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Collect `pat`'s bindings as a single-line `const … = …; ` string for the
    /// guard-evaluating IIFE. Mirrors `pattern_binds_to_string_js`.
    fn pattern_binds_to_string_ts(&self, pat: &AIRNode, access: &str) -> String {
        let mut out = String::new();
        self.collect_binds_ts(pat, access, &mut out);
        out
    }

    fn collect_binds_ts(&self, pat: &AIRNode, access: &str, out: &mut String) {
        match &pat.kind {
            NodeKind::BindPat { name, .. } => {
                // Skip a self-binding (`const n = (n as any)`) — redundant and a
                // TS2448 TDZ error inside the guard-evaluating IIFE. See
                // `pattern_binds_ts`.
                if ts_bind_is_self_reference(&name.name, access) {
                    return;
                }
                let _ = write!(out, "const {} = {access}; ", ts_value_ident(&name.name));
            }
            NodeKind::ConstructorPat { fields, .. } => {
                for (i, field) in fields.iter().enumerate() {
                    self.collect_binds_ts(field, &format!("{access}._{i}"), out);
                }
            }
            NodeKind::RecordPat { fields, .. } => {
                for f in fields {
                    let field_access = format!("{access}.{}", f.name.name);
                    match &f.pattern {
                        Some(p) => self.collect_binds_ts(p, &field_access, out),
                        None => {
                            let _ = write!(out, "const {} = {field_access}; ", f.name.name);
                        }
                    }
                }
            }
            NodeKind::TuplePat { elems } => {
                for (i, e) in elems.iter().enumerate() {
                    self.collect_binds_ts(e, &format!("{access}[{i}]"), out);
                }
            }
            NodeKind::ListPat { elems, rest } => {
                for (i, e) in elems.iter().enumerate() {
                    self.collect_binds_ts(e, &format!("{access}[{i}]"), out);
                }
                if let Some(r) = rest {
                    if let NodeKind::BindPat { name, .. } = &r.kind {
                        let _ = write!(
                            out,
                            "const {} = {access}.slice({}); ",
                            ts_value_ident(&name.name),
                            elems.len()
                        );
                    }
                }
            }
            NodeKind::OrPat { alternatives } => {
                if let Some(first) = alternatives.first() {
                    self.collect_binds_ts(first, access, out);
                }
            }
            _ => {}
        }
    }

    // ── Pipe operator ───────────────────────────────────────────────────────

    fn emit_pipe(&mut self, left: &AIRNode, right: &AIRNode) -> Result<(), CodegenError> {
        if let NodeKind::Call { callee, args, .. } = &right.kind {
            let has_placeholder = args
                .iter()
                .any(|a| matches!(a.value.kind, NodeKind::Placeholder));
            if has_placeholder {
                self.emit_callee(callee)?;
                self.buf.push('(');
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        self.buf.push_str(", ");
                    }
                    if matches!(arg.value.kind, NodeKind::Placeholder) {
                        self.emit_expr(left)?;
                    } else {
                        self.emit_expr(&arg.value)?;
                    }
                }
                self.buf.push(')');
                return Ok(());
            }
        }
        // `right` is a callee, so parenthesize it when it is a bare arrow
        // (`Lambda`/`Compose`) — otherwise the trailing `(left)` binds to the
        // arrow body instead of invoking it.
        self.emit_callee(right)?;
        self.buf.push('(');
        self.emit_expr(left)?;
        self.buf.push(')');
        Ok(())
    }

    /// Emit an expression in **callee** position, parenthesizing it when its
    /// surface syntax would otherwise swallow the trailing argument list.
    ///
    /// The case that matters is a bare arrow callee: `(x) => body` followed by
    /// `(arg)` parses in TS as `(x) => (body(arg))` — the call binds to the body,
    /// never invoking the arrow. Wrapping it as `((x) => body)(arg)` makes the
    /// call apply to the arrow itself. This arises when the AIR compose desugar
    /// (`f >> g` → `(__compose_x) => g(f(__compose_x))`) **nests**: a chained
    /// `>>` lowers the inner compose to a `Lambda` (or a `Compose` still awaiting
    /// lowering), which then appears as the callee `f`/`g` inside the call.
    /// Mirrors the python (`emit_callee`) and rust (`emit_callee_rs`) backends.
    fn emit_callee(&mut self, callee: &AIRNode) -> Result<(), CodegenError> {
        if matches!(
            callee.kind,
            NodeKind::Lambda { .. } | NodeKind::Compose { .. }
        ) {
            self.buf.push('(');
            self.emit_expr(callee)?;
            self.buf.push(')');
            Ok(())
        } else {
            self.emit_expr(callee)
        }
    }

    // ── Helpers ─────────────────────────────────────────────────────────────

    /// Returns true if `ts_name` has already been declared in the innermost
    /// `let` scope, so a further binding of it must be a plain assignment rather
    /// than a `const`/`let` re-declaration (which TS rejects with TS2451).
    fn simple_let_redeclared(&self, ts_name: &str) -> bool {
        self.let_scopes
            .last()
            .is_some_and(|s| s.declared.contains(ts_name))
    }

    /// Returns true if `ts_name` is re-bound or assigned later in its block, so
    /// its first declaration must use `let` (not `const`) to allow reassignment.
    fn simple_let_needs_let(&self, ts_name: &str) -> bool {
        self.let_scopes
            .last()
            .is_some_and(|s| s.needs_let.contains(ts_name))
    }

    /// Record that `ts_name` has now been declared in the innermost `let` scope.
    fn mark_simple_let_declared(&mut self, ts_name: &str) {
        if let Some(s) = self.let_scopes.last_mut() {
            s.declared.insert(ts_name.to_string());
        }
    }

    /// Push a fresh `let` scope for a TS block, pre-scanning `block`'s direct
    /// statements to find which simple `let`-bound names are re-bound or
    /// assigned within the block (so their first declaration emits `let`). Only
    /// the block's own statements are scanned — nested blocks open their own
    /// scopes, so a name re-bound only in a nested block does not force `let`
    /// here. Mirrors the js backend (#217).
    fn enter_let_scope(&mut self, block: &AIRNode) {
        let mut needs_let = HashSet::new();
        if let NodeKind::Block { stmts, tail } = &block.kind {
            let mut seen: HashSet<String> = HashSet::new();
            let mut visit = |n: &AIRNode, needs_let: &mut HashSet<String>| match &n.kind {
                NodeKind::LetBinding { pattern, .. } => {
                    if let NodeKind::BindPat { name, .. } = &pattern.kind {
                        let ts = ts_value_ident(&name.name);
                        // A re-binding of an already-seen name needs `let`.
                        if !seen.insert(ts.clone()) {
                            needs_let.insert(ts);
                        }
                    }
                }
                NodeKind::Assign { target, .. } => {
                    if let NodeKind::Identifier { name } = &target.kind {
                        needs_let.insert(ts_value_ident(&name.name));
                    }
                }
                _ => {}
            };
            for s in stmts {
                visit(s, &mut needs_let);
            }
            if let Some(t) = tail {
                visit(t, &mut needs_let);
            }
        }
        self.let_scopes.push(LetScope {
            declared: HashSet::new(),
            needs_let,
        });
    }

    /// Pop the innermost `let` scope pushed by [`Self::enter_let_scope`].
    fn leave_let_scope(&mut self) {
        self.let_scopes.pop();
    }

    fn emit_block_body(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        self.enter_let_scope(node);
        let r = self.emit_block_body_inner(node);
        self.leave_let_scope();
        r
    }

    /// Emit a **loop body** (`for`/`while`/`loop`). A loop body is statement
    /// position: its tail expression is discarded (Bock loops evaluate to Unit;
    /// the body's value is not the function's value). The default
    /// [`Self::emit_block_body`] treats a tail as a function-body return, which
    /// for a loop body would `return console.log(i);` — aborting the function on
    /// the first iteration. Activating a [`ValueSink::Discard`] for the body's
    /// duration routes the tail to a bare expression statement instead. The sink
    /// is saved/restored so it never leaks past the loop, and any nested lambda
    /// clears it (a lambda body's tail is genuinely returned — see the
    /// `NodeKind::Lambda` arm). A `break v` value still flows through the
    /// separate per-loop `loop_value_sinks` stack, not this discard sink.
    fn emit_loop_body(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        let prev_sink = self.value_sink.replace(ValueSink::Discard);
        let r = self.emit_block_body(node);
        self.value_sink = prev_sink;
        r
    }

    /// Emit a function/method body whose top-level `let` scope is pre-seeded with
    /// the function's `params` as already-declared names. A Bock `let x = …` that
    /// shadows a parameter `x` is the same block scope as the TS parameter, so it
    /// must lower to a plain assignment (`x = …`) rather than a `let`/`const`
    /// redeclaration (which TS rejects). Mirrors the js backend (#217).
    fn emit_fn_body_seeded(
        &mut self,
        params: &[AIRNode],
        body: &AIRNode,
    ) -> Result<(), CodegenError> {
        self.enter_let_scope(body);
        if let Some(scope) = self.let_scopes.last_mut() {
            for p in params {
                if let NodeKind::Param { pattern, .. } = &p.kind {
                    if let NodeKind::BindPat { name, .. } = &pattern.kind {
                        let ts = ts_value_ident(&name.name);
                        scope.needs_let.insert(ts.clone());
                        scope.declared.insert(ts);
                    }
                }
            }
        }
        let r = self.emit_block_body_inner(body);
        self.leave_let_scope();
        r
    }

    fn emit_block_body_inner(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        if let NodeKind::Block { stmts, tail } = &node.kind {
            // Every non-tail statement is statement position: its value is
            // discarded. A statement-position `if`/`match` whose branch/arm
            // bodies end in an expression (e.g. `println(...)`) must NOT `return`
            // that value — doing so aborts the function before the statements
            // after the `if`/`match` run. Activate a `Discard` sink for the
            // non-tail statements (restored before the tail, which keeps the
            // function-body-return semantics). A nested loop/lambda overrides
            // this sink within its own body, so the discard applies only to the
            // immediate statement-position control flow.
            let prev_sink = self.value_sink.replace(ValueSink::Discard);
            let mut stmt_res = Ok(());
            for s in stmts {
                stmt_res = self.emit_node(s);
                if stmt_res.is_err() {
                    break;
                }
            }
            self.value_sink = prev_sink;
            stmt_res?;
            if let Some(t) = tail {
                if crate::generator::node_is_statement(t) {
                    self.emit_node(t)?;
                    return Ok(());
                }
                // A diverging-intrinsic tail (`todo()`/`unreachable()`) lowers to
                // a bare `throw` statement — emitting `return throw …` is invalid
                // TS (TS1109). Emit it as a statement instead.
                if self.call_is_diverging(t) {
                    self.write_indent();
                    self.emit_expr(t)?;
                    self.buf.push_str(";\n");
                    return Ok(());
                }
                // A tail-position `expr?`: emit the early-return guard, then
                // `return` the unwrapped payload (the fn's value). Through the
                // sink when one is active (statement-position control flow).
                if let NodeKind::Propagate { expr } = &t.kind {
                    let access = self.emit_propagate(expr)?;
                    if let Some(sink) = self.value_sink.clone() {
                        return self.emit_sink_value_str(&access, &sink);
                    }
                    let ind = self.indent_str();
                    let _ = writeln!(self.buf, "{ind}return {access};");
                    return Ok(());
                }
                // Expression-position control flow whose branches carry
                // statements (a value `if`/`match` with a `return` arm, or a
                // `loop` producing its value via `break v`) has no TS expression
                // form. Lower it in statement position, delivering each value
                // tail through the active sink (default `return`; cluster-1 fix;
                // see `emit_value_in_stmt_pos`).
                if self.value_needs_stmt_form(t) {
                    let sink = self.value_sink.clone().unwrap_or(ValueSink::Return);
                    return self.emit_value_in_stmt_pos(t, &sink);
                }
                if let NodeKind::Match { scrutinee, arms } = &t.kind {
                    if crate::generator::match_has_statement_arm(arms) {
                        self.emit_match(scrutinee, arms, false)?;
                        return Ok(());
                    }
                }
                self.emit_block_tail_value(t)?;
            }
        } else if crate::generator::node_is_statement(node) {
            self.emit_node(node)?;
        } else if self.call_is_diverging(node) {
            self.write_indent();
            self.emit_expr(node)?;
            self.buf.push_str(";\n");
        } else if self.value_needs_stmt_form(node) {
            let sink = self.value_sink.clone().unwrap_or(ValueSink::Return);
            self.emit_value_in_stmt_pos(node, &sink)?;
        } else if let NodeKind::Match { scrutinee, arms } = &node.kind {
            if crate::generator::match_has_statement_arm(arms) {
                self.emit_match(scrutinee, arms, false)?;
            } else {
                self.emit_block_tail_value(node)?;
            }
        } else {
            self.emit_block_tail_value(node)?;
        }
        Ok(())
    }

    /// Deliver a block's value tail. When a [`ValueSink`] is active (the block is
    /// a `match`-arm body inside a statement-position control-flow lowering), the
    /// value flows through it (`return v` / `binding = v`); otherwise the default
    /// function-body behavior — `return v` — applies.
    fn emit_block_tail_value(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        if let Some(sink) = self.value_sink.clone() {
            return self.emit_sink_value(node, &sink);
        }
        let ind = self.indent_str();
        let _ = write!(self.buf, "{ind}return ");
        self.emit_expr(node)?;
        self.buf.push_str(";\n");
        Ok(())
    }

    /// True when a `Call` is to a diverging intrinsic (`todo()` / `unreachable()`),
    /// which lowers to a bare `throw new Error(...)` *statement* — never produces
    /// a value. Emitting it after `return ` (`return throw …`) is invalid TS, so
    /// callers in value-tail position must emit it as a statement instead.
    fn call_is_diverging(&self, node: &AIRNode) -> bool {
        if let NodeKind::Call { callee, .. } = &node.kind {
            if let NodeKind::Identifier { name } = &callee.kind {
                return matches!(name.name.as_str(), "todo" | "unreachable");
            }
        }
        false
    }

    /// True when `node` (in *value* position) contains control flow that has no
    /// TypeScript expression form — a `Loop` (its value arrives via `break v`), or
    /// an `if`/`match`/`block` any of whose value-tails is a `return`/`break`/
    /// `continue`, a diverging intrinsic call, or (recursively) a nested
    /// control-flow value that itself needs statement form. Such a value must be
    /// emitted in **statement** position (assigning the result to a binding, or
    /// `return`ing it) via [`Self::emit_value_in_stmt_pos`] — the ternary /
    /// value-IIFE lowering would emit `/* unsupported */` for the control-flow
    /// tail. The recursion is what makes a *nested* `if … else if … else { return
    /// … }` chain (chat-protocol) trigger the statement lowering, not just a
    /// single-level `if`.
    fn value_needs_stmt_form(&self, node: &AIRNode) -> bool {
        match &node.kind {
            // A loop never has an expression form; its value comes from `break v`.
            NodeKind::Loop { .. } => true,
            NodeKind::If {
                then_block,
                else_block,
                let_pattern: None,
                ..
            } => {
                self.branch_needs_stmt_form(then_block)
                    || else_block
                        .as_deref()
                        .is_some_and(|e| self.branch_needs_stmt_form(e))
            }
            NodeKind::Match { arms, .. } => arms.iter().any(|arm| {
                matches!(&arm.kind, NodeKind::MatchArm { body, .. } if self.branch_needs_stmt_form(body))
            }),
            NodeKind::Block { tail, .. } => {
                tail.as_deref().is_some_and(|t| self.value_needs_stmt_form(t))
            }
            _ => false,
        }
    }

    /// True when a branch / arm body (an `if`/`match`/`loop`/`block` arm, or a
    /// bare expression) used in value position requires statement-form lowering:
    /// its value tail is a diverging statement, or it is itself control flow that
    /// needs statement form. Drives the recursion in [`Self::value_needs_stmt_form`].
    fn branch_needs_stmt_form(&self, node: &AIRNode) -> bool {
        self.value_tail_diverges(node) || self.value_needs_stmt_form(node)
    }

    /// True when the *value tail* of `node` is a diverging statement — a
    /// `return`/`break`/`continue` node, a diverging intrinsic call, or (for a
    /// block) a tail that itself diverges. Drives [`Self::branch_needs_stmt_form`]:
    /// a value-position branch whose tail is one of these cannot be a ternary/IIFE
    /// arm.
    fn value_tail_diverges(&self, node: &AIRNode) -> bool {
        match &node.kind {
            NodeKind::Return { .. } | NodeKind::Break { .. } | NodeKind::Continue => true,
            NodeKind::Call { .. } => self.call_is_diverging(node),
            NodeKind::Block { stmts, tail } => match tail {
                Some(t) => self.value_tail_diverges(t),
                // A block with no tail (ends in a statement) yields no value.
                None => stmts.last().is_some_and(|s| self.value_tail_diverges(s)),
            },
            _ => false,
        }
    }

    /// Emit a value-position expression that [`Self::value_needs_stmt_form`] has
    /// flagged, in **statement** position, delivering its result via `sink`
    /// (`return <v>;` or `<name> = <v>;`). Diverging tails (`return`/`break`/
    /// `continue`/`todo()`) emit their own statement and ignore the sink. This is
    /// the TS-side desugar of expression-position control flow whose branches
    /// carry statements; it keeps `return`/`break` in the enclosing function/loop
    /// scope (an IIFE would capture them) — see the cluster-1 OPEN in the PR body
    /// proposing a shared AIR desugar.
    fn emit_value_in_stmt_pos(
        &mut self,
        node: &AIRNode,
        sink: &ValueSink,
    ) -> Result<(), CodegenError> {
        match &node.kind {
            // A diverging statement: emit it directly, ignore the sink.
            NodeKind::Return { .. } | NodeKind::Break { .. } | NodeKind::Continue => {
                self.emit_node(node)
            }
            NodeKind::Call { .. } if self.call_is_diverging(node) => {
                self.write_indent();
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
                Ok(())
            }
            NodeKind::Loop { body } => {
                self.emit_loop_label_prefix(body);
                // The loop's value arrives through `break v` (recorded in the
                // separate `loop_value_sinks` stack), NOT the body's tail — the
                // body is statement position, so its tail is discarded via
                // `emit_loop_body`.
                self.set_loop_value_sink(sink.clone());
                self.writeln("while (true) {");
                self.indent += 1;
                self.emit_loop_body(body)?;
                self.indent -= 1;
                self.writeln("}");
                self.pop_loop_frame();
                Ok(())
            }
            NodeKind::If {
                let_pattern: None,
                condition,
                then_block,
                else_block,
            } => {
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}if (");
                self.emit_expr(condition)?;
                self.buf.push_str(") {\n");
                self.indent += 1;
                self.emit_value_in_stmt_pos(then_block, sink)?;
                self.indent -= 1;
                if let Some(else_b) = else_block {
                    if matches!(
                        else_b.kind,
                        NodeKind::If {
                            let_pattern: None,
                            ..
                        }
                    ) {
                        let ind = self.indent_str();
                        let _ = write!(self.buf, "{ind}}} else ");
                        // Re-dispatch the nested `if` without re-opening a brace.
                        self.emit_value_in_stmt_pos_else_if(else_b, sink)?;
                        return Ok(());
                    }
                    self.writeln("} else {");
                    self.indent += 1;
                    self.emit_value_in_stmt_pos(else_b, sink)?;
                    self.indent -= 1;
                }
                self.writeln("}");
                Ok(())
            }
            NodeKind::Match { scrutinee, arms } => {
                let prev = self.value_sink.replace(sink.clone());
                let res = self.emit_match(scrutinee, arms, false);
                self.value_sink = prev;
                res
            }
            NodeKind::Block { stmts, tail } => {
                for s in stmts {
                    self.emit_node(s)?;
                }
                if let Some(t) = tail {
                    self.emit_value_in_stmt_pos(t, sink)?;
                }
                Ok(())
            }
            // A plain value: deliver it through the sink.
            _ => self.emit_sink_value(node, sink),
        }
    }

    /// Helper for the `else if` chain in [`Self::emit_value_in_stmt_pos`]: emits an
    /// `if (...) { … } else …` after the caller has already written `} else `.
    fn emit_value_in_stmt_pos_else_if(
        &mut self,
        node: &AIRNode,
        sink: &ValueSink,
    ) -> Result<(), CodegenError> {
        let NodeKind::If {
            condition,
            then_block,
            else_block,
            ..
        } = &node.kind
        else {
            return self.emit_value_in_stmt_pos(node, sink);
        };
        self.buf.push_str("if (");
        self.emit_expr(condition)?;
        self.buf.push_str(") {\n");
        self.indent += 1;
        self.emit_value_in_stmt_pos(then_block, sink)?;
        self.indent -= 1;
        if let Some(else_b) = else_block {
            if matches!(
                else_b.kind,
                NodeKind::If {
                    let_pattern: None,
                    ..
                }
            ) {
                let ind = self.indent_str();
                let _ = write!(self.buf, "{ind}}} else ");
                self.emit_value_in_stmt_pos_else_if(else_b, sink)?;
                return Ok(());
            }
            self.writeln("} else {");
            self.indent += 1;
            self.emit_value_in_stmt_pos(else_b, sink)?;
            self.indent -= 1;
        }
        self.writeln("}");
        Ok(())
    }

    /// Deliver a finished value expression `node` through `sink`.
    fn emit_sink_value(&mut self, node: &AIRNode, sink: &ValueSink) -> Result<(), CodegenError> {
        let ind = self.indent_str();
        match sink {
            ValueSink::Return => {
                let _ = write!(self.buf, "{ind}return ");
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
            }
            ValueSink::Assign(name) => {
                let _ = write!(self.buf, "{ind}{name} = ");
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
            }
            ValueSink::Discard => {
                let _ = write!(self.buf, "{ind}");
                self.emit_expr(node)?;
                self.buf.push_str(";\n");
            }
        }
        Ok(())
    }

    /// Deliver an already-rendered value expression `value` through `sink`
    /// (`return value;` / `name = value;`). Used by the tail-position `?`
    /// lowering, whose unwrapped payload is a literal access string rather than
    /// an [`AIRNode`].
    fn emit_sink_value_str(&mut self, value: &str, sink: &ValueSink) -> Result<(), CodegenError> {
        let ind = self.indent_str();
        match sink {
            ValueSink::Return => {
                let _ = writeln!(self.buf, "{ind}return {value};");
            }
            ValueSink::Assign(name) => {
                let _ = writeln!(self.buf, "{ind}{name} = {value};");
            }
            ValueSink::Discard => {
                let _ = writeln!(self.buf, "{ind}{value};");
            }
        }
        Ok(())
    }

    fn emit_block_as_expr(&mut self, node: &AIRNode) -> Result<(), CodegenError> {
        if let NodeKind::Block { stmts, tail } = &node.kind {
            if stmts.is_empty() {
                if let Some(t) = tail {
                    return self.emit_expr(t);
                }
            }
        }
        self.emit_expr(node)
    }

    fn pattern_to_binding_name(&self, pat: &AIRNode) -> String {
        match &pat.kind {
            NodeKind::BindPat { name, .. } => ts_value_ident(&name.name),
            NodeKind::WildcardPat => "_".into(),
            NodeKind::TuplePat { elems } => {
                format!(
                    "[{}]",
                    elems
                        .iter()
                        .map(|e| self.pattern_to_binding_name(e))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            NodeKind::RecordPat { fields, .. } => {
                format!(
                    "{{ {} }}",
                    fields
                        .iter()
                        .map(|f| to_camel_case(&f.name.name).to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            _ => "_".into(),
        }
    }

    fn pattern_to_ts_destructure(&self, pat: &AIRNode) -> String {
        self.pattern_to_binding_name(pat)
    }

    fn type_expr_to_string(&self, node: &AIRNode) -> String {
        match &node.kind {
            NodeKind::TypeNamed { path, .. } => path
                .segments
                .iter()
                .map(|s| s.name.as_str())
                .collect::<Vec<_>>()
                .join("."),
            NodeKind::Identifier { name } => name.name.clone(),
            _ => "Unknown".into(),
        }
    }
}

// ─── Utility functions ───────────────────────────────────────────────────────

/// Build the `: T` return-type clause for a TS function signature, wrapping
/// the inner type in `Promise<...>` when the function is async. An async
/// function with no declared return type is typed `Promise<void>`.
fn build_ts_return_type(is_async: bool, inner: Option<String>) -> String {
    match (is_async, inner) {
        (true, Some(t)) => format!(": Promise<{t}>"),
        (true, None) => ": Promise<void>".to_string(),
        (false, Some(t)) => format!(": {t}"),
        (false, None) => String::new(),
    }
}

/// Returns true if `name` is the identifier of a Duration or Instant instance
/// method. Used to recognise `d.as_millis()` / `i.elapsed()` calls during codegen.
fn is_time_method_name(name: &str) -> bool {
    matches!(
        name,
        "as_nanos"
            | "as_millis"
            | "as_seconds"
            | "is_zero"
            | "is_negative"
            | "abs"
            | "elapsed"
            | "duration_since"
    )
}

/// Convert a name to `camelCase` (handles `snake_case`, `PascalCase`, and already `camelCase`).
/// Convert a Bock *value* identifier (a param, local binding, or free-function
/// name) to its TS form: `camelCase`, then escaped against the TS reserved-word
/// set so a binding named e.g. `default`/`type` emits `default_`/`type_` rather
/// than the illegal bare keyword. Apply at every value declaration and reference
/// site so the escaped name is used uniformly; member/method names use bare
/// [`to_camel_case`]. See [`crate::generator::escape_target_keyword`].
///
/// On top of the shared reserved-word escape, TS modules are emitted in *strict
/// mode* (ES modules always are), which makes `eval` and `arguments` illegal as
/// binding names — a `function eval(...)` declaration is rejected with `TS1215:
/// Invalid use of 'eval'` even though `eval` is not a keyword. The shared
/// keyword set is target-agnostic and JS (non-module/sloppy-mode) accepts these
/// names, so they are escaped here, in the TS-only funnel, with the same
/// trailing-`_` mangle the keyword escape uses (`eval` → `eval_`). Applied at
/// the single value-ident funnel so declarations and references stay in sync.
fn ts_value_ident(name: &str) -> String {
    let escaped = crate::generator::escape_target_keyword(
        &to_camel_case(name),
        crate::generator::KeywordTarget::Ts,
    );
    if matches!(escaped.as_str(), "eval" | "arguments") {
        format!("{escaped}_")
    } else {
        escaped
    }
}

/// True when binding `bind_name` against `access` would be a self-reference:
/// the access is either the bare TS name (`n`) or its if-chain cast form
/// (`(n as any)`). Emitting `const n = (n as any)` shadows the parameter and
/// reads the freshly-declared `const` in its own initialiser (TS2448), so such
/// a binding must be skipped. Mirrors the JS `js != access` self-bind guard.
fn ts_bind_is_self_reference(bind_name: &str, access: &str) -> bool {
    let ts = ts_value_ident(bind_name);
    access == ts || access == format!("({ts} as any)")
}

/// Spell `name` the way the TS backend emits the symbol's declaration / call
/// sites for an `import`/`export` specifier in the per-module path: a function
/// is camelCased and keyword-escaped via [`ts_value_ident`]; any other kind
/// (records, enum variants, classes, traits, effects, consts, type aliases)
/// keeps its raw name.
fn ts_esm_emit_name(name: &str, is_fn: bool) -> String {
    if is_fn {
        ts_value_ident(name)
    } else {
        name.to_string()
    }
}

fn to_camel_case(s: &str) -> String {
    if s.is_empty() || s == "_" {
        return s.to_string();
    }
    // If already camelCase (starts lowercase, no underscores), return as-is.
    if !s.contains('_') && s.starts_with(|c: char| c.is_lowercase()) {
        return s.to_string();
    }
    // If it's snake_case, convert to camelCase.
    if s.contains('_') {
        let parts: Vec<&str> = s.split('_').filter(|p| !p.is_empty()).collect();
        if parts.is_empty() {
            return s.to_string();
        }
        let mut result = parts[0].to_lowercase();
        for part in &parts[1..] {
            let mut chars = part.chars();
            if let Some(first) = chars.next() {
                result.push(
                    first
                        .to_uppercase()
                        .next()
                        .expect("uppercase yields at least one char"),
                );
                result.extend(chars);
            }
        }
        return result;
    }
    // If PascalCase, lowercase first letter.
    let mut chars = s.chars();
    let first = chars.next().expect("non-empty string guaranteed by caller");
    let mut result = first.to_lowercase().to_string();
    result.extend(chars);
    result
}

/// Escape special characters in a JS/TS string literal.
fn escape_js_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(ch),
        }
    }
    out
}

/// Render a literal as a TS value expression — used by the if-chain match
/// lowering to compare a scrutinee against a literal pattern (`<access> === …`).
/// Render a `RangePat` bound (`lo`/`hi`) as a TS expression. Range bounds are
/// literals (`1..10`) or a const identifier (`MIN..MAX`); anything else falls
/// back to the wrapped literal/identifier text, or `0` for an unrecognised node.
/// Mirrors `range_bound_to_js`.
fn range_bound_to_ts(node: &AIRNode) -> String {
    match &node.kind {
        NodeKind::LiteralPat { lit } => ts_literal(lit),
        NodeKind::Literal { lit } => ts_literal(lit),
        NodeKind::Identifier { name } => ts_value_ident(&name.name),
        _ => "0".to_string(),
    }
}

fn ts_literal(lit: &Literal) -> String {
    match lit {
        Literal::Int(s) | Literal::Float(s) => s.clone(),
        Literal::Bool(b) => {
            if *b {
                "true".to_string()
            } else {
                "false".to_string()
            }
        }
        Literal::Char(s) => format!("'{s}'"),
        Literal::String(s) => format!("\"{}\"", escape_js_string(s)),
        Literal::Unit => "undefined".to_string(),
    }
}

/// Escape special characters in a JS/TS template literal.
fn escape_template_literal(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '`' => out.push_str("\\`"),
            '\\' => out.push_str("\\\\"),
            '$' => out.push_str("\\$"),
            _ => out.push(ch),
        }
    }
    out
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use bock_air::{AirArg, AirRecordField};
    use bock_ast::{GenericParam, Ident, TypeExpr, TypePath};
    use bock_errors::{FileId, Span};

    fn span() -> Span {
        Span {
            file: FileId(0),
            start: 0,
            end: 0,
        }
    }

    fn ident(name: &str) -> Ident {
        Ident {
            name: name.to_string(),
            span: span(),
        }
    }

    fn type_path(segments: &[&str]) -> TypePath {
        TypePath {
            segments: segments.iter().map(|s| ident(s)).collect(),
            span: span(),
        }
    }

    fn node(id: u32, kind: NodeKind) -> AIRNode {
        AIRNode::new(id, span(), kind)
    }

    fn int_lit(id: u32, val: &str) -> AIRNode {
        node(
            id,
            NodeKind::Literal {
                lit: Literal::Int(val.into()),
            },
        )
    }

    fn str_lit(id: u32, val: &str) -> AIRNode {
        node(
            id,
            NodeKind::Literal {
                lit: Literal::String(val.into()),
            },
        )
    }

    fn id_node(id: u32, name: &str) -> AIRNode {
        node(id, NodeKind::Identifier { name: ident(name) })
    }

    fn bind_pat(id: u32, name: &str) -> AIRNode {
        node(
            id,
            NodeKind::BindPat {
                name: ident(name),
                is_mut: false,
            },
        )
    }

    fn typed_param_node(id: u32, name: &str, ty_name: &str) -> AIRNode {
        node(
            id,
            NodeKind::Param {
                pattern: Box::new(bind_pat(id + 100, name)),
                ty: Some(Box::new(node(
                    id + 200,
                    NodeKind::TypeNamed {
                        path: type_path(&[ty_name]),
                        args: vec![],
                    },
                ))),
                default: None,
            },
        )
    }

    fn type_node(id: u32, name: &str) -> AIRNode {
        node(
            id,
            NodeKind::TypeNamed {
                path: type_path(&[name]),
                args: vec![],
            },
        )
    }

    /// A parameter with no type annotation (e.g. the `self` receiver of an
    /// impl method, which Bock declares as bare `self`).
    fn untyped_param_node(id: u32, name: &str) -> AIRNode {
        node(
            id,
            NodeKind::Param {
                pattern: Box::new(bind_pat(id + 100, name)),
                ty: None,
                default: None,
            },
        )
    }

    fn block(id: u32, stmts: Vec<AIRNode>, tail: Option<AIRNode>) -> AIRNode {
        node(
            id,
            NodeKind::Block {
                stmts,
                tail: tail.map(Box::new),
            },
        )
    }

    fn module(imports: Vec<AIRNode>, items: Vec<AIRNode>) -> AIRNode {
        node(
            0,
            NodeKind::Module {
                path: None,
                annotations: vec![],
                imports,
                items,
            },
        )
    }

    fn gen(module: &AIRNode) -> String {
        let gen = TsGenerator::new();
        let result = gen.generate_module(module).unwrap();
        result.files[0].content.clone()
    }

    fn make_generic_param(name: &str) -> GenericParam {
        GenericParam {
            id: 0,
            span: span(),
            name: ident(name),
            bounds: vec![],
        }
    }

    fn make_bounded_generic_param(name: &str, bounds: &[&str]) -> GenericParam {
        GenericParam {
            id: 0,
            span: span(),
            name: ident(name),
            bounds: bounds.iter().map(|b| type_path(&[b])).collect(),
        }
    }

    fn make_type_expr(name: &str) -> TypeExpr {
        TypeExpr::Named {
            id: 0,
            span: span(),
            path: type_path(&[name]),
            args: vec![],
        }
    }

    fn make_record_field(name: &str, ty_name: &str) -> bock_ast::RecordDeclField {
        bock_ast::RecordDeclField {
            id: 0,
            span: span(),
            name: ident(name),
            ty: make_type_expr(ty_name),
            default: None,
        }
    }

    // ── Basic tests ─────────────────────────────────────────────────────────

    #[test]
    fn implements_code_generator_trait() {
        let gen = TsGenerator::new();
        assert_eq!(gen.target().id, "ts");
    }

    #[test]
    fn empty_module() {
        let m = module(vec![], vec![]);
        let out = gen(&m);
        assert_eq!(out, "");
    }

    #[test]
    fn generate_project_uses_source_mirrored_path_for_ts() {
        let gen = TsGenerator::new();
        let m = module(vec![], vec![]);
        let src_path = std::path::Path::new("src/lib.bock");
        let result = gen.generate_project(&[(&m, src_path)]).unwrap();
        assert_eq!(result.files[0].path, std::path::PathBuf::from("lib.ts"));
    }

    /// A module node with a declared dotted `path`, for the per-module tests.
    fn module_with_path(path: &[&str], imports: Vec<AIRNode>, items: Vec<AIRNode>) -> AIRNode {
        node(
            0,
            NodeKind::Module {
                path: Some(bock_ast::ModulePath {
                    segments: path.iter().map(|s| ident(s)).collect(),
                    span: span(),
                }),
                annotations: vec![],
                imports,
                items,
            },
        )
    }

    /// An `import <path>.{ name }` AIR node (single-item `Named` import).
    fn import_named(id: u32, path: &[&str], name: &str) -> AIRNode {
        node(
            id,
            NodeKind::ImportDecl {
                path: bock_ast::ModulePath {
                    segments: path.iter().map(|s| ident(s)).collect(),
                    span: span(),
                },
                items: bock_ast::ImportItems::Named(vec![bock_ast::ImportedName {
                    span: span(),
                    name: ident(name),
                    alias: None,
                }]),
            },
        )
    }

    /// A bare `fn <name>() -> <tail>` declaration with the given visibility.
    fn fn_decl_tail(id: u32, vis: Visibility, name: &str, tail: AIRNode) -> AIRNode {
        node(
            id,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: vis,
                is_async: false,
                name: ident(name),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(id + 1, vec![], Some(tail))),
            },
        )
    }

    #[test]
    fn per_module_emits_native_esm_import_tree_ts() {
        // entry `module main` uses `mathutil.add_one`; emission must produce
        // `main.ts` (with `import { addOne } from "./mathutil.ts"` — the relative
        // specifier references the *emitted* `.ts` source directly) and
        // `mathutil.ts`. The `package.json` run affordance is emitted by the
        // scaffolder (project mode), NOT codegen (S6a / DV18).
        let call = node(
            10,
            NodeKind::Call {
                callee: Box::new(id_node(11, "add_one")),
                args: vec![bock_air::AirArg {
                    label: None,
                    value: int_lit(12, "6"),
                }],
                type_args: vec![],
            },
        );
        let main_mod = module_with_path(
            &["main"],
            vec![import_named(5, &["mathutil"], "add_one")],
            vec![fn_decl_tail(1, Visibility::Private, "main", call)],
        );
        let util_mod = module_with_path(
            &["mathutil"],
            vec![],
            vec![fn_decl_tail(
                20,
                Visibility::Public,
                "add_one",
                int_lit(22, "7"),
            )],
        );

        let gen = TsGenerator::new();
        let out = gen
            .generate_project(&[
                (&main_mod, std::path::Path::new("src/main.bock")),
                (&util_mod, std::path::Path::new("src/mathutil.bock")),
            ])
            .unwrap();
        let by_name = |p: &str| out.files.iter().find(|f| f.path == std::path::Path::new(p));
        let main_file = by_name("main.ts").expect("main.ts emitted");
        let util_file = by_name("mathutil.ts").expect("mathutil.ts emitted");
        // Codegen no longer emits the run affordance (S6a / DV18) — the
        // scaffolder owns the `package.json` in project mode.
        assert!(
            by_name("package.json").is_none(),
            "codegen must NOT emit package.json — the scaffolder owns it (S6a)"
        );
        assert!(
            main_file
                .content
                .contains("import { addOne } from \"./mathutil.ts\";"),
            "main.ts must import the camelCased fn via the `.ts` specifier; got:\n{}",
            main_file.content
        );
        assert!(
            util_file.content.contains("export function addOne("),
            "mathutil.ts must export the fn inline; got:\n{}",
            util_file.content
        );
    }

    #[test]
    fn per_module_imports_enum_type_via_import_type_ts() {
        // entry `module main` references a `public enum Color` declared in
        // `module palette` *as a type* (a function param annotation). The enum's
        // type name has no JS binding, so TS must `import type { Color }` — not a
        // value import. The variants are re-exported by `palette.ts` and lower
        // inline as tagged objects.
        let color_enum = node(
            40,
            NodeKind::EnumDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Color"),
                generic_params: vec![],
                variants: vec![
                    node(
                        41,
                        NodeKind::EnumVariant {
                            name: ident("Red"),
                            payload: EnumVariantPayload::Unit,
                        },
                    ),
                    node(
                        42,
                        NodeKind::EnumVariant {
                            name: ident("Blue"),
                            payload: EnumVariantPayload::Unit,
                        },
                    ),
                ],
            },
        );
        let palette_mod = module_with_path(&["palette"], vec![], vec![color_enum]);
        // `fn paint(c: Color) -> Int { 0 }` — `Color` appears as a type only.
        let paint = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("main"),
                generic_params: vec![],
                params: vec![typed_param_node(2, "c", "Color")],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(4, vec![], Some(int_lit(5, "0")))),
            },
        );
        let main_mod = module_with_path(
            &["main"],
            vec![import_named(6, &["palette"], "Color")],
            vec![paint],
        );

        let gen = TsGenerator::new();
        let out = gen
            .generate_project(&[
                (&main_mod, std::path::Path::new("src/main.bock")),
                (&palette_mod, std::path::Path::new("src/palette.bock")),
            ])
            .unwrap();
        let by_name = |p: &str| out.files.iter().find(|f| f.path == std::path::Path::new(p));
        let main_file = by_name("main.ts").expect("main.ts emitted");
        let palette_file = by_name("palette.ts").expect("palette.ts emitted");
        assert!(
            main_file
                .content
                .contains("import type { Color } from \"./palette.ts\";"),
            "main.ts must `import type` the enum type; got:\n{}",
            main_file.content
        );
        assert!(
            palette_file
                .content
                .contains("export { Color_Blue, Color_Red };"),
            "palette.ts must re-export the enum variant values; got:\n{}",
            palette_file.content
        );
    }

    // ── Type annotations ────────────────────────────────────────────────────

    #[test]
    fn function_with_type_annotations() {
        let body = block(10, vec![], Some(id_node(11, "x")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("add"),
                generic_params: vec![],
                params: vec![
                    typed_param_node(2, "x", "Int"),
                    typed_param_node(3, "y", "Int"),
                ],
                return_type: Some(Box::new(type_node(4, "Int"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("x: number"), "got: {out}");
        assert!(out.contains("y: number"), "got: {out}");
        assert!(out.contains("): number"), "got: {out}");
        assert!(out.contains("export function add"));
    }

    #[test]
    fn function_without_type_annotations() {
        let body = block(10, vec![], Some(int_lit(11, "42")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("answer"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("function answer()"), "got: {out}");
        assert!(!out.contains("export"), "got: {out}");
    }

    // ── Generics ────────────────────────────────────────────────────────────

    #[test]
    fn function_with_generics() {
        let body = block(10, vec![], Some(id_node(11, "x")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("identity"),
                generic_params: vec![make_generic_param("T")],
                params: vec![typed_param_node(2, "x", "T")],
                return_type: Some(Box::new(type_node(3, "T"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("function identity<T>"), "got: {out}");
        assert!(out.contains("x: T"), "got: {out}");
        assert!(out.contains("): T"), "got: {out}");
    }

    #[test]
    fn generics_with_bounds() {
        let body = block(10, vec![], Some(id_node(11, "x")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("sorted"),
                generic_params: vec![make_bounded_generic_param("T", &["Comparable"])],
                params: vec![typed_param_node(2, "x", "T")],
                return_type: Some(Box::new(type_node(3, "T"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        // GAP-C: `Comparable` is a sealed-core trait with no user `impl` in this
        // module, so the `extends Comparable` bound (no such TS type) is dropped to
        // a bare `<T>`; the `.compare` call is lowered to a native operator. A
        // user-declared `Comparable` would keep its `extends` (see use_core_compare).
        assert!(
            out.contains("function sorted<T>(x: T): T {") && !out.contains("extends"),
            "got: {out}"
        );
    }

    // ── Traits → Interfaces ─────────────────────────────────────────────────

    #[test]
    fn trait_becomes_interface() {
        let method = node(
            2,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("area"),
                generic_params: vec![],
                params: vec![],
                return_type: Some(Box::new(type_node(3, "Float"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(4, vec![], None)),
            },
        );
        let trait_decl = node(
            1,
            NodeKind::TraitDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_platform: false,
                name: ident("Shape"),
                generic_params: vec![],
                associated_types: vec![],
                methods: vec![method],
            },
        );
        let out = gen(&module(vec![], vec![trait_decl]));
        assert!(out.contains("export interface Shape"), "got: {out}");
        assert!(out.contains("area(): number"), "got: {out}");
    }

    #[test]
    fn trait_with_generics() {
        let method = node(
            2,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("compare"),
                generic_params: vec![],
                params: vec![typed_param_node(3, "other", "T")],
                return_type: Some(Box::new(type_node(4, "Int"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(5, vec![], None)),
            },
        );
        let trait_decl = node(
            1,
            NodeKind::TraitDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_platform: false,
                name: ident("Comparable"),
                generic_params: vec![make_generic_param("T")],
                associated_types: vec![],
                methods: vec![method],
            },
        );
        let out = gen(&module(vec![], vec![trait_decl]));
        assert!(out.contains("interface Comparable<T>"), "got: {out}");
        assert!(out.contains("compare(other: T): number"), "got: {out}");
    }

    #[test]
    fn trait_decl_self_param_typed_as_trait_interface() {
        // P2 item 2: a trait method whose leading `self` is untyped must be
        // typed as the trait's own interface type (here `Eq`) — otherwise `tsc
        // --strict` flags `self` as an implicit `any`.
        let method = node(
            2,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("equals"),
                generic_params: vec![],
                params: vec![untyped_param_node(3, "self")],
                return_type: Some(Box::new(type_node(4, "Bool"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(5, vec![], None)),
            },
        );
        let trait_decl = node(
            1,
            NodeKind::TraitDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_platform: false,
                name: ident("Eq"),
                generic_params: vec![],
                associated_types: vec![],
                methods: vec![method],
            },
        );
        let out = gen(&module(vec![], vec![trait_decl]));
        assert!(
            out.contains("equals(self: Eq): boolean"),
            "trait `self` should be typed as the trait interface, got: {out}"
        );
    }

    // ── Records → Interfaces ────────────────────────────────────────────────

    #[test]
    fn record_becomes_interface_and_factory() {
        let record = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Point"),
                generic_params: vec![],
                fields: vec![
                    make_record_field("x", "Float"),
                    make_record_field("y", "Float"),
                ],
            },
        );
        let out = gen(&module(vec![], vec![record]));
        assert!(out.contains("export class Point"), "got: {out}");
        assert!(out.contains("x: number"), "got: {out}");
        assert!(out.contains("y: number"), "got: {out}");
        assert!(
            out.contains("constructor({ x, y }: { x: number; y: number })"),
            "got: {out}"
        );
        assert!(out.contains("this.x = x;"), "got: {out}");
        assert!(out.contains("this.y = y;"), "got: {out}");
    }

    // ── Enums → Discriminated unions ────────────────────────────────────────

    #[test]
    fn enum_becomes_discriminated_union() {
        let variants = vec![
            node(
                2,
                NodeKind::EnumVariant {
                    name: ident("None"),
                    payload: EnumVariantPayload::Unit,
                },
            ),
            node(
                3,
                NodeKind::EnumVariant {
                    name: ident("Some"),
                    payload: EnumVariantPayload::Struct(vec![make_record_field("value", "T")]),
                },
            ),
        ];
        let enum_decl = node(
            1,
            NodeKind::EnumDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Option"),
                generic_params: vec![make_generic_param("T")],
                variants,
            },
        );
        let out = gen(&module(vec![], vec![enum_decl]));
        // Union type: each variant reference carries the enum's type args
        // (`Option_None<T> | Option_Some<T>`), at the same arity the variant
        // interfaces declare — referencing them bare fails `tsc` with TS2314
        // (Q-ts-generic-enum-codegen).
        assert!(
            out.contains("export type Option<T> = Option_None<T> | Option_Some<T>;"),
            "got: {out}"
        );
        // Unit variant: a phantom (unused) type param gets an `= unknown`
        // default so the zero-arg `const Option_None: Option_None` annotation is
        // valid while the union still references it as `Option_None<T>`.
        assert!(
            out.contains("interface Option_None<T = unknown>"),
            "got: {out}"
        );
        assert!(out.contains("readonly _tag: \"None\""), "got: {out}");
        assert!(
            out.contains("const Option_None: Option_None = "),
            "got: {out}"
        );
        // Struct variant: interface and factory return type carry consistent
        // arity (`Option_Some<T>` … `: Option_Some<T>`).
        assert!(out.contains("interface Option_Some<T>"), "got: {out}");
        assert!(out.contains("readonly value: T"), "got: {out}");
        assert!(
            out.contains("function Option_Some<T>(value: T): Option_Some<T>"),
            "got: {out}"
        );
    }

    /// Q-ts-variant-constructed-let-typing: a type-annotated binding initialised
    /// by a single variant construction must widen the initialiser to the
    /// declared enum *union* (`Gate_Open(7) as Gate`), not narrow `g` to the
    /// construction variant — otherwise a later `match g` on a sibling variant
    /// fails `tsc --noEmit` (TS2678). Covers all three payload shapes: struct
    /// (`RecordConstruct`), tuple (`Call` on a variant name), and unit
    /// (bare `Identifier`).
    #[test]
    fn typed_let_binding_widens_variant_construct_to_declared_union() {
        let gate = node(
            1,
            NodeKind::EnumDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Gate"),
                generic_params: vec![],
                variants: vec![
                    node(
                        2,
                        NodeKind::EnumVariant {
                            name: ident("Open"),
                            payload: EnumVariantPayload::Struct(vec![make_record_field(
                                "level", "Int",
                            )]),
                        },
                    ),
                    node(
                        3,
                        NodeKind::EnumVariant {
                            name: ident("Closed"),
                            payload: EnumVariantPayload::Tuple(vec![type_node(4, "Int")]),
                        },
                    ),
                    node(
                        5,
                        NodeKind::EnumVariant {
                            name: ident("Locked"),
                            payload: EnumVariantPayload::Unit,
                        },
                    ),
                ],
            },
        );
        // let g: Gate = Open { level: 7 }   (struct variant)
        let open = node(
            10,
            NodeKind::RecordConstruct {
                path: type_path(&["Open"]),
                fields: vec![bock_air::AirRecordField {
                    name: ident("level"),
                    value: Some(Box::new(int_lit(11, "7"))),
                }],
                spread: None,
            },
        );
        let let_g = node(
            12,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(13, "g")),
                ty: Some(Box::new(type_node(14, "Gate"))),
                value: Box::new(open),
            },
        );
        // let c: Gate = Closed(3)   (tuple variant)
        let closed = node(
            20,
            NodeKind::Call {
                callee: Box::new(id_node(21, "Closed")),
                args: vec![AirArg {
                    label: None,
                    value: int_lit(22, "3"),
                }],
                type_args: vec![],
            },
        );
        let let_c = node(
            23,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(24, "c")),
                ty: Some(Box::new(type_node(25, "Gate"))),
                value: Box::new(closed),
            },
        );
        // let k: Gate = Locked   (unit variant)
        let let_k = node(
            30,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(31, "k")),
                ty: Some(Box::new(type_node(32, "Gate"))),
                value: Box::new(id_node(33, "Locked")),
            },
        );
        let f = ts_fn_decl(
            40,
            "main",
            vec![],
            None,
            block(41, vec![let_g, let_c, let_k], None),
        );
        let out = gen(&module(vec![], vec![gate, f]));
        assert!(
            out.contains("const g: Gate = Gate_Open(7) as Gate;"),
            "struct-variant binding must widen to the declared union, got:\n{out}"
        );
        assert!(
            out.contains("const c: Gate = Gate_Closed(3) as Gate;"),
            "tuple-variant binding must widen to the declared union, got:\n{out}"
        );
        assert!(
            out.contains("const k: Gate = Gate_Locked as Gate;"),
            "unit-variant binding must widen to the declared union, got:\n{out}"
        );
    }

    /// The widening cast is *scoped to the matching declared type*: a binding
    /// annotated with a type that is not the constructed variant's enum union
    /// (here a record `Point`, not an enum) emits unchanged — no spurious cast.
    #[test]
    fn typed_let_binding_no_widening_for_non_enum_construct() {
        let point = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Point"),
                generic_params: vec![],
                fields: vec![make_record_field("x", "Int")],
            },
        );
        let ctor = node(
            10,
            NodeKind::RecordConstruct {
                path: type_path(&["Point"]),
                fields: vec![bock_air::AirRecordField {
                    name: ident("x"),
                    value: Some(Box::new(int_lit(11, "5"))),
                }],
                spread: None,
            },
        );
        let let_p = node(
            12,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(13, "p")),
                ty: Some(Box::new(type_node(14, "Point"))),
                value: Box::new(ctor),
            },
        );
        let f = ts_fn_decl(20, "main", vec![], None, block(21, vec![let_p], None));
        let out = gen(&module(vec![], vec![point, f]));
        assert!(
            !out.contains(" as Point"),
            "a record (non-enum) binding must not get a widening cast, got:\n{out}"
        );
    }

    // ── Type aliases ────────────────────────────────────────────────────────

    #[test]
    fn type_alias_emitted() {
        let alias = node(
            1,
            NodeKind::TypeAlias {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("UserId"),
                generic_params: vec![],
                ty: Box::new(type_node(2, "String")),
                where_clause: vec![],
            },
        );
        let out = gen(&module(vec![], vec![alias]));
        assert!(out.contains("export type UserId = string;"), "got: {out}");
    }

    #[test]
    fn generic_type_alias() {
        let alias = node(
            1,
            NodeKind::TypeAlias {
                annotations: vec![],
                visibility: Visibility::Private,
                name: ident("Pair"),
                generic_params: vec![make_generic_param("A"), make_generic_param("B")],
                ty: Box::new(node(
                    2,
                    NodeKind::TypeTuple {
                        elems: vec![type_node(3, "A"), type_node(4, "B")],
                    },
                )),
                where_clause: vec![],
            },
        );
        let out = gen(&module(vec![], vec![alias]));
        assert!(out.contains("type Pair<A, B> = [A, B];"), "got: {out}");
    }

    // ── Effects → typed parameters ──────────────────────────────────────────

    #[test]
    fn effects_as_typed_params() {
        let body = block(10, vec![], None);
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("process"),
                generic_params: vec![],
                params: vec![typed_param_node(2, "data", "String")],
                return_type: None,
                effect_clause: vec![type_path(&["Log"]), type_path(&["Clock"])],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("{ log, clock }: { log: Log, clock: Clock }"),
            "got: {out}"
        );
    }

    /// Q-clock-handler-routing: inside a `with Clock` function the §18.3.1 time
    /// builtins route through the in-scope `clock` handler — `Instant.now()` →
    /// `clock.now_monotonic()`, `sleep(d)` → `clock.sleep(d)`,
    /// `start.elapsed()` → `clock.now_monotonic() - start` — NOT the inlined
    /// host primitives (`performance.now()` / `setTimeout`). The `Duration` /
    /// `Instant` annotations also render `number` (not the undefined identifiers)
    /// so the handler impl type-checks under `tsc --noEmit`.
    #[test]
    fn clock_time_ops_route_through_handler() {
        let out = gen(&module(vec![], vec![clock_timed_fn()]));
        assert!(out.contains("clock.now_monotonic()"), "got: {out}");
        assert!(out.contains("clock.sleep("), "got: {out}");
        assert!(
            !out.contains("performance.now()"),
            "host clock primitive leaked past the handler: {out}"
        );
        assert!(
            !out.contains("setTimeout"),
            "host sleep primitive leaked past the handler: {out}"
        );
    }

    /// `Duration` / `Instant` used as type annotations must render `number`
    /// (their value representation), not the undefined identifiers, so a
    /// `Clock` handler impl type-checks (Q-clock-handler-routing supporting fix).
    #[test]
    fn builtin_time_types_map_to_number() {
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("span"),
                generic_params: vec![],
                params: vec![typed_param_node(2, "d", "Duration")],
                return_type: Some(Box::new(type_node(3, "Instant"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(10, vec![], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("d: number"), "Duration annotation: {out}");
        assert!(out.contains("): number"), "Instant annotation: {out}");
        assert!(!out.contains(": Duration"), "leaked Duration type: {out}");
        assert!(!out.contains(": Instant"), "leaked Instant type: {out}");
    }

    /// Builds `fn timed() with Clock { let start = Instant.now(); sleep(
    /// Duration.millis(1)); let d = start.elapsed() }` — the `with Clock` clause
    /// puts the `clock` handler in scope so the time builtins route through it.
    fn clock_timed_fn() -> AIRNode {
        let instant_now = node(
            40,
            NodeKind::Call {
                callee: Box::new(node(
                    41,
                    NodeKind::FieldAccess {
                        object: Box::new(id_node(42, "Instant")),
                        field: ident("now"),
                    },
                )),
                args: vec![],
                type_args: vec![],
            },
        );
        let duration_millis = node(
            50,
            NodeKind::Call {
                callee: Box::new(node(
                    51,
                    NodeKind::FieldAccess {
                        object: Box::new(id_node(52, "Duration")),
                        field: ident("millis"),
                    },
                )),
                args: vec![AirArg {
                    label: None,
                    value: int_lit(53, "1"),
                }],
                type_args: vec![],
            },
        );
        let sleep_call = node(
            60,
            NodeKind::Call {
                callee: Box::new(id_node(61, "sleep")),
                args: vec![AirArg {
                    label: None,
                    value: duration_millis,
                }],
                type_args: vec![],
            },
        );
        let elapsed_call = node(
            70,
            NodeKind::MethodCall {
                receiver: Box::new(id_node(71, "start")),
                method: ident("elapsed"),
                type_args: vec![],
                args: vec![],
            },
        );
        let body = block(
            30,
            vec![
                node(
                    31,
                    NodeKind::LetBinding {
                        is_mut: false,
                        pattern: Box::new(bind_pat(32, "start")),
                        ty: None,
                        value: Box::new(instant_now),
                    },
                ),
                sleep_call,
                node(
                    33,
                    NodeKind::LetBinding {
                        is_mut: false,
                        pattern: Box::new(bind_pat(34, "d")),
                        ty: None,
                        value: Box::new(elapsed_call),
                    },
                ),
            ],
            None,
        );
        node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("timed"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![type_path(&["Clock"])],
                where_clause: vec![],
                body: Box::new(body),
            },
        )
    }

    // ── Async functions ─────────────────────────────────────────────────────

    #[test]
    fn async_function_with_types() {
        let body = block(10, vec![], Some(str_lit(11, "done")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: true,
                name: ident("fetch"),
                generic_params: vec![],
                params: vec![typed_param_node(2, "url", "String")],
                return_type: Some(Box::new(type_node(3, "String"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("export async function fetch"), "got: {out}");
        assert!(out.contains("url: string"), "got: {out}");
        // Async declared return type is wrapped in Promise<T>.
        assert!(out.contains("): Promise<string>"), "got: {out}");
    }

    #[test]
    fn async_function_without_return_type_is_promise_void() {
        let body = block(10, vec![], None);
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: true,
                name: ident("tick"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("async function tick()"), "got: {out}");
        assert!(out.contains("): Promise<void>"), "got: {out}");
    }

    #[test]
    fn sync_function_return_type_unchanged() {
        let body = block(10, vec![], Some(str_lit(11, "done")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("hello"),
                generic_params: vec![],
                params: vec![],
                return_type: Some(Box::new(type_node(2, "String"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("function hello(): string"), "got: {out}");
        assert!(!out.contains("Promise"), "got: {out}");
    }

    #[test]
    fn entry_invocation_async_main_ts() {
        let inv = TsGenerator::new().entry_invocation(true).unwrap();
        assert!(inv.contains("async () =>"));
        assert!(inv.contains("await main()"));
    }

    #[test]
    fn generate_project_async_main_wraps_entry_ts() {
        let main_fn = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: true,
                name: ident("main"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(2, vec![], None)),
            },
        );
        let m = module(vec![], vec![main_fn]);
        let gen = TsGenerator::new();
        let src_path = std::path::Path::new("src/main.bock");
        let out = gen.generate_project(&[(&m, src_path)]).unwrap();
        let src = &out.files[0].content;
        assert_eq!(out.files[0].path, std::path::PathBuf::from("main.ts"));
        assert!(src.contains("async function main()"), "got: {src}");
        assert!(
            src.contains("(async () => { await main(); })();"),
            "got: {src}"
        );
    }

    // ── Let bindings with type annotations ──────────────────────────────────

    #[test]
    fn let_binding_with_type() {
        let stmt = node(
            1,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(2, "x")),
                ty: Some(Box::new(type_node(3, "Int"))),
                value: Box::new(int_lit(4, "42")),
            },
        );
        let f = node(
            5,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(6, vec![stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("const x: number = 42;"), "got: {out}");
    }

    #[test]
    fn mutable_binding_with_type() {
        let stmt = node(
            1,
            NodeKind::LetBinding {
                is_mut: true,
                pattern: Box::new(bind_pat(2, "count")),
                ty: Some(Box::new(type_node(3, "Int"))),
                value: Box::new(int_lit(4, "0")),
            },
        );
        let f = node(
            5,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(6, vec![stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("let count: number = 0;"), "got: {out}");
    }

    // ── Type mapping ────────────────────────────────────────────────────────

    #[test]
    fn type_mapping_primitives() {
        let ctx = TsEmitCtx::new();
        assert_eq!(ctx.map_type_name("Int"), "number");
        assert_eq!(ctx.map_type_name("Float"), "number");
        assert_eq!(ctx.map_type_name("Bool"), "boolean");
        assert_eq!(ctx.map_type_name("String"), "string");
        assert_eq!(ctx.map_type_name("Void"), "void");
        assert_eq!(ctx.map_type_name("Unit"), "void");
        assert_eq!(ctx.map_type_name("List"), "Array");
        assert_eq!(ctx.map_type_name("CustomType"), "CustomType");
    }

    #[test]
    fn optional_type_emitted() {
        // `T?` must lower to the tagged `BockOption<T>` union (not `T | null`):
        // the runtime value is `{ _tag: "Some", _0: v }` / `{ _tag: "None" }`,
        // so the type has to describe that for `tsc` to accept it (Q-ts-codegen).
        let ctx = TsEmitCtx::new();
        let opt = node(
            1,
            NodeKind::TypeOptional {
                inner: Box::new(type_node(2, "String")),
            },
        );
        assert_eq!(ctx.type_to_ts(&opt), "BockOption<string>");
    }

    #[test]
    fn generic_type_args() {
        let ctx = TsEmitCtx::new();
        let list_of_int = node(
            1,
            NodeKind::TypeNamed {
                path: type_path(&["List"]),
                args: vec![type_node(2, "Int")],
            },
        );
        assert_eq!(ctx.type_to_ts(&list_of_int), "Array<number>");
    }

    #[test]
    fn function_type() {
        let ctx = TsEmitCtx::new();
        let fn_type = node(
            1,
            NodeKind::TypeFunction {
                params: vec![type_node(2, "Int"), type_node(3, "String")],
                ret: Box::new(type_node(4, "Bool")),
                effects: vec![],
            },
        );
        assert_eq!(
            ctx.type_to_ts(&fn_type),
            "(arg0: number, arg1: string) => boolean"
        );
    }

    #[test]
    fn tuple_type() {
        let ctx = TsEmitCtx::new();
        let tuple = node(
            1,
            NodeKind::TypeTuple {
                elems: vec![type_node(2, "Int"), type_node(3, "String")],
            },
        );
        assert_eq!(ctx.type_to_ts(&tuple), "[number, string]");
    }

    // ── Constants with types ────────────────────────────────────────────────

    #[test]
    fn const_with_type() {
        let c = node(
            1,
            NodeKind::ConstDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("PI"),
                ty: Box::new(type_node(2, "Float")),
                value: Box::new(node(
                    3,
                    NodeKind::Literal {
                        lit: Literal::Float("3.14159".into()),
                    },
                )),
            },
        );
        let out = gen(&module(vec![], vec![c]));
        assert!(
            out.contains("export const PI: number = 3.14159;"),
            "got: {out}"
        );
    }

    // ── Class with types ────────────────────────────────────────────────────

    #[test]
    fn class_with_typed_fields() {
        let class = node(
            1,
            NodeKind::ClassDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Point"),
                generic_params: vec![],
                base: None,
                traits: vec![],
                fields: vec![
                    make_record_field("x", "Float"),
                    make_record_field("y", "Float"),
                ],
                methods: vec![],
            },
        );
        let out = gen(&module(vec![], vec![class]));
        assert!(out.contains("export class Point"), "got: {out}");
        assert!(out.contains("x: number;"), "got: {out}");
        assert!(out.contains("y: number;"), "got: {out}");
        assert!(
            out.contains("constructor(x: number, y: number)"),
            "got: {out}"
        );
    }

    /// A `class T { a, b }` literal must construct via the class's **positional**
    /// constructor — `new T(a_value, b_value)` in *field-declaration order* — not
    /// the bare object literal the record path emits (which `tsc` rejects with
    /// `TS2339: Property '<method>' does not exist`). Q-class-codegen.
    #[test]
    fn class_literal_constructs_positionally() {
        let class = node(
            1,
            NodeKind::ClassDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Button"),
                generic_params: vec![],
                base: None,
                traits: vec![],
                fields: vec![
                    make_record_field("label", "String"),
                    make_record_field("on_click", "String"),
                ],
                methods: vec![],
            },
        );
        // Supply fields OUT of declaration order; the emitter must reorder to
        // declaration order for the positional constructor.
        let construct = node(
            10,
            NodeKind::RecordConstruct {
                path: type_path(&["Button"]),
                fields: vec![
                    AirRecordField {
                        name: ident("on_click"),
                        value: Some(Box::new(str_lit(11, "click"))),
                    },
                    AirRecordField {
                        name: ident("label"),
                        value: Some(Box::new(str_lit(12, "Submit"))),
                    },
                ],
                spread: None,
            },
        );
        let main_fn = node(
            20,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("main"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(
                    21,
                    vec![node(
                        22,
                        NodeKind::LetBinding {
                            is_mut: false,
                            pattern: Box::new(bind_pat(23, "b")),
                            ty: None,
                            value: Box::new(construct),
                        },
                    )],
                    None,
                )),
            },
        );
        let out = gen(&module(vec![], vec![class, main_fn]));
        assert!(
            out.contains(r#"new Button("Submit", "click")"#),
            "expected positional `new Button(...)` in declaration order, got:\n{out}"
        );
        assert!(
            !out.contains("{ label:"),
            "class literal must not emit a bare object literal:\n{out}"
        );
    }

    // ── Effect declarations → interfaces ────────────────────────────────────

    #[test]
    fn effect_becomes_interface() {
        let op = node(
            2,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("log"),
                generic_params: vec![],
                params: vec![typed_param_node(3, "msg", "String")],
                return_type: Some(Box::new(type_node(4, "Void"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(5, vec![], None)),
            },
        );
        let effect = node(
            1,
            NodeKind::EffectDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Logger"),
                generic_params: vec![],
                components: vec![],
                operations: vec![op],
            },
        );
        let out = gen(&module(vec![], vec![effect]));
        assert!(out.contains("interface Logger"), "got: {out}");
        assert!(out.contains("log(msg: string): void"), "got: {out}");
    }

    // ── Ownership erasure ───────────────────────────────────────────────────

    #[test]
    fn ownership_erased() {
        let move_expr = node(
            1,
            NodeKind::Move {
                expr: Box::new(id_node(2, "x")),
            },
        );
        let borrow_expr = node(
            3,
            NodeKind::Borrow {
                expr: Box::new(id_node(4, "y")),
            },
        );
        let stmts = vec![
            node(
                5,
                NodeKind::LetBinding {
                    is_mut: false,
                    pattern: Box::new(bind_pat(6, "a")),
                    ty: None,
                    value: Box::new(move_expr),
                },
            ),
            node(
                7,
                NodeKind::LetBinding {
                    is_mut: false,
                    pattern: Box::new(bind_pat(8, "b")),
                    ty: None,
                    value: Box::new(borrow_expr),
                },
            ),
        ];
        let f = node(
            9,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(10, stmts, None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("const a = x;"), "got: {out}");
        assert!(out.contains("const b = y;"), "got: {out}");
    }

    // ── String interpolation ────────────────────────────────────────────────

    #[test]
    fn string_interpolation() {
        let interp = node(
            1,
            NodeKind::Interpolation {
                parts: vec![
                    AirInterpolationPart::Literal("Hello, ".into()),
                    AirInterpolationPart::Expr(Box::new(id_node(2, "name"))),
                    AirInterpolationPart::Literal("!".into()),
                ],
            },
        );
        let stmt = node(
            3,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(4, "msg")),
                ty: None,
                value: Box::new(interp),
            },
        );
        let f = node(
            5,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(6, vec![stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        // Rendered through `__bockStr` so a user `Displayable` value dispatches
        // through its `to_string` (Q-displayable-interpolation-dispatch).
        assert!(out.contains("`Hello, ${__bockStr(name)}!`"), "got: {out}");
    }

    // ── Collections ─────────────────────────────────────────────────────────

    #[test]
    fn collections() {
        let list = node(
            1,
            NodeKind::ListLiteral {
                elems: vec![int_lit(2, "1"), int_lit(3, "2"), int_lit(4, "3")],
            },
        );
        let map = node(
            5,
            NodeKind::MapLiteral {
                entries: vec![bock_air::AirMapEntry {
                    key: str_lit(6, "a"),
                    value: int_lit(7, "1"),
                }],
            },
        );
        let set = node(
            8,
            NodeKind::SetLiteral {
                elems: vec![int_lit(9, "1"), int_lit(10, "2")],
            },
        );
        let stmts = vec![
            node(
                11,
                NodeKind::LetBinding {
                    is_mut: false,
                    pattern: Box::new(bind_pat(12, "xs")),
                    ty: None,
                    value: Box::new(list),
                },
            ),
            node(
                13,
                NodeKind::LetBinding {
                    is_mut: false,
                    pattern: Box::new(bind_pat(14, "m")),
                    ty: None,
                    value: Box::new(map),
                },
            ),
            node(
                15,
                NodeKind::LetBinding {
                    is_mut: false,
                    pattern: Box::new(bind_pat(16, "s")),
                    ty: None,
                    value: Box::new(set),
                },
            ),
        ];
        let f = node(
            17,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(18, stmts, None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("[1, 2, 3]"), "got: {out}");
        assert!(out.contains("new Map("), "got: {out}");
        assert!(out.contains("new Set("), "got: {out}");
    }

    // ── Result types with as const ──────────────────────────────────────────

    #[test]
    fn result_construct_has_as_const() {
        let ok = node(
            1,
            NodeKind::ResultConstruct {
                variant: ResultVariant::Ok,
                value: Some(Box::new(int_lit(2, "42"))),
            },
        );
        let stmt = node(
            3,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(4, "r")),
                ty: None,
                value: Box::new(ok),
            },
        );
        let f = node(
            5,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(6, vec![stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        // Reconciled on the `_0` payload key the `Result` match reads.
        assert!(
            out.contains("{ _tag: \"Ok\" as const, _0: 42 }"),
            "got: {out}"
        );
    }

    // ── Record construct ────────────────────────────────────────────────────

    #[test]
    fn record_construct() {
        let rc = node(
            1,
            NodeKind::RecordConstruct {
                path: type_path(&["Point"]),
                fields: vec![
                    AirRecordField {
                        name: ident("x"),
                        value: Some(Box::new(int_lit(2, "1"))),
                    },
                    AirRecordField {
                        name: ident("y"),
                        value: Some(Box::new(int_lit(3, "2"))),
                    },
                ],
                spread: None,
            },
        );
        let stmt = node(
            4,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(5, "p")),
                ty: None,
                value: Box::new(rc),
            },
        );
        let f = node(
            6,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("test"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(7, vec![stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(out.contains("{ x: 1, y: 2 }"), "got: {out}");
    }

    #[test]
    fn to_camel_case_converts_snake_case() {
        assert_eq!(to_camel_case("create_user"), "createUser");
        assert_eq!(to_camel_case("get_all_items"), "getAllItems");
        assert_eq!(to_camel_case("Log"), "log");
        assert_eq!(to_camel_case("createUser"), "createUser");
        assert_eq!(to_camel_case("_"), "_");
        assert_eq!(to_camel_case(""), "");
    }

    #[test]
    fn snake_case_fn_becomes_camel_case_ts() {
        let body = block(2, vec![], Some(int_lit(3, "42")));
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("create_user"),
                generic_params: vec![],
                params: vec![typed_param_node(4, "name", "String")],
                return_type: Some(Box::new(type_node(5, "Int"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("function createUser("),
            "expected camelCase function name, got: {out}"
        );
        assert!(
            out.contains("name: string"),
            "expected type annotations, got: {out}"
        );
    }

    // ── Prelude function mapping tests ──────────────────────────────────────

    /// Helper: generate TypeScript for a module with a `main` function containing a single call.
    fn gen_prelude_call(func_name: &str, arg: AIRNode) -> String {
        let call = node(
            10,
            NodeKind::Call {
                callee: Box::new(id_node(11, func_name)),
                args: vec![AirArg {
                    label: None,
                    value: arg,
                }],
                type_args: vec![],
            },
        );
        let body = block(2, vec![call], None);
        let f = node(
            1,
            NodeKind::FnDecl {
                name: ident("main"),
                params: vec![],
                return_type: None,
                body: Box::new(body),
                generic_params: vec![],
                visibility: Visibility::Private,
                annotations: vec![],
                effect_clause: vec![],
                where_clause: vec![],
                is_async: false,
            },
        );
        gen(&module(vec![], vec![f]))
    }

    /// Helper: generate TypeScript for a nullary prelude call (no args).
    fn gen_prelude_call_no_args(func_name: &str) -> String {
        let call = node(
            10,
            NodeKind::Call {
                callee: Box::new(id_node(11, func_name)),
                args: vec![],
                type_args: vec![],
            },
        );
        let body = block(2, vec![call], None);
        let f = node(
            1,
            NodeKind::FnDecl {
                name: ident("main"),
                params: vec![],
                return_type: None,
                body: Box::new(body),
                generic_params: vec![],
                visibility: Visibility::Private,
                annotations: vec![],
                effect_clause: vec![],
                where_clause: vec![],
                is_async: false,
            },
        );
        gen(&module(vec![], vec![f]))
    }

    #[test]
    fn prelude_println_maps_to_console_log() {
        let out = gen_prelude_call("println", str_lit(12, "hello"));
        assert!(
            out.contains("console.log("),
            "println should map to console.log, got: {out}"
        );
        assert!(
            !out.contains("println("),
            "should not emit bare println(, got: {out}"
        );
    }

    #[test]
    fn prelude_print_maps_to_process_stdout() {
        let out = gen_prelude_call("print", str_lit(12, "hello"));
        assert!(
            out.contains("process.stdout.write(String("),
            "print should map to process.stdout.write, got: {out}"
        );
    }

    #[test]
    fn prelude_debug_maps_to_console_debug() {
        let out = gen_prelude_call("debug", str_lit(12, "val"));
        assert!(
            out.contains("console.debug("),
            "debug should map to console.debug, got: {out}"
        );
    }

    #[test]
    fn prelude_assert_maps_to_throw() {
        let arg = node(
            12,
            NodeKind::Literal {
                lit: Literal::Bool(true),
            },
        );
        let out = gen_prelude_call("assert", arg);
        assert!(
            out.contains("if (!true) throw new Error(\"assertion failed\")"),
            "assert should map to if-throw, got: {out}"
        );
    }

    #[test]
    fn prelude_todo_maps_to_throw_not_implemented() {
        let out = gen_prelude_call_no_args("todo");
        assert!(
            out.contains("throw new Error(\"not implemented\")"),
            "todo should map to throw, got: {out}"
        );
    }

    #[test]
    fn prelude_unreachable_maps_to_throw_unreachable() {
        let out = gen_prelude_call_no_args("unreachable");
        assert!(
            out.contains("throw new Error(\"unreachable\")"),
            "unreachable should map to throw, got: {out}"
        );
    }

    #[test]
    fn non_prelude_call_passes_through() {
        let out = gen_prelude_call("my_custom_func", str_lit(12, "arg"));
        assert!(
            out.contains("myCustomFunc("),
            "non-prelude call should use camelCase, got: {out}"
        );
    }

    #[test]
    fn handling_block_passes_handlers_to_effectful_call() {
        use bock_air::AirHandlerPair;

        let effect_decl = node(
            1,
            NodeKind::EffectDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Logger"),
                generic_params: vec![],
                components: vec![],
                operations: vec![node(
                    2,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("log"),
                        generic_params: vec![],
                        params: vec![typed_param_node(3, "msg", "String")],
                        return_type: None,
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(4, vec![], None)),
                    },
                )],
            },
        );

        let inner_fn = node(
            10,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("inner"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![type_path(&["Logger"])],
                where_clause: vec![],
                body: Box::new(block(12, vec![], Some(str_lit(13, "hello")))),
            },
        );

        let call_inner = node(
            20,
            NodeKind::Call {
                callee: Box::new(id_node(21, "inner")),
                args: vec![],
                type_args: vec![],
            },
        );
        let handling = node(
            30,
            NodeKind::HandlingBlock {
                handlers: vec![AirHandlerPair {
                    effect: type_path(&["Logger"]),
                    handler: Box::new(node(
                        31,
                        NodeKind::Call {
                            callee: Box::new(id_node(32, "StdoutLogger")),
                            args: vec![],
                            type_args: vec![],
                        },
                    )),
                }],
                body: Box::new(block(33, vec![], Some(call_inner))),
            },
        );
        let main_fn = node(
            40,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("main"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(41, vec![handling], None)),
            },
        );

        let out = gen(&module(vec![], vec![effect_decl, inner_fn, main_fn]));
        // TS: inner({ logger: __logger })
        assert!(
            out.contains("inner({ logger: __logger })"),
            "handling block should pass handler to effectful call, got: {out}"
        );
        assert!(
            out.contains("const __logger: Logger = stdoutLogger()"),
            "handling block should instantiate handler with type, got: {out}"
        );
    }

    #[test]
    fn sibling_handling_blocks_do_not_share_let_scope() {
        use bock_air::AirHandlerPair;

        // Two *sibling* `handling` blocks, each `let part = …` under the SAME
        // name. Each block lowers to its own `{ … }` TS lexical scope, so both
        // must declare a fresh `const part` — neither may be rewritten into a
        // bare `part = …` assignment against the other (a name that went out of
        // scope when the first block closed; `tsc` would reject it as TS2304).
        // Regression for Q-js-handling-let-redeclaration.
        let make_handling = |id: u32, val: &str| {
            node(
                id,
                NodeKind::HandlingBlock {
                    handlers: vec![AirHandlerPair {
                        effect: type_path(&["Logger"]),
                        handler: Box::new(node(
                            id + 1,
                            NodeKind::Call {
                                callee: Box::new(id_node(id + 2, "StdoutLogger")),
                                args: vec![],
                                type_args: vec![],
                            },
                        )),
                    }],
                    body: Box::new(block(
                        id + 3,
                        vec![node(
                            id + 4,
                            NodeKind::LetBinding {
                                is_mut: false,
                                pattern: Box::new(bind_pat(id + 5, "part")),
                                ty: None,
                                value: Box::new(str_lit(id + 6, val)),
                            },
                        )],
                        Some(id_node(id + 7, "part")),
                    )),
                },
            )
        };
        let main_fn = node(
            40,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("main"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(
                    41,
                    vec![make_handling(50, "first"), make_handling(70, "second")],
                    None,
                )),
            },
        );

        let out = gen(&module(vec![], vec![main_fn]));
        assert_eq!(
            out.matches("const part = ").count(),
            2,
            "each sibling handling block should declare its own `const part`, got: {out}"
        );
        assert!(
            !out.contains("\n  part = "),
            "no sibling handling block may rewrite its `let part` into a bare \
             assignment, got: {out}"
        );
    }

    #[test]
    fn record_becomes_class() {
        let rec = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("ConsoleLogger"),
                generic_params: vec![],
                fields: vec![],
            },
        );
        let out = gen(&module(vec![], vec![rec]));
        assert!(
            out.contains("export class ConsoleLogger {}"),
            "empty record should be an empty exported class, got: {out}"
        );
    }

    #[test]
    fn impl_emits_interface_extension_for_declaration_merging() {
        use bock_air::AirHandlerPair;
        let _ = AirHandlerPair {
            effect: type_path(&["X"]),
            handler: Box::new(id_node(0, "x")),
        };

        let effect_decl = node(
            1,
            NodeKind::EffectDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Logger"),
                generic_params: vec![],
                components: vec![],
                operations: vec![node(
                    2,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("log"),
                        generic_params: vec![],
                        params: vec![typed_param_node(3, "msg", "String")],
                        return_type: None,
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(4, vec![], None)),
                    },
                )],
            },
        );

        let rec = node(
            5,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("StdLogger"),
                generic_params: vec![],
                fields: vec![],
            },
        );

        let impl_block = node(
            10,
            NodeKind::ImplBlock {
                annotations: vec![],
                trait_path: Some(type_path(&["Logger"])),
                trait_args: vec![],
                target: Box::new(type_node(11, "StdLogger")),
                generic_params: vec![],
                methods: vec![node(
                    12,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("log"),
                        generic_params: vec![],
                        // An instance method leads with `self` (as real lowering
                        // produces). A method with no `self` is an associated
                        // function, emitted as a `namespace` static, not an
                        // instance member on the merged interface.
                        params: vec![
                            untyped_param_node(15, "self"),
                            typed_param_node(13, "msg", "String"),
                        ],
                        return_type: None,
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(14, vec![], None)),
                    },
                )],
                where_clause: vec![],
            },
        );

        let out = gen(&module(vec![], vec![effect_decl, rec, impl_block]));
        assert!(
            out.contains("interface StdLogger extends Logger {"),
            "impl should emit interface extension for declaration merging, got: {out}"
        );
        // The merged interface also declares the concrete method signatures so
        // `x.log(...)` call sites resolve against the class type.
        assert!(
            out.contains("log(msg: string): void;"),
            "merged interface should declare the method signature, got: {out}"
        );
        assert!(
            out.contains("StdLogger.prototype.log"),
            "impl should attach method to prototype, got: {out}"
        );
    }

    #[test]
    fn generic_trait_impl_extends_clause_carries_type_args() {
        // GAP-A: `impl P[T] for R[T]` for a generic `trait P[T]` must emit
        // `interface R<T> extends P<T>` — the `extends` clause carries the
        // impl's trait type-args. Without them `tsc` rejects with TS2314.
        let rec = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("R"),
                generic_params: vec![make_generic_param("T")],
                fields: vec![make_record_field("v", "T")],
            },
        );
        let impl_block = node(
            10,
            NodeKind::ImplBlock {
                annotations: vec![],
                trait_path: Some(type_path(&["P"])),
                trait_args: vec![node(
                    11,
                    NodeKind::TypeNamed {
                        path: type_path(&["T"]),
                        args: vec![],
                    },
                )],
                target: Box::new(node(
                    12,
                    NodeKind::TypeNamed {
                        path: type_path(&["R"]),
                        args: vec![node(
                            13,
                            NodeKind::TypeNamed {
                                path: type_path(&["T"]),
                                args: vec![],
                            },
                        )],
                    },
                )),
                generic_params: vec![],
                methods: vec![node(
                    14,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("f"),
                        generic_params: vec![],
                        params: vec![untyped_param_node(15, "self")],
                        return_type: None,
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(16, vec![], None)),
                    },
                )],
                where_clause: vec![],
            },
        );
        let out = gen(&module(vec![], vec![rec, impl_block]));
        assert!(
            out.contains("interface R<T> extends P<T> {"),
            "generic trait impl's extends clause must carry `<T>`, got: {out}"
        );
    }

    #[test]
    fn optional_named_type_maps_to_bock_option() {
        // The spelled-out `Optional[T]` named type must lower to `BockOption<T>`
        // (matching the `T?` shorthand and the emitted tagged value), not a
        // bare `Optional<T>` (TS2304 undefined name).
        let ctx = TsEmitCtx::new();
        let opt = node(
            1,
            NodeKind::TypeNamed {
                path: type_path(&["Optional"]),
                args: vec![node(
                    2,
                    NodeKind::TypeNamed {
                        path: type_path(&["String"]),
                        args: vec![],
                    },
                )],
            },
        );
        assert_eq!(ctx.type_to_ts(&opt), "BockOption<string>");
    }

    #[test]
    fn impl_self_method_typed_and_declaration_merged() {
        // Q-ts-codegen defect 1: an inherent impl method with a bare `self`
        // receiver. The AIR keeps `self` as a real param and prepends the
        // receiver at call sites. TS must (a) type `self` as the impl target
        // (no implicit `any`) and (b) declare the method on the class via a
        // merged interface so `p.sum(p)` type-checks.
        let rec = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Point"),
                generic_params: vec![],
                fields: vec![make_record_field("x", "Int"), make_record_field("y", "Int")],
            },
        );
        let body = block(
            20,
            vec![],
            Some(node(
                21,
                NodeKind::BinaryOp {
                    op: BinOp::Add,
                    left: Box::new(node(
                        22,
                        NodeKind::FieldAccess {
                            object: Box::new(id_node(23, "self")),
                            field: ident("x"),
                        },
                    )),
                    right: Box::new(node(
                        24,
                        NodeKind::FieldAccess {
                            object: Box::new(id_node(25, "self")),
                            field: ident("y"),
                        },
                    )),
                },
            )),
        );
        let impl_block = node(
            10,
            NodeKind::ImplBlock {
                annotations: vec![],
                trait_path: None,
                trait_args: vec![],
                target: Box::new(type_node(11, "Point")),
                generic_params: vec![],
                methods: vec![node(
                    12,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("sum"),
                        generic_params: vec![],
                        params: vec![untyped_param_node(13, "self")],
                        return_type: Some(Box::new(type_node(14, "Int"))),
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(body),
                    },
                )],
                where_clause: vec![],
            },
        );
        let out = gen(&module(vec![], vec![rec, impl_block]));
        assert!(
            out.contains("interface Point {"),
            "inherent impl should emit a declaration-merging interface, got: {out}"
        );
        assert!(
            out.contains("sum(self: Point): number;"),
            "merged interface should declare the self-typed method, got: {out}"
        );
        assert!(
            out.contains("Point.prototype.sum = function(self: Point): number {"),
            "prototype function should type the self param as the target, got: {out}"
        );
    }

    /// A plain inherent `impl` method that names `Self` in its return AND its
    /// parameter type must render `Self` as the concrete target (`Counter`), not
    /// the `this` type. Each impl method emits as a free prototype function
    /// (`Counter.prototype.m = function(...): this`), and `tsc` rejects a `this`
    /// type outside a class/interface member (TS2526). Before the P4 fix
    /// `trait_self_subst` was set only for synthesized trait *default* methods;
    /// an inherent-impl `Self` lowered to `this`. Both the merged-interface
    /// signature and the prototype function must agree, or declaration merging
    /// breaks.
    #[test]
    fn self_in_plain_impl_resolves_to_target_not_this() {
        let rec = node(
            1,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Counter"),
                generic_params: vec![],
                fields: vec![make_record_field("value", "Int")],
            },
        );
        let other_param = node(
            30,
            NodeKind::Param {
                pattern: Box::new(bind_pat(31, "other")),
                ty: Some(Box::new(node(32, NodeKind::TypeSelf))),
                default: None,
            },
        );
        let impl_block = node(
            10,
            NodeKind::ImplBlock {
                annotations: vec![],
                trait_path: None,
                trait_args: vec![],
                target: Box::new(type_node(11, "Counter")),
                generic_params: vec![],
                methods: vec![node(
                    12,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("combine"),
                        generic_params: vec![],
                        params: vec![untyped_param_node(13, "self"), other_param],
                        return_type: Some(Box::new(node(14, NodeKind::TypeSelf))),
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(15, vec![], None)),
                    },
                )],
                where_clause: vec![],
            },
        );
        let out = gen(&module(vec![], vec![rec, impl_block]));
        assert!(
            !out.contains(": this"),
            "Self must not lower to the `this` type (TS2526), got: {out}"
        );
        assert!(
            out.contains("combine(self: Counter, other: Counter): Counter;"),
            "merged interface should render Self as the target in param & return, got: {out}"
        );
        assert!(
            out.contains(
                "Counter.prototype.combine = function(self: Counter, other: Counter): Counter {"
            ),
            "prototype function should render Self as the target in param & return, got: {out}"
        );
    }

    #[test]
    fn optional_runtime_prelude_and_value_type_agree() {
        // Q-ts-codegen defect 2: the Optional *type* and *value* must agree.
        // A function returning `Int?` gets `BockOption<number>`, the prelude
        // type is emitted, and `Some`/`None` lower to the matching tagged
        // objects.
        let body = block(
            20,
            vec![],
            Some(node(
                21,
                NodeKind::Call {
                    callee: Box::new(id_node(22, "Some")),
                    args: vec![AirArg {
                        label: None,
                        value: int_lit(23, "7"),
                    }],
                    type_args: vec![],
                },
            )),
        );
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("pick"),
                generic_params: vec![],
                params: vec![],
                return_type: Some(Box::new(node(
                    2,
                    NodeKind::TypeOptional {
                        inner: Box::new(type_node(3, "Int")),
                    },
                ))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("type BockOption<T> ="),
            "Optional runtime type prelude should be emitted, got: {out}"
        );
        assert!(
            out.contains("): BockOption<number> {"),
            "Optional return type should be BockOption<number>, got: {out}"
        );
        assert!(
            out.contains("{ _tag: \"Some\" as const, _0: 7 }"),
            "Some should lower to the matching tagged-object value, got: {out}"
        );
    }

    /// A `match` whose scrutinee is a call (not a bare identifier) must hoist it
    /// into a single `const __matchN = …;`. Re-emitting the call inline at the
    /// switch head and in each payload binding both double-evaluated it and
    /// defeated TS discriminated-union narrowing (TS2339 on `_0`, since
    /// `f()._0` is a fresh, un-narrowed expression). The hoisted temp is a
    /// stable reference TS narrows correctly.
    #[test]
    fn match_call_scrutinee_hoisted_to_temp() {
        // match f() { Some(x) => x; None => 0 }
        let scrutinee = node(
            10,
            NodeKind::Call {
                callee: Box::new(id_node(11, "f")),
                args: vec![],
                type_args: vec![],
            },
        );
        let some_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Some"]),
                        fields: vec![bind_pat(22, "x")],
                    },
                )),
                guard: None,
                body: Box::new(block(23, vec![], Some(id_node(24, "x")))),
            },
        );
        let none_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    31,
                    NodeKind::ConstructorPat {
                        path: type_path(&["None"]),
                        fields: vec![],
                    },
                )),
                guard: None,
                body: Box::new(block(32, vec![], Some(int_lit(33, "0")))),
            },
        );
        let match_stmt = node(
            40,
            NodeKind::Match {
                scrutinee: Box::new(scrutinee),
                arms: vec![some_arm, none_arm],
            },
        );
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("run"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(2, vec![match_stmt], None)),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("const __match1 = f();"),
            "call scrutinee should be hoisted to a temp, got: {out}"
        );
        assert!(
            out.contains("switch (__match1._tag)"),
            "switch should dispatch on the hoisted temp, got: {out}"
        );
        assert!(
            out.contains(
                r#"const x = (__match1 as Extract<typeof __match1, { _tag: "Some" }>)._0;"#
            ),
            "payload binding should read the hoisted temp through the narrowing cast, got: {out}"
        );
        // The call must not be re-emitted inline (single evaluation).
        assert!(
            !out.contains("f()._tag") && !out.contains("f()._0"),
            "call scrutinee must not be re-emitted inline, got: {out}"
        );
    }

    /// Q-match-exprpos (P4): an expression-position value `match` over a bare
    /// identifier, bound into a typed `let`. The IIFE arrow is annotated with the
    /// binding type (`(() : boolean => …)()`), and the bare scrutinee is hoisted
    /// into a temp (`const __matchN = n; switch (__matchN) …`) so the `switch`
    /// narrows the temp — not the original `n`. Without the hoist, `switch (n)`
    /// narrows `n` to the case literal inside each arm, so an arm body
    /// re-referencing `n` (`n === <other-literal>`) trips TS2367.
    #[test]
    fn expr_position_value_match_hoists_scrutinee_and_annotates_iife() {
        // let flag: Bool = match n { 0 => n; _ => n }   (in a fn returning Int)
        let zero_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::LiteralPat {
                        lit: Literal::Int("0".into()),
                    },
                )),
                guard: None,
                body: Box::new(block(22, vec![], Some(id_node(23, "n")))),
            },
        );
        let default_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(31, NodeKind::WildcardPat)),
                guard: None,
                body: Box::new(block(32, vec![], Some(id_node(33, "n")))),
            },
        );
        let m = node(
            40,
            NodeKind::Match {
                scrutinee: Box::new(id_node(41, "n")),
                arms: vec![zero_arm, default_arm],
            },
        );
        let let_flag = node(
            50,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(51, "flag")),
                ty: Some(Box::new(type_node(52, "Int"))),
                value: Box::new(m),
            },
        );
        let f = node(
            1,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("classify"),
                generic_params: vec![],
                params: vec![{
                    node(
                        2,
                        NodeKind::Param {
                            pattern: Box::new(bind_pat(3, "n")),
                            ty: Some(Box::new(type_node(4, "Int"))),
                            default: None,
                        },
                    )
                }],
                return_type: Some(Box::new(type_node(5, "Int"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(6, vec![let_flag], Some(id_node(7, "flag")))),
            },
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("(() : number => {"),
            "value-position match IIFE arrow should be annotated with the binding type, got: {out}"
        );
        assert!(
            out.contains("const __match1 = n;"),
            "bare-identifier scrutinee must be hoisted in expression position, got: {out}"
        );
        assert!(
            out.contains("switch (__match1)"),
            "switch should dispatch on the hoisted temp, not the original binding, got: {out}"
        );
    }

    // ── Generic impl interface-merge (DV12 / P1-b2) ───────────────────────────

    fn generic_param(id: u32, name: &str) -> GenericParam {
        GenericParam {
            id,
            span: span(),
            name: ident(name),
            bounds: vec![],
        }
    }

    fn named_type(id: u32, name: &str) -> AIRNode {
        node(
            id,
            NodeKind::TypeNamed {
                path: type_path(&[name]),
                args: vec![],
            },
        )
    }

    /// `record Box[T] { value: T }`.
    fn generic_box_record() -> AIRNode {
        node(
            10,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                name: ident("Box"),
                generic_params: vec![generic_param(11, "T")],
                fields: vec![bock_ast::RecordDeclField {
                    id: 12,
                    span: span(),
                    name: ident("value"),
                    ty: TypeExpr::Named {
                        id: 13,
                        span: span(),
                        path: type_path(&["T"]),
                        args: vec![],
                    },
                    default: None,
                }],
            },
        )
    }

    /// `impl Box { fn get(self) -> T { return self.value } }`.
    fn generic_box_impl() -> AIRNode {
        let self_param = node(
            20,
            NodeKind::Param {
                pattern: Box::new(bind_pat(21, "self")),
                ty: None,
                default: None,
            },
        );
        let body = block(
            22,
            vec![],
            Some(node(
                23,
                NodeKind::Return {
                    value: Some(Box::new(node(
                        24,
                        NodeKind::FieldAccess {
                            object: Box::new(id_node(25, "self")),
                            field: ident("value"),
                        },
                    ))),
                },
            )),
        );
        let method = node(
            26,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("get"),
                generic_params: vec![],
                params: vec![self_param],
                return_type: Some(Box::new(named_type(27, "T"))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        node(
            30,
            NodeKind::ImplBlock {
                annotations: vec![],
                generic_params: vec![],
                trait_path: None,
                trait_args: vec![],
                target: Box::new(named_type(31, "Box")),
                where_clause: vec![],
                methods: vec![method],
            },
        )
    }

    #[test]
    fn generic_impl_merges_onto_generic_class() {
        // `impl Box { ... }` for `record Box[T]` must declaration-merge onto the
        // generic class: `interface Box<T>`, `self: Box<T>`, and a prototype
        // function that re-declares `<T>` (it lives outside the class scope).
        let out = gen(&module(
            vec![],
            vec![generic_box_record(), generic_box_impl()],
        ));
        assert!(
            out.contains("interface Box<T> {"),
            "merged interface should carry `<T>`, got: {out}"
        );
        assert!(
            out.contains("get(self: Box<T>): T;"),
            "interface signature should type `self` as `Box<T>`, got: {out}"
        );
        assert!(
            out.contains("Box.prototype.get = function<T>(self: Box<T>): T {"),
            "prototype function should re-declare `<T>` and reference `Box.prototype`, got: {out}"
        );
    }

    #[test]
    fn method_colliding_with_field_is_disambiguated() {
        // trait Error { fn message(self) -> String }
        let trait_decl = node(
            1,
            NodeKind::TraitDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_platform: false,
                name: ident("Error"),
                generic_params: vec![],
                associated_types: vec![],
                methods: vec![node(
                    2,
                    NodeKind::FnDecl {
                        annotations: vec![],
                        visibility: Visibility::Public,
                        is_async: false,
                        name: ident("message"),
                        generic_params: vec![],
                        params: vec![typed_param_node(3, "self", "Error")],
                        return_type: Some(Box::new(node(
                            4,
                            NodeKind::TypeNamed {
                                path: type_path(&["String"]),
                                args: vec![],
                            },
                        ))),
                        effect_clause: vec![],
                        where_clause: vec![],
                        body: Box::new(block(5, vec![], None)),
                    },
                )],
            },
        );
        // record SimpleError { message: String }
        let record_decl = node(
            10,
            NodeKind::RecordDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("SimpleError"),
                generic_params: vec![],
                fields: vec![make_record_field("message", "String")],
            },
        );
        // impl Error for SimpleError { fn message(self) -> String { self.message } }
        let method = node(
            20,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("message"),
                generic_params: vec![],
                params: vec![typed_param_node(21, "self", "SimpleError")],
                return_type: Some(Box::new(node(
                    22,
                    NodeKind::TypeNamed {
                        path: type_path(&["String"]),
                        args: vec![],
                    },
                ))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(
                    23,
                    vec![],
                    Some(node(
                        24,
                        NodeKind::FieldAccess {
                            object: Box::new(id_node(25, "self")),
                            field: ident("message"),
                        },
                    )),
                )),
            },
        );
        let impl_block = node(
            30,
            NodeKind::ImplBlock {
                annotations: vec![],
                target: Box::new(node(
                    31,
                    NodeKind::TypeNamed {
                        path: type_path(&["SimpleError"]),
                        args: vec![],
                    },
                )),
                trait_path: Some(type_path(&["Error"])),
                trait_args: vec![],
                generic_params: vec![],
                where_clause: vec![],
                methods: vec![method],
            },
        );
        // fn read(e: SimpleError) -> String { e.message() }
        let read_fn = node(
            40,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                is_async: false,
                name: ident("read"),
                generic_params: vec![],
                params: vec![typed_param_node(41, "e", "SimpleError")],
                return_type: Some(Box::new(node(
                    42,
                    NodeKind::TypeNamed {
                        path: type_path(&["String"]),
                        args: vec![],
                    },
                ))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(block(
                    43,
                    vec![],
                    Some(node(
                        44,
                        NodeKind::Call {
                            callee: Box::new(node(
                                45,
                                NodeKind::FieldAccess {
                                    // The lowerer reuses the *same* receiver node
                                    // in both the field-access object and the self
                                    // arg; `desugared_self_call` keys on the shared
                                    // NodeId, so the test must too.
                                    object: Box::new(id_node(46, "e")),
                                    field: ident("message"),
                                },
                            )),
                            type_args: vec![],
                            args: vec![AirArg {
                                label: None,
                                value: id_node(46, "e"),
                            }],
                        },
                    )),
                )),
            },
        );
        let out = gen(&module(
            vec![],
            vec![trait_decl, record_decl, impl_block, read_fn],
        ));
        // The class field stays `message`.
        assert!(
            out.contains("message: string;"),
            "class field should remain `message: string`, got: {out}"
        );
        // The trait interface, merged interface, and prototype rename to
        // `messageMethod` so the field and method no longer share an identifier.
        assert!(
            out.contains("messageMethod(self: Error): string;"),
            "trait interface should declare `messageMethod`, got: {out}"
        );
        assert!(
            out.contains("messageMethod(self: SimpleError): string;"),
            "merged interface should declare `messageMethod`, got: {out}"
        );
        assert!(
            out.contains("SimpleError.prototype.messageMethod = "),
            "prototype method should be `messageMethod`, got: {out}"
        );
        // Call site renamed; field read in the body untouched.
        assert!(
            out.contains(".messageMethod(e)"),
            "call site should be `.messageMethod(e)`, got: {out}"
        );
        assert!(
            out.contains("return self.message;"),
            "method body should read the field `self.message`, got: {out}"
        );
        // No bare duplicate-identifier `message(...)` method declaration remains.
        assert!(
            !out.contains("message(self: SimpleError)"),
            "must NOT emit a `message(...)` method colliding with the field, got: {out}"
        );
    }

    /// `fn f() { let x = if (c) { 1 } else { return 0 }  x }` — value-position
    /// `if` with a diverging else. The shared value-CF hoist lowers it to a
    /// declare-then-assign temp, never `/* unsupported */` or an IIFE capturing
    /// the `return`.
    fn diverging_value_if_fn() -> AIRNode {
        let then_b = block(2, vec![], Some(int_lit(3, "1")));
        let ret = node(
            5,
            NodeKind::Return {
                value: Some(Box::new(int_lit(6, "0"))),
            },
        );
        let else_b = block(4, vec![], Some(ret));
        let if_node = node(
            1,
            NodeKind::If {
                let_pattern: None,
                condition: Box::new(id_node(7, "c")),
                then_block: Box::new(then_b),
                else_block: Some(Box::new(else_b)),
            },
        );
        let let_x = node(
            10,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(11, "x")),
                ty: None,
                value: Box::new(if_node),
            },
        );
        let body = block(20, vec![let_x], Some(id_node(21, "x")));
        let f = node(
            30,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident("f"),
                generic_params: vec![],
                params: vec![],
                return_type: None,
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        );
        module(vec![], vec![f])
    }

    #[test]
    fn diverging_value_if_hoists_to_stmt_form_no_iife() {
        let out = gen(&diverging_value_if_fn());
        assert!(
            !out.contains("/* unsupported */"),
            "diverging value-if must not emit `/* unsupported */`, got: {out}"
        );
        assert!(
            out.contains("bockCf0 = 1"),
            "value arm must assign the temp, got: {out}"
        );
        assert!(
            out.contains("return 0"),
            "diverging arm must keep its return (not wrapped in an IIFE), got: {out}"
        );
    }

    // ── ts codegen fixes (examples audit): guard-let, let-shadow, `?` ─────────

    /// `let [mut] name = value` binding node.
    fn ts_let_binding(id: u32, name: &str, is_mut: bool, value: AIRNode) -> AIRNode {
        node(
            id,
            NodeKind::LetBinding {
                is_mut,
                pattern: Box::new(node(
                    id + 1,
                    NodeKind::BindPat {
                        name: ident(name),
                        is_mut,
                    },
                )),
                ty: None,
                value: Box::new(value),
            },
        )
    }

    /// A no-arg call `callee()`.
    fn ts_call(id: u32, callee: &str) -> AIRNode {
        node(
            id,
            NodeKind::Call {
                callee: Box::new(id_node(id + 1, callee)),
                args: vec![],
                type_args: vec![],
            },
        )
    }

    /// A `fn name(params) -> ret { body }` declaration. `ret` is an optional
    /// return-type name (e.g. `Result`/`Optional`) for the `?` lowering tests.
    fn ts_fn_decl(
        id: u32,
        name: &str,
        params: Vec<AIRNode>,
        ret: Option<&str>,
        body: AIRNode,
    ) -> AIRNode {
        node(
            id,
            NodeKind::FnDecl {
                annotations: vec![],
                visibility: Visibility::Private,
                is_async: false,
                name: ident(name),
                generic_params: vec![],
                params,
                return_type: ret.map(|r| Box::new(type_node(id + 500, r))),
                effect_clause: vec![],
                where_clause: vec![],
                body: Box::new(body),
            },
        )
    }

    #[test]
    fn ts_guard_let_binds_into_enclosing_scope() {
        // fn run() { guard (let Ok(guess) = parse()) else { return }; guess }
        let guard = node(
            10,
            NodeKind::Guard {
                let_pattern: Some(Box::new(node(
                    11,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Ok"]),
                        fields: vec![bind_pat(12, "guess")],
                    },
                ))),
                condition: Box::new(ts_call(13, "parse")),
                else_block: Box::new(block(
                    15,
                    vec![node(16, NodeKind::Return { value: None })],
                    None,
                )),
            },
        );
        let body = block(2, vec![guard], Some(id_node(20, "guess")));
        let out = gen(&module(
            vec![],
            vec![ts_fn_decl(1, "run", vec![], None, body)],
        ));
        // The guard evaluates the scrutinee once into a temp, tests the Ok tag,
        // diverges in the else, then binds `guess` into the enclosing scope.
        assert!(
            out.contains("const __guard1 = parse();"),
            "guard-let must evaluate the scrutinee once into a temp, got: {out}"
        );
        assert!(
            out.contains("if (!(__guard1._tag === \"Ok\"))"),
            "guard-let must test the pattern's tag, got: {out}"
        );
        assert!(
            out.contains("const guess = __guard1._0;"),
            "guard-let must bind the payload into the enclosing scope, got: {out}"
        );
        // The binding must NOT be inside the else block (it follows the guard).
        let bind_pos = out.find("const guess = __guard1._0;").unwrap();
        let else_pos = out.find("if (!(__guard1._tag").unwrap();
        assert!(
            bind_pos > else_pos,
            "the binding must follow the guard's else, got: {out}"
        );
    }

    #[test]
    fn ts_let_shadow_rebinds_to_assignment_not_redeclaration() {
        // fn run() { let acc = 1; let acc = 2; let acc = 3 }
        let body = block(
            2,
            vec![
                ts_let_binding(10, "acc", false, int_lit(11, "1")),
                ts_let_binding(20, "acc", false, int_lit(21, "2")),
                ts_let_binding(30, "acc", false, int_lit(31, "3")),
            ],
            None,
        );
        let out = gen(&module(
            vec![],
            vec![ts_fn_decl(1, "run", vec![], None, body)],
        ));
        // First binding declares `let` (re-bound later), subsequent ones assign.
        assert!(
            out.contains("let acc = 1;"),
            "first re-bound `let` should declare with `let`, got: {out}"
        );
        assert!(
            out.contains("acc = 2;") && out.contains("acc = 3;"),
            "later bindings should be plain assignments, got: {out}"
        );
        assert!(
            !out.contains("const acc"),
            "a re-bound binding must not emit `const acc` (TS2451), got: {out}"
        );
        // Exactly one declaration of `acc` (the first `let`); no redeclaration.
        assert_eq!(
            out.matches("let acc").count(),
            1,
            "exactly one `let acc` declaration expected, got: {out}"
        );
    }

    #[test]
    fn ts_let_shadow_of_param_lowers_to_assignment() {
        // fn run(x: Int) { let x = 1; x }  — `let x` shadows the param in the
        // same TS block scope, so it must be an assignment, not a redeclaration.
        let body = block(
            2,
            vec![ts_let_binding(10, "x", false, int_lit(11, "1"))],
            Some(id_node(20, "x")),
        );
        let f = ts_fn_decl(1, "run", vec![typed_param_node(3, "x", "Int")], None, body);
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains("x = 1;") && !out.contains("const x = 1;") && !out.contains("let x = 1;"),
            "a `let` shadowing a param must lower to assignment, got: {out}"
        );
    }

    #[test]
    fn ts_propagate_let_unwraps_and_early_returns_result() {
        // fn run() -> Result { let v = f()?; v }
        let body = block(
            2,
            vec![ts_let_binding(
                10,
                "v",
                false,
                node(
                    12,
                    NodeKind::Propagate {
                        expr: Box::new(ts_call(13, "f")),
                    },
                ),
            )],
            Some(id_node(20, "v")),
        );
        let out = gen(&module(
            vec![],
            vec![ts_fn_decl(1, "run", vec![], Some("Result"), body)],
        ));
        assert!(
            out.contains("const __prop1 = f();"),
            "`?` must evaluate the inner once into a temp, got: {out}"
        );
        // Result return → single `Err` discriminant (preserves TS narrowing).
        assert!(
            out.contains("if (__prop1._tag === \"Err\") {"),
            "`?` in a Result fn must guard on the Err tag, got: {out}"
        );
        assert!(
            out.contains("return __prop1 as never;"),
            "`?` must early-return the failure container, got: {out}"
        );
        assert!(
            out.contains("const v = __prop1._0;"),
            "`?` must bind the unwrapped payload, got: {out}"
        );
    }

    #[test]
    fn ts_propagate_optional_guards_on_none_tag() {
        // fn run() -> Optional { let v = f()?; v }
        let body = block(
            2,
            vec![ts_let_binding(
                10,
                "v",
                false,
                node(
                    12,
                    NodeKind::Propagate {
                        expr: Box::new(ts_call(13, "f")),
                    },
                ),
            )],
            Some(id_node(20, "v")),
        );
        let out = gen(&module(
            vec![],
            vec![ts_fn_decl(1, "run", vec![], Some("Optional"), body)],
        ));
        assert!(
            out.contains("if (__prop1._tag === \"None\") {"),
            "`?` in an Optional fn must guard on the None tag, got: {out}"
        );
    }

    #[test]
    fn ts_propagate_bare_statement_early_returns_discards_payload() {
        // fn run() -> Result { f()?; g() }  — the `?` value is discarded but the
        // early-return guard still fires.
        let body = block(
            2,
            vec![node(
                10,
                NodeKind::Propagate {
                    expr: Box::new(ts_call(11, "f")),
                },
            )],
            Some(ts_call(20, "g")),
        );
        let out = gen(&module(
            vec![],
            vec![ts_fn_decl(1, "run", vec![], Some("Result"), body)],
        ));
        assert!(
            out.contains("const __prop1 = f();"),
            "a bare `expr?` statement must still hoist + guard, got: {out}"
        );
        assert!(
            out.contains("if (__prop1._tag === \"Err\") {")
                && out.contains("return __prop1 as never;"),
            "a bare `expr?` must early-return on failure, got: {out}"
        );
        // The discarded payload is not bound to anything.
        assert!(
            !out.contains("__prop1._0"),
            "a bare `expr?` discards the payload (no `._0` use), got: {out}"
        );
    }

    /// A list-pattern `match` (`[] / [only] / [first, ..rest]`) must route to the
    /// if-chain (the shared recogniser now flags `ListPat`), with a length test
    /// per arm and positional element / `..rest` slice binds — not the broken
    /// `switch` fast-path (duplicate `default:`, unbound `only`/`first`/`rest`).
    #[test]
    fn ts_list_pattern_match_lowers_to_ifchain_with_binds() {
        // match items { [] => "e"; [only] => only?; [first, ..rest] => first? }
        let empty_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::ListPat {
                        elems: vec![],
                        rest: None,
                    },
                )),
                guard: None,
                body: Box::new(block(22, vec![], Some(str_lit(23, "empty")))),
            },
        );
        let single_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    31,
                    NodeKind::ListPat {
                        elems: vec![bind_pat(32, "only")],
                        rest: None,
                    },
                )),
                guard: None,
                body: Box::new(block(33, vec![], Some(id_node(34, "only")))),
            },
        );
        let head_rest_arm = node(
            40,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    41,
                    NodeKind::ListPat {
                        elems: vec![bind_pat(42, "first")],
                        rest: Some(Box::new(bind_pat(43, "rest"))),
                    },
                )),
                guard: None,
                body: Box::new(block(44, vec![], Some(id_node(45, "first")))),
            },
        );
        // A trailing wildcard keeps `[first, ..rest]` a *conditional* arm so its
        // `length >= 1` test is emitted (a final arm becomes the bare `else`).
        let else_arm = node(
            46,
            NodeKind::MatchArm {
                pattern: Box::new(node(47, NodeKind::WildcardPat)),
                guard: None,
                body: Box::new(block(48, vec![], Some(str_lit(49, "other")))),
            },
        );
        let match_stmt = node(
            50,
            NodeKind::Match {
                scrutinee: Box::new(id_node(51, "items")),
                arms: vec![empty_arm, single_arm, head_rest_arm, else_arm],
            },
        );
        let f = ts_fn_decl(
            1,
            "describeList",
            vec![typed_param_node(2, "items", "Array")],
            Some("String"),
            block(3, vec![match_stmt], None),
        );
        let out = gen(&module(vec![], vec![f]));
        // No switch fast-path; arms are an if/else-if chain.
        assert!(
            !out.contains("switch ("),
            "list-pattern match must not use the switch fast-path, got: {out}"
        );
        // Empty list: exact-length test.
        assert!(
            out.contains(".length === 0"),
            "`[]` arm should test length === 0, got: {out}"
        );
        // `[only]`: length 1 and binds `only`.
        assert!(
            out.contains(".length === 1") && out.contains("const only = "),
            "`[only]` should test length === 1 and bind `only`, got: {out}"
        );
        // `[first, ..rest]`: length >= 1, binds `first` and `rest` (a slice).
        assert!(
            out.contains(".length >= 1"),
            "`[first, ..rest]` should test length >= 1, got: {out}"
        );
        assert!(
            out.contains("const first = ")
                && out.contains("const rest = ")
                && out.contains(".slice(1)"),
            "`[first, ..rest]` should bind `first` and a `rest = …slice(1)`, got: {out}"
        );
    }

    /// A range-pattern `match` (`1..10`, `100..=200`) must route to the if-chain
    /// and emit a relational bounds test (`>= lo && < hi` exclusive, `<=` for
    /// inclusive) — not a `switch` whose every arm collapses to `default:`.
    #[test]
    fn ts_range_pattern_match_lowers_to_ifchain_with_bounds() {
        // match n { 1..10 => "a"; 10..=20 => "b"; _ => "c" }
        let lo_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::RangePat {
                        lo: Box::new(int_lit(22, "1")),
                        hi: Box::new(int_lit(23, "10")),
                        inclusive: false,
                    },
                )),
                guard: None,
                body: Box::new(block(24, vec![], Some(str_lit(25, "a")))),
            },
        );
        let hi_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    31,
                    NodeKind::RangePat {
                        lo: Box::new(int_lit(32, "10")),
                        hi: Box::new(int_lit(33, "20")),
                        inclusive: true,
                    },
                )),
                guard: None,
                body: Box::new(block(34, vec![], Some(str_lit(35, "b")))),
            },
        );
        let else_arm = node(
            40,
            NodeKind::MatchArm {
                pattern: Box::new(node(41, NodeKind::WildcardPat)),
                guard: None,
                body: Box::new(block(42, vec![], Some(str_lit(43, "c")))),
            },
        );
        let match_stmt = node(
            50,
            NodeKind::Match {
                scrutinee: Box::new(id_node(51, "n")),
                arms: vec![lo_arm, hi_arm, else_arm],
            },
        );
        let f = ts_fn_decl(
            1,
            "classifyRange",
            vec![typed_param_node(2, "n", "Int")],
            Some("String"),
            block(3, vec![match_stmt], None),
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            !out.contains("switch ("),
            "range-pattern match must not use the switch fast-path, got: {out}"
        );
        // Exclusive `1..10` → `>= 1 && < 10`.
        assert!(
            out.contains(">= 1") && out.contains("< 10"),
            "`1..10` should test `>= 1 && < 10`, got: {out}"
        );
        // Inclusive `10..=20` → `>= 10 && <= 20`.
        assert!(
            out.contains(">= 10") && out.contains("<= 20"),
            "`10..=20` should test `>= 10 && <= 20`, got: {out}"
        );
    }

    /// Q-ts-match-narrowing: a constructor-pattern arm's payload binding casts
    /// the scrutinee through `Extract<typeof s, { _tag: "<variant>" }>` before
    /// reading `._N`. TS control-flow narrowing on `s._tag` reaches the arm body
    /// *only while the arm is reachable*; when an earlier statement-position
    /// `match` has every arm `return`, TS marks everything after it unreachable
    /// and stops narrowing, so a later arm's `const x = s._0` widens back to the
    /// full union payload (`T | E`) — passing it to a `T`-typed callee is TS2345.
    /// The `Extract` cast pins the binding to the matched variant's payload type
    /// regardless of reachability, so it never widens.
    #[test]
    fn ts_match_narrow_payload_binding_casts_through_extract() {
        // match r { Ok(x) => x; Err(e) => e }  over a bare identifier `r`.
        let ok_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Ok"]),
                        fields: vec![bind_pat(22, "x")],
                    },
                )),
                guard: None,
                body: Box::new(block(23, vec![], Some(id_node(24, "x")))),
            },
        );
        let err_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    31,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Err"]),
                        fields: vec![bind_pat(32, "e")],
                    },
                )),
                guard: None,
                body: Box::new(block(33, vec![], Some(id_node(34, "e")))),
            },
        );
        let match_stmt = node(
            40,
            NodeKind::Match {
                scrutinee: Box::new(id_node(41, "r")),
                arms: vec![ok_arm, err_arm],
            },
        );
        let f = ts_fn_decl(
            1,
            "run",
            vec![typed_param_node(2, "r", "Result")],
            None,
            block(3, vec![match_stmt], None),
        );
        let out = gen(&module(vec![], vec![f]));
        assert!(
            out.contains(r#"const x = (r as Extract<typeof r, { _tag: "Ok" }>)._0;"#),
            "Ok-arm payload binding should cast through Extract for narrowing, got: {out}"
        );
        assert!(
            out.contains(r#"const e = (r as Extract<typeof r, { _tag: "Err" }>)._0;"#),
            "Err-arm payload binding should cast through Extract for narrowing, got: {out}"
        );
    }

    // ── Statement-position tails must be discarded, not `return`ed ───────────
    //
    // A loop / statement-`if` / statement-`match` body's final expression is
    // discarded in Bock (these are statements, not the function's value). The
    // TS backend's `emit_block_body` had treated the tail as a function-body
    // return, so e.g. `for i in … { println(i) }` emitted
    // `for (… ) { return console.log(i); }` — the `return` aborts the function
    // on the first iteration (the loop runs once, then the fn exits). These
    // tests pin the discard behaviour for each statement context.

    /// Build a `println(<arg>)` call node.
    fn println_call(id: u32, arg: AIRNode) -> AIRNode {
        node(
            id,
            NodeKind::Call {
                callee: Box::new(id_node(id + 1, "println")),
                args: vec![AirArg {
                    label: None,
                    value: arg,
                }],
                type_args: vec![],
            },
        )
    }

    #[test]
    fn ts_for_loop_body_tail_call_is_discarded_not_returned() {
        // fn main() { for i in 1..=3 { println(i) } }
        let range = node(
            20,
            NodeKind::Range {
                lo: Box::new(int_lit(21, "1")),
                hi: Box::new(int_lit(22, "3")),
                inclusive: true,
            },
        );
        let loop_body = block(30, vec![], Some(println_call(31, id_node(33, "i"))));
        let for_loop = node(
            10,
            NodeKind::For {
                pattern: Box::new(bind_pat(11, "i")),
                iterable: Box::new(range),
                body: Box::new(loop_body),
            },
        );
        let f = ts_fn_decl(1, "main", vec![], None, block(2, vec![for_loop], None));
        let out = gen(&module(vec![], vec![f]));
        assert!(
            !out.contains("return console.log"),
            "a for-loop body's tail call must be a discarded statement, not a \
             `return` (which aborts the loop after one iteration); got:\n{out}"
        );
        assert!(
            out.contains("console.log(i);"),
            "the loop body should still emit the call as a statement; got:\n{out}"
        );
    }

    #[test]
    fn ts_while_loop_body_tail_call_is_discarded_not_returned() {
        // fn main() { while (true) { println("x") } }
        let cond = node(
            20,
            NodeKind::Literal {
                lit: Literal::Bool(true),
            },
        );
        let loop_body = block(30, vec![], Some(println_call(31, str_lit(33, "x"))));
        let while_loop = node(
            10,
            NodeKind::While {
                condition: Box::new(cond),
                body: Box::new(loop_body),
            },
        );
        let f = ts_fn_decl(1, "main", vec![], None, block(2, vec![while_loop], None));
        let out = gen(&module(vec![], vec![f]));
        assert!(
            !out.contains("return console.log"),
            "a while-loop body's tail call must be a discarded statement, not a \
             `return`; got:\n{out}"
        );
    }

    #[test]
    fn ts_statement_match_arm_tail_call_is_discarded_not_returned() {
        // fn run(r: Result) { match r { Ok(v) => println(v); Err(e) => println(e) } }
        // — the `match` is a non-tail statement (a sibling block follows), so its
        // arm tails are discarded, not returned.
        let ok_arm = node(
            20,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    21,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Ok"]),
                        fields: vec![bind_pat(22, "v")],
                    },
                )),
                guard: None,
                body: Box::new(block(23, vec![], Some(println_call(24, id_node(26, "v"))))),
            },
        );
        let err_arm = node(
            30,
            NodeKind::MatchArm {
                pattern: Box::new(node(
                    31,
                    NodeKind::ConstructorPat {
                        path: type_path(&["Err"]),
                        fields: vec![bind_pat(32, "e")],
                    },
                )),
                guard: None,
                body: Box::new(block(33, vec![], Some(println_call(34, id_node(36, "e"))))),
            },
        );
        let match_stmt = node(
            40,
            NodeKind::Match {
                scrutinee: Box::new(id_node(41, "r")),
                arms: vec![ok_arm, err_arm],
            },
        );
        // A trailing statement makes the match non-tail (statement position).
        let trailer = println_call(50, str_lit(52, "done"));
        let f = ts_fn_decl(
            1,
            "run",
            vec![typed_param_node(2, "r", "Result")],
            None,
            block(3, vec![match_stmt], Some(trailer)),
        );
        let out = gen(&module(vec![], vec![f]));
        // The arm bodies must emit the call as a bare statement (`console.log(v);`),
        // never `return console.log(v);` — a `return` inside the `switch` would
        // skip the code that follows the match.
        assert!(
            out.contains("console.log(v);") && out.contains("console.log(e);"),
            "statement-position match arms should emit their tail call as a \
             discarded statement; got:\n{out}"
        );
        assert!(
            !out.contains("return console.log(v);") && !out.contains("return console.log(e);"),
            "a statement-position match arm's tail call must be a discarded \
             statement, not a `return` (which would skip the code after the \
             match); got:\n{out}"
        );
    }

    // ── Cross-module enum-variant glob import (inventory-system) ─────────────
    //
    // `module main` does `use models.*` and references a bare enum variant
    // (`Electronics`) declared in `module models`. The variant emits as the
    // value-const `Category_Electronics`, which must be imported from
    // `./models.ts`. The shared import scan keys on the value-name but the AIR
    // references the bare source name; the shared collector
    // (`generator::implicit_esm_imports_for`) now probes the variant's bare
    // source name too, so the import is produced for js and ts alike.

    /// A glob `use <path>.*` import AIR node.
    fn import_glob(id: u32, path: &[&str]) -> AIRNode {
        node(
            id,
            NodeKind::ImportDecl {
                path: bock_ast::ModulePath {
                    segments: path.iter().map(|s| ident(s)).collect(),
                    span: span(),
                },
                items: bock_ast::ImportItems::Glob,
            },
        )
    }

    #[test]
    fn ts_glob_imported_enum_variant_is_imported() {
        // module models { public enum Category { Electronics Clothing } }
        let category_enum = node(
            40,
            NodeKind::EnumDecl {
                annotations: vec![],
                visibility: Visibility::Public,
                name: ident("Category"),
                generic_params: vec![],
                variants: vec![
                    node(
                        41,
                        NodeKind::EnumVariant {
                            name: ident("Electronics"),
                            payload: EnumVariantPayload::Unit,
                        },
                    ),
                    node(
                        42,
                        NodeKind::EnumVariant {
                            name: ident("Clothing"),
                            payload: EnumVariantPayload::Unit,
                        },
                    ),
                ],
            },
        );
        let models_mod = module_with_path(&["models"], vec![], vec![category_enum]);

        // module main { use models.*  fn main() { let c = Electronics } }
        let let_c = node(
            10,
            NodeKind::LetBinding {
                is_mut: false,
                pattern: Box::new(bind_pat(11, "c")),
                ty: None,
                value: Box::new(id_node(12, "Electronics")),
            },
        );
        let main_fn = ts_fn_decl(1, "main", vec![], None, block(2, vec![let_c], None));
        let main_mod =
            module_with_path(&["main"], vec![import_glob(5, &["models"])], vec![main_fn]);

        let gen = TsGenerator::new();
        let out = gen
            .generate_project(&[
                (&main_mod, std::path::Path::new("src/main.bock")),
                (&models_mod, std::path::Path::new("src/models.bock")),
            ])
            .unwrap();
        let main_file = out
            .files
            .iter()
            .find(|f| f.path == std::path::Path::new("main.ts"))
            .expect("main.ts emitted");
        assert!(
            main_file.content.contains("Category_Electronics")
                && main_file.content.contains(r#"from "./models.ts""#),
            "main.ts must import the glob-referenced enum variant \
             `Category_Electronics` from ./models.ts; got:\n{}",
            main_file.content
        );
        // It must be a value import (not `import type`) — the variant is a const.
        assert!(
            !main_file
                .content
                .contains("import type { Category_Electronics"),
            "the variant const must be a value import, not `import type`; got:\n{}",
            main_file.content
        );
    }
}