aver-lang 0.19.0

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
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
//! Top-level wasm module assembly.
//!
//! Walks post-pipeline IR, assembles a wasm-gc module:
//!
//! 1. **Type section**, two layers in order:
//!    - User-type slots (records, variant constructors) — assigned by
//!      `TypeRegistry::build` so emit sites already know their indices.
//!    - Function types — one per Aver fn, plus type-0 reserved for
//!      `_start: () -> ()`.
//! 2. **Function section** — one entry per Aver fn referencing the
//!    function-type idx assigned in step 1.
//! 3. **Export section** — `_start` (always at fn idx 0) plus every
//!    user fn by name.
//! 4. **Code section** — `_start` calls `main` and drops any return
//!    value; user fns get their bodies from `body::emit_fn_body`.
//!
//! Validation runs `wasmparser` with GC + tail-call features before
//! returning bytes.

use std::collections::HashMap;

use wasm_encoder::{
    CodeSection, DataCountSection, DataSection, EntityType, ExportKind, ExportSection, Function,
    FunctionSection, ImportSection, Instruction, Module, TypeSection, ValType,
};

use super::WasmGcError;
use super::body::eq_helpers::{EqHelperRegistry, EqKind};
#[allow(dead_code)]
struct Wasip2Globals {
    /// Global idx of the bump-allocator cursor backing
    /// `cabi_realloc` — Phase 1.3.1. Always allocated when this
    /// struct is constructed (i.e., wasip2 imports active). Initial
    /// value `65536` (start of page 2): page 1 stays as the
    /// transient transport buffer for `__rt_string_to_lm` /
    /// `Console.*` writes; persistent `cabi_realloc` allocations
    /// grow upward from page 2.
    bump_alloc_ptr: u32,
    /// Global idx caching the `wasi:cli/stdout.get-stdout` resource
    /// handle, lazy-initialised on first use. `None` when the program
    /// does not register `Console.print` (the only effect that calls
    /// `get-stdout`). Phase 1.2b1.5 is the consumer.
    stdout_handle: Option<u32>,
    /// Same shape, for `wasi:cli/stderr.get-stderr`. Populated when
    /// `Console.error` or `Console.warn` is registered.
    stderr_handle: Option<u32>,
    /// Same shape, for `wasi:cli/stdin.get-stdin`. Populated when
    /// `Console.readLine` is registered. The resource is program-
    /// lifetime — wasmtime cleans up at component exit, so we never
    /// emit `[resource-drop]input-stream` for it.
    stdin_handle: Option<u32>,
    /// Phase 1.5.1 — caches the first `wasi:filesystem/preopens.
    /// get-directories` entry's descriptor handle. Populated when
    /// any `Disk.*` is registered. -1 sentinel = "not yet
    /// fetched" or "no preopens"; helpers retry fetch on -1.
    disk_preopen_handle: Option<u32>,
}
use super::body::hash_helpers::{HashHelperRegistry, HashKind};
use super::body::{FnEntry, FnMap, emit_fn_body};
use super::builtins::{BuiltinName, BuiltinRegistry};
use super::effects::{EffectName, EffectRegistry};
use super::maps::MapHelperRegistry;
use super::types::{TypeRegistry, param_types, record_struct_type, return_results};
use super::wasip2_helpers::{
    CabiReallocIndices, ConsoleReadLineIndices, DecodeListStringIndices, DiskExistsIndices,
    DiskListDirIndices, DiskReadTextIndices, DiskSimplePathOpIndices, DiskWriteTextIndices,
    EnvGetLookupIndices, FormatIso8601Indices, TimeSleepIndices, emit_cabi_realloc,
    emit_console_read_line, emit_decode_list_string, emit_disk_exists, emit_disk_list_dir,
    emit_disk_read_text, emit_disk_simple_path_op, emit_disk_write_text, emit_env_get_lookup,
    emit_format_iso8601, emit_time_sleep,
};
use super::wat_helper;
use crate::types::Type as AverType;

use crate::ast::{Expr, FnDef, Stmt, TopLevel, TypeDef};

pub(super) fn emit_module_with(
    items: &[TopLevel],
    handler_name: Option<&str>,
    target: super::TargetMode,
) -> Result<Vec<u8>, WasmGcError> {
    let registry = TypeRegistry::build_with_handler(items, handler_name.is_some());

    // Lazy caller_fn name registry — populated during user-fn body
    // emit by `emit_caller_fn_idx` call sites. Threaded into every
    // `emit_fn_body` call via `EmitCtx::caller_fn_collector`. The
    // post-emit phase reads `collector.names` to materialise the
    // exported caller-fn name table (`__caller_fn_count` +
    // `__caller_fn_name`) and the matching passive data segments.
    let caller_fn_collector = std::cell::RefCell::new(super::body::CallerFnCollector::default());

    let fn_defs: Vec<&FnDef> = items
        .iter()
        .filter_map(|it| match it {
            TopLevel::FnDef(fd) => Some(fd),
            _ => None,
        })
        .collect();

    // Discover used pure-builtins. Walk every fn body looking for
    // `FnCall` whose callee is `Attr(_, "method")` and the dotted
    // form is a known builtin. Discovery happens before slot
    // allocation so the registry can reserve indices in declaration
    // order.
    let mut builtin_registry = BuiltinRegistry::new();
    let mut effect_registry = EffectRegistry::new();
    let mut eq_helpers_registry = EqHelperRegistry::new();
    let mut hash_helpers_registry = HashHelperRegistry::new();
    for fd in &fn_defs {
        discover_builtins_in_fn(
            fd,
            &mut builtin_registry,
            &mut effect_registry,
            &mut eq_helpers_registry,
            &registry,
        );
    }
    // Sweep nominal element types of every registered List / Vector
    // and key types of every registered Map. The list/vec helper
    // bodies dispatch nominal element eq/hash via `Call(__eq_<X>)`
    // (since 0.16.3); without auto-registering those types here, a
    // program that holds `List<Item>` without ever writing
    // `list == list` directly would still get a list helper body
    // that calls into an unregistered `__eq_Item`. Keys of `Map<K,_>`
    // need the same: maps.rs `emit_eq_for(K)` reaches into
    // `__eq_<X>` helpers when K is a record/sum field-of-field.
    let mut nominal_seed: Vec<String> = Vec::new();
    for canonical in &registry.list_order {
        if let Some(elem) = super::types::TypeRegistry::list_element_type(canonical) {
            nominal_seed.push(elem.trim().to_string());
        }
    }
    for canonical in &registry.vector_order {
        if let Some(elem) = super::types::TypeRegistry::vector_element_type(canonical) {
            nominal_seed.push(elem.trim().to_string());
        }
    }
    for canonical in &registry.map_order {
        if let Some((k, _v)) = super::types::parse_map_kv(canonical) {
            nominal_seed.push(k.trim().to_string());
        }
    }
    for name in &nominal_seed {
        if registry.record_fields.contains_key(name) {
            eq_helpers_registry.register_transitive(name, EqKind::Record, &registry);
            hash_helpers_registry.register_transitive(name, HashKind::Record, &registry);
        } else if registry
            .variants
            .values()
            .flat_map(|v| v.iter())
            .any(|v| &v.parent == name)
        {
            eq_helpers_registry.register_transitive(name, EqKind::Sum, &registry);
            hash_helpers_registry.register_transitive(name, HashKind::Sum, &registry);
        } else if name.starts_with("Option<") && name.ends_with('>') {
            // Carrier element of List<Option<X>> / Vector<Option<X>>
            // / Map<Option<X>, _> — list/vec eq+hash bodies dispatch
            // each element via `Call(__eq_Option<X>)` which means
            // eq_helpers must hold the slot. Same logic for the hash
            // side. Inner type registration happens transitively.
            eq_helpers_registry.register_transitive(name, EqKind::OptionEq, &registry);
            hash_helpers_registry.register_transitive(name, HashKind::OptionHash, &registry);
        } else if name.starts_with("Result<") && name.ends_with('>') {
            eq_helpers_registry.register_transitive(name, EqKind::ResultEq, &registry);
            hash_helpers_registry.register_transitive(name, HashKind::ResultHash, &registry);
        } else if name.starts_with("Tuple<") && name.ends_with('>') {
            eq_helpers_registry.register_transitive(name, EqKind::TupleEq, &registry);
            hash_helpers_registry.register_transitive(name, HashKind::TupleHash, &registry);
        }
    }
    // Mirror eq registry's transitive shape — every type registered
    // for eq dispatch also needs a hash helper, since list/vec/map
    // helpers and per-record/sum hash bodies dispatch through
    // `Call(__hash_<X>)` for non-primitive fields. Walk the eq
    // registry post-seed and register matching hash slots.
    let eq_snapshot: Vec<(String, EqKind)> = eq_helpers_registry
        .iter()
        .map(|(n, k)| (n.to_string(), k))
        .collect();
    for (name, kind) in &eq_snapshot {
        let hk = match kind {
            EqKind::Record => HashKind::Record,
            EqKind::Sum => HashKind::Sum,
            EqKind::OptionEq => HashKind::OptionHash,
            EqKind::ResultEq => HashKind::ResultHash,
            EqKind::TupleEq => HashKind::TupleHash,
        };
        hash_helpers_registry.register_transitive(name, hk, &registry);
    }
    // Eq helpers over records / sums with String fields need
    // `__wasmgc_string_eq` — force-register so the slot is allocated
    // before bodies emit.
    if eq_helpers_registry.needs_string_eq(&registry) {
        builtin_registry.register(BuiltinName::StringEq);
    }
    // `--handler X` on `--target wasm-gc` (AverBridge) — the
    // synthesised `aver_http_handle` wrapper reads `Request.*` and
    // dispatches `Response.text` / `Response.setHeader` via the JS
    // host's `aver/*` import surface, so register them up front. The
    // user handler may also touch `Http.*` / `Env.*`, which discovery
    // already picks up through `discover_builtins_in_fn`.
    //
    // `--target wasip2 --world wasi:http/proxy` uses the same
    // `handler_name` argument but takes a different codegen path:
    // the proxy wrapper decodes request fields from the host-
    // supplied `incoming-request` resource and writes the response
    // through `response-outparam.set`. No `aver/*` Request/Response
    // bridge there — pure canonical-ABI wasi:http imports.
    let proxy_mode = handler_name.is_some() && matches!(target, super::TargetMode::Wasip2);
    if handler_name.is_some() && matches!(target, super::TargetMode::AverBridge) {
        for eff in [
            EffectName::RequestMethod,
            EffectName::RequestUrl,
            EffectName::RequestQuery,
            EffectName::RequestBody,
            EffectName::RequestHeadersLoad,
            EffectName::ResponseText,
            EffectName::ResponseSetHeader,
        ] {
            effect_registry.register(eff);
        }
    }

    // List<String>/List<Char> show up as soon as the program reaches
    // for `String.split` or any List<String> literal. Their per-T
    // `contains` helper compares heads via `__wasmgc_string_eq`, so
    // force-register that builtin if any such list type is in the
    // registry — keeps slot allocation deterministic regardless of
    // whether `match` discovery already picked it up.
    if registry.list_order.iter().any(|c| c == "List<String>") {
        builtin_registry.register(BuiltinName::StringEq);
    }
    // Same trigger for `List<Record>` when the record has any
    // String field — `List.contains` over such a list does inline
    // field-by-field eq and reaches `__wasmgc_string_eq`.
    for canonical in &registry.list_order {
        if let Some(elem) = super::types::TypeRegistry::list_element_type(canonical)
            && let Some(fields) = registry.record_fields.get(elem.trim())
            && fields.iter().any(|(_, t)| t.trim() == "String")
        {
            builtin_registry.register(BuiltinName::StringEq);
            break;
        }
    }

    if fn_defs.is_empty() {
        return Err(WasmGcError::Validation(
            "module has no fn definitions".into(),
        ));
    }
    // `_start` calls `__entry__` if present (synthesised by the
    // playground / `--expr` path to wrap a user fn call with literal
    // args), otherwise `main`. Both are optional — modules that act
    // as a Worker handler (e.g. `tools/edge/handler.av`) export
    // `handler` instead and never run `_start`; when neither is
    // present, `_start` is emitted as a no-op so the module shape
    // stays valid.
    let main_idx: Option<usize> = fn_defs
        .iter()
        .position(|fd| fd.name == "__entry__")
        .or_else(|| fn_defs.iter().position(|fd| fd.name == "main"));

    let mut module = Module::new();

    // ── Type section ───────────────────────────────────────────────
    let mut types = TypeSection::new();

    // 1) User types in `TypeRegistry` order. Indices match what the
    //    registry recorded so emit sites can reference them directly.
    emit_user_types(&mut types, items, &registry)?;

    // 2) Effect import types. Imports take fn idx 0..K so their
    //    type slots come right after user types.
    //
    //    Phase 1.2b1.2 — branch on `target`. AverBridge keeps the
    //    existing `aver/*` import shape (one wasm import per
    //    registered `EffectName`). Wasip2 substitutes a parallel
    //    `Wasip2ImportRegistry` whose slots speak Component-Model
    //    canonical-ABI names (`wasi:cli/stdout.get-stdout` etc.).
    //    For Phase 1.2b1.2 the wasip2 registry is empty unless the
    //    upstream effect-check let a Console.* effect through —
    //    which only happens once Phase 1.2b1.5 graduates the trio
    //    from `pending` to `wired`.
    let mut next_type_idx = registry.user_type_count;
    let mut wasip2_imports = super::wasip2_imports::Wasip2ImportRegistry::new();
    match target {
        super::TargetMode::AverBridge => {
            effect_registry.assign_slots(&mut next_type_idx);
            for name in effect_registry.iter() {
                let p = name.params(&registry)?;
                let r = name.results(&registry)?;
                types.ty().function(p, r);
            }
        }
        super::TargetMode::Wasip2 => {
            // Populate the wasip2 registry from each effect that
            // lowers on this target. The slot set per effect is:
            //   Console.print → CliGetStdout + OutputStreamBlockingWriteAndFlush
            //   Console.error → CliGetStderr + OutputStreamBlockingWriteAndFlush
            //   Console.warn  → CliGetStderr + OutputStreamBlockingWriteAndFlush
            // (warn → stderr matches the VM and wasm-gc target's
            // default semantics — `Console.warn` writes to fd 2.)
            use super::effects::EffectName;
            use super::wasip2_imports::Wasip2ImportSlot;
            for name in effect_registry.iter() {
                if !name.lowers_on_wasip2() {
                    continue;
                }
                match name {
                    EffectName::ConsolePrint => {
                        wasip2_imports.register(Wasip2ImportSlot::CliGetStdout);
                        wasip2_imports
                            .register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                    }
                    EffectName::ConsoleError | EffectName::ConsoleWarn => {
                        wasip2_imports.register(Wasip2ImportSlot::CliGetStderr);
                        wasip2_imports
                            .register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                    }
                    EffectName::TimeUnixMs | EffectName::TimeNow => {
                        wasip2_imports.register(Wasip2ImportSlot::ClocksWallClockNow);
                    }
                    EffectName::RandomInt | EffectName::RandomFloat => {
                        wasip2_imports.register(Wasip2ImportSlot::RandomGetRandomU64);
                    }
                    EffectName::ArgsGet => {
                        wasip2_imports.register(Wasip2ImportSlot::CliEnvironmentGetArguments);
                    }
                    EffectName::EnvGet => {
                        wasip2_imports.register(Wasip2ImportSlot::CliEnvironmentGetEnvironment);
                    }
                    EffectName::ConsoleReadLine => {
                        wasip2_imports.register(Wasip2ImportSlot::CliStdinGetStdin);
                        wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
                    }
                    EffectName::TimeSleep => {
                        wasip2_imports.register(Wasip2ImportSlot::ClocksMonotonicSubscribeDuration);
                        wasip2_imports.register(Wasip2ImportSlot::IoPollPoll);
                        wasip2_imports.register(Wasip2ImportSlot::IoPollResourceDropPollable);
                    }
                    EffectName::DiskExists => {
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesStatAt);
                    }
                    EffectName::DiskReadText => {
                        // Shares the preopens cache with Disk.exists.
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesOpenAt);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesReadViaStream);
                        wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
                        wasip2_imports
                            .register(Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor);
                        wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
                    }
                    EffectName::DiskWriteText => {
                        // Shares preopens / open-at / blocking-write-and-flush
                        // / drop-descriptor with earlier phases; adds
                        // write-via-stream and the output-stream drop.
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesOpenAt);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesWriteViaStream);
                        wasip2_imports
                            .register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                        wasip2_imports
                            .register(Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor);
                        wasip2_imports
                            .register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
                    }
                    EffectName::DiskAppendText => {
                        // Same shape as writeText, but uses
                        // append-via-stream + open-flags=CREATE only.
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesOpenAt);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesAppendViaStream);
                        wasip2_imports
                            .register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                        wasip2_imports
                            .register(Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor);
                        wasip2_imports
                            .register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
                    }
                    EffectName::DiskDelete => {
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesUnlinkFileAt);
                    }
                    EffectName::DiskDeleteDir => {
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesRemoveDirectoryAt);
                    }
                    EffectName::DiskMakeDir => {
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesCreateDirectoryAt);
                    }
                    EffectName::DiskListDir => {
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemPreopensGetDirectories);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesOpenAt);
                        wasip2_imports.register(Wasip2ImportSlot::FilesystemTypesReadDirectory);
                        wasip2_imports.register(
                            Wasip2ImportSlot::FilesystemTypesDirectoryEntryStreamReadDirectoryEntry,
                        );
                        wasip2_imports
                            .register(Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor);
                        wasip2_imports.register(
                            Wasip2ImportSlot::FilesystemTypesResourceDropDirectoryEntryStream,
                        );
                    }
                    EffectName::HttpGet
                    | EffectName::HttpHead
                    | EffectName::HttpDelete
                    | EffectName::HttpPost
                    | EffectName::HttpPut
                    | EffectName::HttpPatch => {
                        // GET/HEAD/DELETE all share the same wasi:http
                        // import set — only `set-method` differentiates
                        // the verb (handled inside `__rt_http_request`
                        // based on the method_tag i32 param).
                        //
                        // 16 new + 4 reused (Step D) + Step F+G's 4 +
                        // Step J's set-method = 24 new + 4 reused.
                        // Reused: `wasi:io/poll.poll` (Time.sleep
                        // pollable-wait), `[resource-drop]pollable`,
                        // `input-stream.blocking-read` (Disk.readText
                        // / Console.readLine), input-stream drop.
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsNew);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingRequestNew);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesOutgoingRequestSetScheme);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesOutgoingRequestSetAuthority);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesOutgoingRequestSetPathWithQuery);
                        wasip2_imports.register(Wasip2ImportSlot::HttpOutgoingHandlerHandle);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesFutureIncomingResponseSubscribe);
                        wasip2_imports.register(Wasip2ImportSlot::IoPollPoll);
                        wasip2_imports.register(Wasip2ImportSlot::IoPollResourceDropPollable);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesFutureIncomingResponseGet);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingResponseStatus);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingResponseConsume);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingBodyStream);
                        wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingBodyFinish);
                        wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesResourceDropOutgoingRequest);
                        wasip2_imports.register(
                            Wasip2ImportSlot::HttpTypesResourceDropFutureIncomingResponse,
                        );
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesResourceDropIncomingResponse);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesResourceDropFutureTrailers);
                        // Step F: drop incoming-body on error paths
                        // (between consume() and finish()).
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesResourceDropIncomingBody);
                        // Step G: surface real response headers via
                        // incoming-response.headers + fields.entries +
                        // [resource-drop]fields (child of response).
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingResponseHeaders);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsEntries);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropFields);
                        // Step J: set-method for HEAD/DELETE (GET keeps
                        // constructor default — set-method call is
                        // gated by p_method != 0 inside the helper).
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesOutgoingRequestSetMethod);
                        // Step K: outgoing-body marshalling for
                        // POST/PUT/PATCH — request.body, body.write,
                        // chunked write via existing
                        // OutputStreamBlockingWriteAndFlush, body.finish,
                        // and fields.append for headers + Content-Type.
                        // outgoing-body resource-drop covers the error
                        // path between request.body() and body.finish().
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingRequestBody);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingBodyWrite);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingBodyFinish);
                        wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsAppend);
                        wasip2_imports
                            .register(Wasip2ImportSlot::HttpTypesResourceDropOutgoingBody);
                        wasip2_imports
                            .register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                        wasip2_imports
                            .register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
                    }
                    _ => {} // unreachable; `lowers_on_wasip2` enumerates the wired set.
                }
            }
            // Phase 3 — `--world wasi:http/proxy` server slots. The
            // import set is independent of any effect a user fn
            // touches: the handler wrapper itself drives every
            // wasi:http/incoming-handler / response-outparam call.
            // Reuses six slots from the client path (fields entries,
            // body stream + finish + drops, input-stream / fields /
            // outgoing-body drops, blocking-read, blocking-write-and-
            // flush, output-stream drop) and the fields/outgoing-body
            // writer chain — so `Http.get` inside the user's handler
            // doesn't double-register them.
            if proxy_mode {
                use super::wasip2_imports::Wasip2ImportSlot;
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingRequestMethod);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingRequestPathWithQuery);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingRequestHeaders);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingRequestConsume);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropIncomingRequest);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsEntries);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropFields);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingBodyStream);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesIncomingBodyFinish);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropIncomingBody);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropFutureTrailers);
                wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
                wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsNew);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesFieldsAppend);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingResponseNew);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingResponseSetStatusCode);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingResponseBody);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingBodyWrite);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesOutgoingBodyFinish);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResourceDropOutgoingBody);
                wasip2_imports.register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
                wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
                wasip2_imports.register(Wasip2ImportSlot::HttpTypesResponseOutparamSet);
            }
            wasip2_imports.assign_slots(&mut next_type_idx);
            for slot in wasip2_imports.iter() {
                let p = slot.params();
                let r = slot.results();
                types.ty().function(p, r);
            }
        }
    }

    // 3) Entry-point type. Three shapes drive different exports:
    //    - AverBridge: `_start: () -> ()` — the JS host calls
    //      `_start` for its side effects and discards any value
    //      `main` returns.
    //    - Wasip2 / CliCommand: `() -> i32` — canonical-ABI
    //      lowering of `wasi:cli/run.run`'s `result<_, _>` return
    //      (`0 == Ok`, `1 == Err`).
    //    - Wasip2 / HttpProxy (proxy_mode): `(req: i32, outparam:
    //      i32) -> ()` — `wasi:http/incoming-handler.handle`'s
    //      canonical-ABI signature. The body emit later in the
    //      code section walks the per-request choreography.
    let start_returns_i32 = matches!(target, super::TargetMode::Wasip2) && !proxy_mode;
    if proxy_mode {
        types.ty().function([ValType::I32, ValType::I32], []);
    } else if start_returns_i32 {
        types.ty().function([], [ValType::I32]);
    } else {
        types.ty().function([], []);
    }
    let start_type_idx = next_type_idx;
    next_type_idx += 1;

    // 4) One fn type per user fn. `fn_type_indices[i]` is the wasm
    //    type idx for the i-th user fn (in declaration order).
    let mut fn_type_indices: Vec<u32> = Vec::with_capacity(fn_defs.len());
    for fd in &fn_defs {
        let params = param_types(&fd.params, Some(&registry))?;
        let results = return_results(&fd.return_type, Some(&registry))?;
        types.ty().function(params, results);
        fn_type_indices.push(next_type_idx);
        next_type_idx += 1;
    }

    // 5) One fn type per registered builtin.
    //
    //    `import_count` is the wasm-fn-idx offset every other
    //    function uses, so it must reflect whichever registry
    //    drove the import-type emission above (per `target`).
    let import_count: u32 = match target {
        super::TargetMode::AverBridge => effect_registry.import_count(),
        super::TargetMode::Wasip2 => wasip2_imports.import_count(),
    };
    let mut next_builtin_fn_idx = import_count + 1 + (fn_defs.len() as u32);
    builtin_registry.assign_slots(&mut next_builtin_fn_idx, &mut next_type_idx);
    for name in builtin_registry.iter() {
        let p = name.params(&registry)?;
        let r = name.results(&registry)?;
        types.ty().function(p, r);
    }

    // 6) Map helper fn types (per-K hash + eq, per-(K,V) empty/set/get/len).
    let mut map_helpers = MapHelperRegistry::default();
    map_helpers.assign_slots(
        &registry.map_order,
        &registry,
        &mut next_builtin_fn_idx,
        &mut next_type_idx,
    )?;
    map_helpers.emit_helper_types(&mut types, &registry)?;

    // 7) List / Vector.fromList / String.split-join helpers — per-T
    //    instantiation list ops, plus singleton split/join when the
    //    surface code uses them.
    let needs_split_join = items_use_string_split_join(items);
    let mut list_helpers = super::lists::ListHelperRegistry::default();
    list_helpers.assign_slots(
        &registry.list_order,
        &registry.vector_order,
        &registry.tuple_order,
        needs_split_join,
        &registry,
        &mut next_builtin_fn_idx,
        &mut next_type_idx,
    )?;
    list_helpers.emit_helper_types(&mut types, &registry)?;

    // Per-(record/sum) `__eq_<TypeName>` helpers — slot allocation +
    // type emit. Bodies emitted after list helpers (they may call
    // `__wasmgc_string_eq` registered above).
    eq_helpers_registry.assign_slots(&mut next_builtin_fn_idx, &mut next_type_idx);
    eq_helpers_registry.emit_helper_types(&mut types);
    hash_helpers_registry.assign_slots(&mut next_builtin_fn_idx, &mut next_type_idx);
    hash_helpers_registry.emit_helper_types(&mut types);

    // 8a) `aver_http_handle` wrapper — `--handler X` synthesises a
    //     no-arg fn that reads request fields via the `Request.*`
    //     effects, builds an `HttpRequest`, calls the user's
    //     `handler`, then walks the response Map and dispatches per
    //     header before finalising via `Response.text`. Slot the type
    //     and fn idx now; the body lands at the end of the code
    //     section (after every helper) so the wrapper's fn idx is
    //     the highest in the module.
    let handler_wrapper: Option<HandlerWrapper> = if let Some(name) = handler_name
        && matches!(target, super::TargetMode::AverBridge)
    {
        let user_idx = fn_defs
            .iter()
            .position(|fd| fd.name == name)
            .ok_or_else(|| {
                WasmGcError::Validation(format!(
                    "--handler `{name}` doesn't match any fn in this module"
                ))
            })?;
        // wrapper is `() -> ()`; status/body land via Response.text.
        types.ty().function([], []);
        let wrapper_type = next_type_idx;
        next_type_idx += 1;
        // list_cons : (head: ref string, tail: ref list_String) -> ref list_String
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "handler wrapper requires String slot".into(),
            ))?;
        let list_idx = registry
            .list_type_idx("List<String>")
            .ok_or(WasmGcError::Validation(
                "handler wrapper requires List<String> slot".into(),
            ))?;
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(s_idx),
        });
        let l_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(list_idx),
        });
        types.ty().function([s_ref, l_ref], [l_ref]);
        let list_cons_type = next_type_idx;
        next_type_idx += 1;

        let wrapper_fn = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        let list_cons_fn = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(HandlerWrapper {
            user_handler_idx: user_idx,
            wrapper_type,
            wrapper_fn,
            list_cons_type,
            list_cons_fn,
        })
    } else {
        None
    };

    // 8) Host-bridge helpers + LM transport buffer — see
    //    `BridgeIndices` for the why. Emit only when the registry
    //    actually allocated a String slot.
    let bridge: Option<BridgeIndices> = if registry.string_array_type_idx.is_some() {
        let idx = emit_bridge_types(&mut types, &registry, &mut next_type_idx)?;
        let mut next_fn = || {
            let v = next_builtin_fn_idx;
            next_builtin_fn_idx += 1;
            v
        };
        Some(BridgeIndices {
            from_lm_type: idx.from_lm_type,
            to_lm_type: idx.to_lm_type,
            pages_type: idx.pages_type,
            grow_type: idx.grow_type,
            from_lm_fn: next_fn(),
            to_lm_fn: next_fn(),
            pages_fn: next_fn(),
            grow_fn: next_fn(),
        })
    } else {
        None
    };

    // 8b) `cabi_realloc` — Phase 1.3.1. The Component Model
    //     canonical ABI requires a guest export named exactly
    //     `cabi_realloc(old_ptr i32, old_size i32, align i32,
    //     new_size i32) -> i32` whenever ANY imported function
    //     returns a list, string, or other host-allocated value.
    //     Phase 1.3.1 emits it scaffolding-style on every wasip2
    //     build that has imports active; the first real consumers
    //     (Args.get / Env.get / Console.readLine / Disk.readText)
    //     come in 1.3.2+. wit-component is happy to carry an
    //     unused export — host just never calls it.
    let cabi_realloc: Option<CabiReallocIndices> =
        if matches!(target, super::TargetMode::Wasip2) && wasip2_imports.import_count() > 0 {
            types.ty().function(
                [ValType::I32, ValType::I32, ValType::I32, ValType::I32],
                [ValType::I32],
            );
            let realloc_type = next_type_idx;
            next_type_idx += 1;
            let realloc_fn = next_builtin_fn_idx;
            next_builtin_fn_idx += 1;
            Some(CabiReallocIndices {
                fn_type: realloc_type,
                fn_idx: realloc_fn,
            })
        } else {
            None
        };

    // 8c) `__rt_canonical_decode_list_string` — Phase 1.3.2.
    //     Shared helper that walks a canonical-ABI lowered
    //     `list<string>` retptr (`(list_ptr i32, list_len i32)`)
    //     into an Aver `List<String>` (cons cells of GC `(array
    //     i8)` strings). Emitted once per module when any list-
    //     returning effect that lowers via this shape is registered;
    //     today that's `Args.get` (more land in 1.3.3 / 1.5).
    //
    //     The fn signature uses the user module's `String` and
    //     `List<String>` engine-GC type indices, so allocation is
    //     gated on both being present in the registry. If the
    //     registry didn't carry them yet, the discovery walker
    //     would have failed earlier — defensive `Option` here just
    //     keeps the helper out of programs that never reach
    //     Args.get.
    let decode_list_string: Option<DecodeListStringIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::CliEnvironmentGetArguments)
            .is_some()
        && let (Some(string_idx), Some(list_string_idx)) = (
            registry.string_array_type_idx,
            registry.list_type_idx("List<String>"),
        ) {
        let list_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(list_string_idx),
        });
        types.ty().function([ValType::I32], [list_ref]);
        let decoder_type = next_type_idx;
        next_type_idx += 1;
        let decoder_fn = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DecodeListStringIndices {
            fn_type: decoder_type,
            fn_idx: decoder_fn,
            string_type_idx: string_idx,
            list_string_type_idx: list_string_idx,
        })
    } else {
        None
    };

    // 8d) `__rt_canonical_env_lookup` — Phase 1.3.3.
    //     Linear-search lookup over the canonical-ABI lowered
    //     `list<tuple<string, string>>` retptr that
    //     `wasi:cli/environment.get-environment` writes to.
    //     Signature: `(retptr i32, key_ptr i32, key_len i32) ->
    //     ref null $string`. Returns the matching value as a
    //     fresh GC `(array i8)`, or an empty array when no key
    //     matches — preserves Aver's `Env.get(name) -> String`
    //     no-Option semantics.
    // Phase 1.4b — `__rt_format_iso8601(secs i64, nanos i32) ->
    // Phase 1.3.4 — `__rt_console_read_line() ->
    // Result<String, String>` body. Caches `wasi:cli/stdin.get-stdin`
    // in a wasm global (lazy-init via `-1` sentinel) and loops
    // 1-byte `wasi:io/streams.[method]input-stream.blocking-read`
    // calls until `\n` or EOF, accumulating into a `cabi_realloc`-
    // owned buffer that doubles on overflow. Returns
    // `Result.Ok(line)` on success (including partial-line-then-EOF
    // — Unix convention) and `Result.Err("EOF")` only when the
    // first read produces zero bytes.
    let console_read_line: Option<ConsoleReadLineIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::CliStdinGetStdin)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(result_idx) = registry.result_type_idx("Result<String,String>")
    {
        let res_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        types.ty().function([], [res_ref]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(ConsoleReadLineIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_string_string_type_idx: result_idx,
        })
    } else {
        None
    };

    // Phase 1.4c — `__rt_time_sleep(ms i64)` helper. Subscribes
    // for a `ms * 1_000_000` nanosecond duration on the monotonic
    // clock, polls the resulting pollable to completion, drops the
    // pollable. Pollable is per-call (single-use), so the
    // `[resource-drop]` here is mandatory — without it every call
    // would leak a host-side handle. Allocation order matches the
    // funcs/codes append order below; getting these out of sync
    // mis-routes call-site `Call(idx)` to the wrong helper body.
    let time_sleep: Option<TimeSleepIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::ClocksMonotonicSubscribeDuration,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollPoll)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable)
            .is_some()
    {
        types.ty().function([ValType::I64], []);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(TimeSleepIndices { fn_type, fn_idx })
    } else {
        None
    };

    // Phase 1.5.1 — `__rt_disk_exists(path: ref string) -> i32`
    // helper. Lazy-fetches the first preopen descriptor (cached
    // in `disk_preopen_handle` global), marshals the path bytes
    // through `__rt_string_to_lm`, calls
    // `wasi:filesystem/types.[method]descriptor.stat-at` and
    // returns `1` for an `Ok` result, `0` for `Err` (and `0`
    // when no preopens are configured at all). The
    // `descriptor-stat` payload itself is left untouched.
    let disk_exists: Option<DiskExistsIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesStatAt)
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
    {
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref], [ValType::I32]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DiskExistsIndices { fn_type, fn_idx })
    } else {
        None
    };

    // Phase 1.5.2 — `__rt_disk_read_text(path: ref string) ->
    // ref null $result_string_string`. Lazy-fetches the preopen,
    // calls `open-at` to obtain a per-call file descriptor,
    // calls `read-via-stream` to obtain a per-call input-stream,
    // loops `blocking-read` (chunk size 65536) until EOF, copies
    // the accumulated bytes into a fresh GC `(array i8)` for the
    // `Result.Ok` payload, then drops both the input-stream and
    // file descriptor. Any failure short-circuits to a generic
    // `Result.Err("…")` (open failure / stream failure / read
    // failure are all categorised by the operation that produced
    // the error code, ignoring the specific `error-code` enum).
    let disk_read_text: Option<DiskReadTextIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesReadViaStream,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
            )
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(result_idx) = registry.result_type_idx("Result<String,String>")
    {
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref], [r_ref]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DiskReadTextIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_string_string_type_idx: result_idx,
        })
    } else {
        None
    };

    // Phase 1.5.3 — `__rt_disk_write_text(path: ref string,
    // content: ref string) -> ref null $result_unit_string`.
    // Mirrors `__rt_disk_read_text`'s skeleton (preopens cache +
    // open-at + via-stream + blocking-* + drops) flipped to the
    // write side: `open-flags = create | truncate` (`5`),
    // `descriptor-flags = WRITE` (`2`), `write-via-stream` for
    // the output-stream, `blocking-write-and-flush` for the
    // bytes themselves. Failure at any step short-circuits to
    // `Result.Err("...")`.
    let disk_write_text: Option<DiskWriteTextIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesWriteViaStream,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
            )
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(result_idx) = registry.result_type_idx("Result<Unit,String>")
    {
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref, s_ref], [r_ref]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DiskWriteTextIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_unit_string_type_idx: result_idx,
        })
    } else {
        None
    };

    // Phase 1.5.5 — `__rt_disk_append_text(path, content) ->
    // Result<Unit, String>`. Reuses the same body emitter as
    // `__rt_disk_write_text` flipped to append mode (open-flags
    // = CREATE only, append-via-stream instead of
    // write-via-stream).
    let disk_append_text: Option<DiskWriteTextIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesAppendViaStream,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
            )
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(result_idx) = registry.result_type_idx("Result<Unit,String>")
    {
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref, s_ref], [r_ref]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DiskWriteTextIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_unit_string_type_idx: result_idx,
        })
    } else {
        None
    };

    // Phase 1.5.4 — `Disk.delete`, `Disk.deleteDir`, `Disk.makeDir`
    // share a generic helper: lazy-init preopen, marshal path,
    // call the matching `<op>-at`, return `Result.Ok(Unit)` on Ok-tag
    // / `Result.Err(<msg>)` on Err. Each Aver effect gets its own
    // wasm fn (different op fn idx + different err message), so
    // separate Indices structs per effect — but the body emitter is
    // a single helper parametrised by the wasi op + message.
    let alloc_path_op = |types: &mut wasm_encoder::TypeSection,
                         next_type_idx: &mut u32,
                         next_builtin_fn_idx: &mut u32,
                         op_slot: super::wasip2_imports::Wasip2ImportSlot|
     -> Option<DiskSimplePathOpIndices> {
        if cabi_realloc.is_none()
            || wasip2_imports
                .lookup_wasm_fn_idx(
                    super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
                )
                .is_none()
            || wasip2_imports.lookup_wasm_fn_idx(op_slot).is_none()
        {
            return None;
        }
        let string_idx = registry.string_array_type_idx?;
        let result_idx = registry.result_type_idx("Result<Unit,String>")?;
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref], [r_ref]);
        let fn_type = *next_type_idx;
        *next_type_idx += 1;
        let fn_idx = *next_builtin_fn_idx;
        *next_builtin_fn_idx += 1;
        Some(DiskSimplePathOpIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_unit_string_type_idx: result_idx,
        })
    };
    let disk_delete = alloc_path_op(
        &mut types,
        &mut next_type_idx,
        &mut next_builtin_fn_idx,
        super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesUnlinkFileAt,
    );
    let disk_delete_dir = alloc_path_op(
        &mut types,
        &mut next_type_idx,
        &mut next_builtin_fn_idx,
        super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesRemoveDirectoryAt,
    );
    let disk_make_dir = alloc_path_op(
        &mut types,
        &mut next_type_idx,
        &mut next_builtin_fn_idx,
        super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesCreateDirectoryAt,
    );

    // Phase 1.5.6 — `__rt_disk_list_dir(path: ref string) ->
    // ref null $result_list_string_string`. Opens path as a
    // directory, drives `read-directory-entry` until None,
    // accumulates each entry's name into a cons-built
    // `List<String>`. Order is filesystem-dependent (matches
    // POSIX `readdir` which doesn't promise any order either);
    // call sites that need a sorted list call `List.sort` after.
    let disk_list_dir: Option<DiskListDirIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesReadDirectory)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesDirectoryEntryStreamReadDirectoryEntry)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDirectoryEntryStream)
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(list_string_idx) = registry.list_type_idx("List<String>")
        && let Some(result_idx) = registry.result_type_idx("Result<List<String>,String>")
    {
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        types.ty().function([s_ref], [r_ref]);
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(DiskListDirIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            list_string_type_idx: list_string_idx,
            result_list_string_string_type_idx: result_idx,
        })
    } else {
        None
    };

    // Phase 2.0 — `__rt_http_get(url: ref string) -> ref Result<
    // HttpResponse, String>`. Owns the entire wasi:http pipeline
    // (URL parse + fields/request constructors + setters + handle
    // + poll + future.get + status + consume + body.stream + drain
    // + per-call drops + HttpResponse build). All 16 new wasi:http
    // slots and 4 reused (poll/drop-pollable/blocking-read/drop-
    // input-stream) must be present, plus String / Result / Http
    // Response / Map<String, List<String>> type slots.
    let http_get: Option<super::wasip2_http::HttpGetIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsNew)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestNew)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetScheme)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetAuthority)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetPathWithQuery)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpOutgoingHandlerHandle)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesFutureIncomingResponseSubscribe)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollPoll)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesFutureIncomingResponseGet)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseStatus)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseConsume)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingBodyStream)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingBodyFinish)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropOutgoingRequest)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFutureIncomingResponse)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropIncomingResponse)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFutureTrailers)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropIncomingBody)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseHeaders)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsEntries)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFields)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetMethod)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestBody)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingBodyWrite)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingBodyFinish)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsAppend)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropOutgoingBody)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush)
            .is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream)
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(result_idx) = registry.result_type_idx("Result<HttpResponse,String>")
        && let Some(resp_idx) = registry.record_type_idx("HttpResponse")
        && let Some(map_slots) = registry.map_slots("Map<String,List<String>>")
        && let Some(list_string_idx) = registry.list_type_idx("List<String>")
        && let Some(opt_list_string_idx) = registry.option_type_idx("Option<List<String>>")
    {
        let r_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(result_idx),
        });
        let s_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        // Step J + K: 5 params total — method tag, url, content-
        // type, body, user headers map. The trailing three are
        // ignored for body-less methods (GET/HEAD/DELETE); the
        // dispatcher pushes empty values in those cases.
        let map_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(map_slots.map),
        });
        types.ty().function(
            [ValType::I32, s_ref, s_ref, s_ref, map_ref],
            [r_ref],
        );
        let fn_type = next_type_idx;
        next_type_idx += 1;
        let fn_idx = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(super::wasip2_http::HttpGetIndices {
            fn_type,
            fn_idx,
            string_type_idx: string_idx,
            result_http_response_string_type_idx: result_idx,
            http_response_type_idx: resp_idx,
            headers_keys_array_type_idx: map_slots.keys_array,
            headers_values_array_type_idx: map_slots.values_array,
            headers_map_type_idx: map_slots.map,
            list_string_type_idx: list_string_idx,
            option_list_string_type_idx: opt_list_string_idx,
        })
    } else {
        None
    };

    let env_get_lookup: Option<EnvGetLookupIndices> = if cabi_realloc.is_some()
        && wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::CliEnvironmentGetEnvironment,
            )
            .is_some()
        && let Some(string_idx) = registry.string_array_type_idx
        && let Some(option_string_idx) = registry.option_type_idx("Option<String>")
    {
        let opt_ref = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(option_string_idx),
        });
        types
            .ty()
            .function([ValType::I32, ValType::I32, ValType::I32], [opt_ref]);
        let lookup_type = next_type_idx;
        next_type_idx += 1;
        let lookup_fn = next_builtin_fn_idx;
        next_builtin_fn_idx += 1;
        Some(EnvGetLookupIndices {
            fn_type: lookup_type,
            fn_idx: lookup_fn,
            string_type_idx: string_idx,
            option_string_type_idx: option_string_idx,
        })
    } else {
        None
    };

    // Phase 1.4b — `__rt_format_iso8601(secs i64, nanos i32) ->
    // ref null $string`. Pure-compute helper that turns the
    // datetime returned by `wasi:clocks/wall-clock.now` into the
    // RFC3339-like string Aver's `Time.now() -> String` exposes.
    // Materialises a fresh 24-byte `(array i8)` and writes
    // `YYYY-MM-DDTHH:MM:SS.mmmZ` into it. The civil_from_days
    // arithmetic mirrors `aver-rt::format_utc_rfc3339_like`.
    // Allocated whenever wasip2 + the clocks slot are wired —
    // `wasm-opt -Oz` strips this when only `Time.unixMs` reaches
    // the import (i.e. no source-level `Time.now`). Allocation
    // position is the LAST helper before factory exports because
    // the funcs/codes append phase below emits its entry last.
    let format_iso8601: Option<FormatIso8601Indices> =
        if matches!(target, super::TargetMode::Wasip2)
            && wasip2_imports
                .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::ClocksWallClockNow)
                .is_some()
            && let Some(string_idx) = registry.string_array_type_idx
        {
            let s_ref = ValType::Ref(wasm_encoder::RefType {
                nullable: true,
                heap_type: wasm_encoder::HeapType::Concrete(string_idx),
            });
            types.ty().function([ValType::I64, ValType::I32], [s_ref]);
            let fn_type = next_type_idx;
            next_type_idx += 1;
            let fn_idx = next_builtin_fn_idx;
            next_builtin_fn_idx += 1;
            Some(FormatIso8601Indices {
                fn_type,
                fn_idx,
                string_type_idx: string_idx,
            })
        } else {
            None
        };

    // 9) Wasm-owned value factories. JS host can't construct wasm-gc
    //    structs/variants directly, so any effect import that returns
    //    a structured ref needs per-type constructor helpers exported
    //    from the binary. Same per-instantiation pattern as
    //    `__rt_string_from_lm` / per-Map probes — host calls the
    //    factory, factory does `struct.new`, returns the ref. Emitted
    //    only when the corresponding effect is registered (DCE'd
    //    otherwise by `wasm-opt -Oz`).
    let factory_exports = allocate_factory_exports(
        &mut types,
        &mut next_type_idx,
        &mut next_builtin_fn_idx,
        &registry,
        &effect_registry,
    )?;

    // 10) Caller-fn name table exports. `__caller_fn_count() -> i32`
    //     and `__caller_fn_name(i32) -> ref null $string`. Host walks
    //     `0..count` once at instantiation, decodes each ref via the
    //     LM bridge, caches in a `Vec<String>`. Per effect call: `i32`
    //     idx flows through `params.last()` → vector index lookup,
    //     no LM round-trip on the hot path.
    //
    //     Allocated only when the program has the String slot (i.e.
    //     any fn def, since `needs_string` forces the slot whenever
    //     `has_fn_defs`). Programs without fns never emit caller_fn
    //     anywhere so the exports would be unused.
    let caller_fn_table_types: Option<(u32, u32)> =
        if let Some(string_type_idx) = registry.string_array_type_idx {
            // count: () -> i32
            types.ty().function([], [ValType::I32]);
            let count_type_idx = next_type_idx;
            next_type_idx += 1;
            // name: (i32) -> (ref null $string)
            let string_ref_ty = ValType::Ref(wasm_encoder::RefType {
                nullable: true,
                heap_type: wasm_encoder::HeapType::Concrete(string_type_idx),
            });
            types.ty().function([ValType::I32], [string_ref_ty]);
            let name_type_idx = next_type_idx;
            // Last type allocation in this fn — `next_type_idx`
            // increment dropped to silence `unused_assignments`.
            Some((count_type_idx, name_type_idx))
        } else {
            None
        };

    module.section(&types);

    // ── Import section ─────────────────────────────────────────────
    //
    // Same per-target branch as the import-type emission above.
    // AverBridge writes `(import "aver" "<name>" ...)` per
    // registered effect; Wasip2 writes the canonical-ABI form
    // (`(import "wasi:cli/stdout@0.2.4" "get-stdout" ...)` etc.).
    match target {
        super::TargetMode::AverBridge => {
            if effect_registry.import_count() > 0 {
                let mut imports = ImportSection::new();
                for name in effect_registry.iter() {
                    let (module_, field) = name.import_pair();
                    let type_idx = effect_registry
                        .lookup_wasm_type_idx(name)
                        .expect("just-assigned effect type idx");
                    imports.import(module_, field, EntityType::Function(type_idx));
                }
                module.section(&imports);
            }
        }
        super::TargetMode::Wasip2 => {
            if wasip2_imports.import_count() > 0 {
                let mut imports = ImportSection::new();
                for slot in wasip2_imports.iter() {
                    let (module_, field) = slot.module_field_pair();
                    let type_idx = wasip2_imports
                        .lookup_wasm_type_idx(slot)
                        .expect("just-assigned wasip2 import type idx");
                    imports.import(module_, field, EntityType::Function(type_idx));
                }
                module.section(&imports);
            }
        }
    }

    // ── Function section ───────────────────────────────────────────
    let mut funcs = FunctionSection::new();
    funcs.function(start_type_idx); // _start at wasm fn idx K
    for type_idx in &fn_type_indices {
        funcs.function(*type_idx);
    }
    for name in builtin_registry.iter() {
        let type_idx = builtin_registry
            .lookup_wasm_type_idx(name)
            .expect("just-assigned builtin type idx");
        funcs.function(type_idx);
    }
    map_helpers.emit_function_section(&mut funcs);
    list_helpers.emit_function_section(&mut funcs);
    // Eq helpers — one fn entry per registered `__eq_<TypeName>` slot.
    for (name, _kind) in eq_helpers_registry.iter() {
        let t_idx = eq_helpers_registry
            .lookup_type_idx(name)
            .expect("registered eq helper has type idx after assign_slots");
        funcs.function(t_idx);
    }
    // Hash helpers — same shape (one entry per registered slot).
    for (name, _kind) in hash_helpers_registry.iter() {
        let t_idx = hash_helpers_registry
            .lookup_type_idx(name)
            .expect("registered hash helper has type idx after assign_slots");
        funcs.function(t_idx);
    }
    if let Some(hw) = &handler_wrapper {
        funcs.function(hw.wrapper_type);
        funcs.function(hw.list_cons_type);
    }
    if let Some(b) = &bridge {
        funcs.function(b.from_lm_type);
        funcs.function(b.to_lm_type);
        funcs.function(b.pages_type);
        funcs.function(b.grow_type);
    }
    if let Some(c) = &cabi_realloc {
        funcs.function(c.fn_type);
    }
    if let Some(d) = &decode_list_string {
        funcs.function(d.fn_type);
    }
    if let Some(c) = &console_read_line {
        funcs.function(c.fn_type);
    }
    if let Some(t) = &time_sleep {
        funcs.function(t.fn_type);
    }
    if let Some(d) = &disk_exists {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_read_text {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_write_text {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_append_text {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_delete {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_delete_dir {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_make_dir {
        funcs.function(d.fn_type);
    }
    if let Some(d) = &disk_list_dir {
        funcs.function(d.fn_type);
    }
    if let Some(h) = &http_get {
        funcs.function(h.fn_type);
    }
    if let Some(e) = &env_get_lookup {
        funcs.function(e.fn_type);
    }
    if let Some(fmt) = &format_iso8601 {
        funcs.function(fmt.fn_type);
    }
    factory_exports.emit_function_entries(&mut funcs);
    // Caller-fn name table fns — fixed-shape entries (count + name),
    // their bodies land at the very end of the code section once
    // `caller_fn_collector` has all names. Idxs are recorded so
    // `module.section(&exports)` can wire them up without re-deriving
    // the position.
    let caller_fn_table_fns: Option<(u32, u32)> = caller_fn_table_types.map(|(c_ty, n_ty)| {
        let count_fn_idx = import_count + funcs.len();
        funcs.function(c_ty);
        let name_fn_idx = import_count + funcs.len();
        funcs.function(n_ty);
        (count_fn_idx, name_fn_idx)
    });
    module.section(&funcs);

    // ── Memory section ─────────────────────────────────────────────
    //
    // 1 page initial, 2048 max (128 MiB ceiling — matches Cloudflare
    // Workers' per-request memory limit). The bridge helpers grow
    // on demand: `__rt_string_to_lm` checks if it can fit the
    // outgoing array and calls `memory.grow` if not.
    //
    // Two reasons to emit memory:
    // - AverBridge with a JS-host bridge: `__rt_string_to_lm` /
    //   `__rt_string_from_lm` need transport space for the
    //   `(array i8)` ↔ `(ptr, len)` boundary the JS host reads.
    // - Wasip2 with any registered canonical-ABI import: same LM
    //   transport, same helpers internally — `wasi:io/streams.
    //   [method]output-stream.blocking-write-and-flush` takes a
    //   `(ptr, len)` lowered from a `list<u8>`, plus a 12-byte
    //   retptr scratch area for the host-written
    //   `result<_, stream-error>`. The helpers are NOT exported
    //   on wasip2 (no JS host calls them); they exist purely for
    //   internal wasm-side glue at effect call sites.
    let need_memory_for_wasip2 =
        matches!(target, super::TargetMode::Wasip2) && wasip2_imports.import_count() > 0;
    if bridge.is_some() || need_memory_for_wasip2 {
        let mut memories = wasm_encoder::MemorySection::new();
        memories.memory(wasm_encoder::MemoryType {
            minimum: 1,
            maximum: Some(2048),
            memory64: false,
            shared: false,
            page_size_log2: None,
        });
        module.section(&memories);
    }

    // ── Globals section (wasip2 resource-handle caches) ────────────
    //
    // On `TargetMode::Wasip2`, when `Console.print` / `error` / `warn`
    // is registered, the call-site glue caches the host-supplied
    // `output-stream` resource handle in a wasm global. -1 is the
    // sentinel for "not yet initialised"; the first call evaluates
    // the matching `wasi:cli/{stdout,stderr}.get-stdout/stderr`
    // import and stores the result. Per-call branch is one
    // `i32.eq` + `if` — negligible against the syscall it guards.
    //
    // Globals are emitted only when at least one of stdout/stderr
    // is actually used (`OutputStreamBlockingWriteAndFlush` registered
    // implies at least one of `CliGetStdout` / `CliGetStderr` does
    // too). Empty Aver programs hit neither and skip the section
    // entirely — no semantic change vs. Phase 1.2b1.3.
    let wasip2_globals: Option<Wasip2Globals> =
        if matches!(target, super::TargetMode::Wasip2) && wasip2_imports.import_count() > 0 {
            let mut globals = wasm_encoder::GlobalSection::new();
            let mut next_global_idx: u32 = 0;
            // Global 0 — bump-alloc cursor for `cabi_realloc`. Initial
            // value `65536` (= page 2 base). Page 1 stays reserved for
            // the `__rt_string_to_lm` transient buffer that
            // `Console.*` writes use; persistent `cabi_realloc` heap
            // grows upward from page 2 with `memory.grow` on overflow.
            // Allocated unconditionally on the wasip2 path so the
            // cabi_realloc helper has a stable global idx to read /
            // write — Phase 1.3.1 onwards consumes it; earlier phases
            // tolerate the unused global (12 bytes of section overhead).
            globals.global(
                wasm_encoder::GlobalType {
                    val_type: ValType::I32,
                    mutable: true,
                    shared: false,
                },
                &wasm_encoder::ConstExpr::i32_const(65536),
            );
            let bump_alloc_ptr = next_global_idx;
            next_global_idx += 1;
            let stdout_handle = if wasip2_imports
                .lookup_wasm_type_idx(super::wasip2_imports::Wasip2ImportSlot::CliGetStdout)
                .is_some()
            {
                globals.global(
                    wasm_encoder::GlobalType {
                        val_type: ValType::I32,
                        mutable: true,
                        shared: false,
                    },
                    &wasm_encoder::ConstExpr::i32_const(-1),
                );
                let idx = next_global_idx;
                next_global_idx += 1;
                Some(idx)
            } else {
                None
            };
            let stderr_handle = if wasip2_imports
                .lookup_wasm_type_idx(super::wasip2_imports::Wasip2ImportSlot::CliGetStderr)
                .is_some()
            {
                globals.global(
                    wasm_encoder::GlobalType {
                        val_type: ValType::I32,
                        mutable: true,
                        shared: false,
                    },
                    &wasm_encoder::ConstExpr::i32_const(-1),
                );
                let idx = next_global_idx;
                next_global_idx += 1;
                Some(idx)
            } else {
                None
            };
            // Phase 1.3.4 — stdin handle cache global. Same lazy-init
            // pattern as stdout/stderr: starts as -1 sentinel, every
            // `Console.readLine` call site checks the global and runs
            // `wasi:cli/stdin.get-stdin` once on first read. The
            // resource is program-lifetime (wasmtime cleans up at
            // component exit) so we never emit `[resource-drop]`.
            let stdin_handle = if wasip2_imports
                .lookup_wasm_type_idx(super::wasip2_imports::Wasip2ImportSlot::CliStdinGetStdin)
                .is_some()
            {
                globals.global(
                    wasm_encoder::GlobalType {
                        val_type: ValType::I32,
                        mutable: true,
                        shared: false,
                    },
                    &wasm_encoder::ConstExpr::i32_const(-1),
                );
                let idx = next_global_idx;
                next_global_idx += 1;
                Some(idx)
            } else {
                None
            };
            // Phase 1.5.1 — disk preopen descriptor cache. -1 sentinel
            // for "not yet fetched". On first `Disk.*` call the helper
            // calls `wasi:filesystem/preopens.get-directories`, takes
            // the first entry's descriptor handle, and caches it here.
            // Program-lifetime — no `[resource-drop]descriptor` for
            // the preopen, wasmtime cleans up at component exit.
            let disk_preopen_handle = if wasip2_imports
                .lookup_wasm_type_idx(
                    super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
                )
                .is_some()
            {
                globals.global(
                    wasm_encoder::GlobalType {
                        val_type: ValType::I32,
                        mutable: true,
                        shared: false,
                    },
                    &wasm_encoder::ConstExpr::i32_const(-1),
                );
                let idx = next_global_idx;
                next_global_idx += 1;
                Some(idx)
            } else {
                None
            };
            let _ = next_global_idx;
            module.section(&globals);
            Some(Wasip2Globals {
                bump_alloc_ptr,
                stdout_handle,
                stderr_handle,
                stdin_handle,
                disk_preopen_handle,
            })
        } else {
            None
        };

    // Phase 1.2b1.5 — `Wasip2Lowering` collects every fn / global /
    // helper idx the call-site lowering for `Console.print` /
    // `Console.error` / `Console.warn` needs to emit canonical-ABI
    // calls instead of the AverBridge `aver/console_print` import.
    // Constructed only when wasip2 imports were registered AND the
    // bridge fn machinery is in place (the latter implies
    // `__rt_string_to_lm` has been allocated — the call site uses
    // it to marshal the Aver String into LM[0..len]).
    let wasip2_lowering: Option<super::body::Wasip2Lowering> =
        if matches!(target, super::TargetMode::Wasip2) && wasip2_imports.import_count() > 0 {
            use super::wasip2_imports::Wasip2ImportSlot;
            // Console.* needs both the bridge `__rt_string_to_lm`
            // helper and the resource-handle globals; clocks /
            // random don't. So those fields are populated only when
            // their owning effects are registered, not as a
            // precondition for `Some(...)` on the whole struct.
            Some(super::body::Wasip2Lowering {
                get_stdout_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::CliGetStdout),
                get_stderr_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::CliGetStderr),
                blocking_write_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush),
                stdout_handle_global: wasip2_globals.as_ref().and_then(|g| g.stdout_handle),
                stderr_handle_global: wasip2_globals.as_ref().and_then(|g| g.stderr_handle),
                str_to_lm_fn_idx: bridge.as_ref().map(|b| b.to_lm_fn),
                clocks_now_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::ClocksWallClockNow),
                random_u64_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::RandomGetRandomU64),
                get_arguments_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::CliEnvironmentGetArguments),
                cabi_realloc_fn_idx: cabi_realloc.as_ref().map(|c| c.fn_idx),
                decode_list_string_fn_idx: decode_list_string.as_ref().map(|d| d.fn_idx),
                get_environment_fn_idx: wasip2_imports
                    .lookup_wasm_fn_idx(Wasip2ImportSlot::CliEnvironmentGetEnvironment),
                env_get_lookup_fn_idx: env_get_lookup.as_ref().map(|e| e.fn_idx),
                fmt_iso8601_fn_idx: format_iso8601.as_ref().map(|f| f.fn_idx),
                console_read_line_fn_idx: console_read_line.as_ref().map(|c| c.fn_idx),
                time_sleep_fn_idx: time_sleep.as_ref().map(|t| t.fn_idx),
                disk_exists_fn_idx: disk_exists.as_ref().map(|d| d.fn_idx),
                disk_read_text_fn_idx: disk_read_text.as_ref().map(|d| d.fn_idx),
                disk_write_text_fn_idx: disk_write_text.as_ref().map(|d| d.fn_idx),
                disk_append_text_fn_idx: disk_append_text.as_ref().map(|d| d.fn_idx),
                disk_delete_fn_idx: disk_delete.as_ref().map(|d| d.fn_idx),
                disk_delete_dir_fn_idx: disk_delete_dir.as_ref().map(|d| d.fn_idx),
                disk_make_dir_fn_idx: disk_make_dir.as_ref().map(|d| d.fn_idx),
                disk_list_dir_fn_idx: disk_list_dir.as_ref().map(|d| d.fn_idx),
                http_get_fn_idx: http_get.as_ref().map(|h| h.fn_idx),
            })
        } else {
            None
        };

    // (caller_fn delivery moved from per-fn globals to an exported
    // name table; segment append + `__caller_fn_*` exports are
    // wired in the post-emit phase further down. Globals + their
    // start-fn init are gone.)

    // Build the fn-name → wasm-fn-idx map. With K imports:
    //   imports at idx 0..K
    //   _start at K
    //   user fn i at K+1+i
    //   builtin at K+1+N+m (assigned by builtin_registry already)
    let start_wasm_idx = import_count;
    let mut by_name: HashMap<String, FnEntry> = HashMap::new();
    for (i, fd) in fn_defs.iter().enumerate() {
        by_name.insert(
            fd.name.clone(),
            FnEntry {
                wasm_idx: import_count + 1 + (i as u32),
                return_type: fd.return_type.clone(),
            },
        );
    }
    let mut builtin_idx_lookup: HashMap<String, u32> = HashMap::new();
    for name in builtin_registry.iter() {
        let idx = builtin_registry
            .lookup_wasm_fn_idx(name)
            .expect("registered builtin has wasm fn idx");
        builtin_idx_lookup.insert(name.canonical().to_string(), idx);
    }
    let mut effect_idx_lookup: HashMap<String, u32> = HashMap::new();
    if matches!(target, super::TargetMode::AverBridge) {
        for name in effect_registry.iter() {
            let idx = effect_registry
                .lookup_wasm_fn_idx(name)
                .expect("registered effect has wasm fn idx");
            effect_idx_lookup.insert(name.canonical().to_string(), idx);
        }
    }
    // On `TargetMode::Wasip2` the EffectRegistry is populated by
    // discovery but never `assign_slots`'d (the import section uses
    // the parallel `Wasip2ImportRegistry` instead), so its
    // `lookup_wasm_fn_idx` returns None for every effect. Leave
    // `effect_idx_lookup` empty: the wasip2 call-site lowering goes
    // through `ctx.wasip2_lowering`, not `ctx.fn_map.effects` /
    // `ctx.effect_idx_lookup`. Effects that the wasip2 path doesn't
    // yet lower (`?!` / `!` independent-product markers, etc.) are
    // out-of-scope for Phase 1.2b1; rejection lives upstream.
    let mut map_helpers_lookup: HashMap<String, super::maps::MapKVHelpers> = HashMap::new();
    for canonical in &registry.map_order {
        if let Some(h) = map_helpers.kv_helpers(canonical) {
            map_helpers_lookup.insert(canonical.clone(), h);
        }
    }
    let mut list_ops_lookup: HashMap<String, super::lists::ListOps> = HashMap::new();
    for canonical in &registry.list_order {
        if let Some(o) = list_helpers.list_ops_for(canonical) {
            list_ops_lookup.insert(canonical.clone(), o);
        }
    }
    let mut vfl_ops_lookup: HashMap<String, super::lists::VectorFromListOps> = HashMap::new();
    for canonical in &registry.list_order {
        if let Some(o) = list_helpers.vfl_ops_for(canonical) {
            vfl_ops_lookup.insert(canonical.clone(), o);
        }
    }
    let mut zip_ops_lookup: HashMap<String, u32> = HashMap::new();
    for tup_canonical in &registry.tuple_order {
        if let Some(idx) = list_helpers.zip_op_for(tup_canonical) {
            zip_ops_lookup.insert(tup_canonical.clone(), idx);
        }
    }
    let string_split_ops = list_helpers.string_split_ops();
    let mut eq_helpers_lookup: HashMap<String, u32> = HashMap::new();
    for (name, _kind) in eq_helpers_registry.iter() {
        if let Some(fn_idx) = eq_helpers_registry.lookup_fn_idx(name) {
            eq_helpers_lookup.insert(name.to_string(), fn_idx);
        }
    }
    // Map<K,V> structural-eq fn idxs flow through the same lookup so
    // BinOp::Eq on a Map dispatches via `Call(__eq_Map<K,V>)` (sum_
    // or_record_eq_fn → ctx.fn_map.eq_helpers). Whitespace-free
    // canonical matches what the operand's `.ty().display()` produces
    // at the call site.
    for canonical in &registry.map_order {
        if let Some(h) = map_helpers.kv_helpers(canonical) {
            eq_helpers_lookup.insert(canonical.clone(), h.eq);
        }
    }
    let fn_map = FnMap {
        by_name,
        builtins: builtin_idx_lookup,
        effects: effect_idx_lookup.clone(),
        map_helpers: map_helpers_lookup,
        list_ops: list_ops_lookup,
        vfl_ops: vfl_ops_lookup,
        zip_ops: zip_ops_lookup,
        string_split_ops,
        eq_helpers: eq_helpers_lookup,
    };

    // ── Export section ─────────────────────────────────────────────
    //
    // Entry-point export name follows the `target`. AverBridge keeps
    // `_start` (the convention every JS host the wasm-gc backend
    // serves understands). Wasip2 exports `wasi:cli/run@0.2.4#run`
    // — the canonical-ABI export name for the WIT function
    // `wasi:cli/run.run`. `wit_component::ComponentEncoder` matches
    // this name against the `wasi:cli/command` world's required
    // `run` export when binding the metadata-declared component
    // surface to the core module.
    let mut exports = ExportSection::new();
    let start_export_name: &str = match (target, proxy_mode) {
        (super::TargetMode::AverBridge, _) => "_start",
        (super::TargetMode::Wasip2, false) => "wasi:cli/run@0.2.4#run",
        // `wasi:http/incoming-handler.handle` — the proxy world's
        // sole required export. `wasmtime serve` / Spin / wasmCloud
        // route every inbound HTTP request through this.
        (super::TargetMode::Wasip2, true) => "wasi:http/incoming-handler@0.2.4#handle",
    };
    exports.export(start_export_name, ExportKind::Func, start_wasm_idx);
    for (i, fd) in fn_defs.iter().enumerate() {
        let wasm_idx = import_count + 1 + (i as u32);
        exports.export(&fd.name, ExportKind::Func, wasm_idx);
    }
    if let Some(b) = &bridge {
        // The four `__rt_*` exports are JS-host-callable only — wasip2
        // hosts (wasmtime / Spin / wasmCloud) consume the canonical-
        // ABI surface, never these names. Skip them when target is
        // Wasip2 to keep the component contract clean (no leaked JS
        // runtime names in a non-JS world).
        if matches!(target, super::TargetMode::AverBridge) {
            exports.export("__rt_string_from_lm", ExportKind::Func, b.from_lm_fn);
            exports.export("__rt_string_to_lm", ExportKind::Func, b.to_lm_fn);
            exports.export("__rt_memory_pages", ExportKind::Func, b.pages_fn);
            exports.export("__rt_memory_grow", ExportKind::Func, b.grow_fn);
        }
        exports.export("memory", ExportKind::Memory, 0);
    } else if cabi_realloc.is_some() {
        // wasip2 path with no bridge (theoretical — cabi_realloc
        // gates on `wasip2_imports.import_count() > 0` which only
        // fires when an effect that needs LM is registered, and
        // every such effect today implies a String). Defensive
        // export so the host can find memory regardless.
        exports.export("memory", ExportKind::Memory, 0);
    }
    if let Some(c) = &cabi_realloc {
        // Required by Component Model canonical ABI as the guest's
        // realloc callback. Phase 1.3.1 ships the impl; consumers
        // (Args.get / Env.get / Console.readLine / Disk.readText)
        // start landing in 1.3.2.
        exports.export("cabi_realloc", ExportKind::Func, c.fn_idx);
    }
    factory_exports.emit_exports(&mut exports);
    if let Some(hw) = &handler_wrapper {
        exports.export("aver_http_handle", ExportKind::Func, hw.wrapper_fn);
        exports.export("__rt_list_string_cons", ExportKind::Func, hw.list_cons_fn);
        // Map<String,List<String>> bridge: the JS host needs to build
        // a request-headers map to satisfy `request_headers_load`.
        // Re-export the per-instance Map helper slots under stable
        // bridge names.
        if let Some(map_h) = map_helpers.kv_helpers("Map<String,List<String>>") {
            exports.export(
                "__rt_map_string_list_string_empty",
                ExportKind::Func,
                map_h.empty,
            );
            exports.export(
                "__rt_map_string_list_string_set",
                ExportKind::Func,
                map_h.set,
            );
        }
    }
    if let Some((count_fn_idx, name_fn_idx)) = caller_fn_table_fns {
        exports.export("__caller_fn_count", ExportKind::Func, count_fn_idx);
        exports.export("__caller_fn_name", ExportKind::Func, name_fn_idx);
    }
    module.section(&exports);

    // (No StartSection — 0.16.2's caller_fn globals init is gone;
    // host reads the caller_fn name table via `__caller_fn_count`
    // + `__caller_fn_name(i)` exports at instantiation instead.)

    // Pre-register the synthesised `aver_http_handle` wrapper as a
    // caller_fn entry — `emit_handler_wrapper` (much later in the
    // code section) pushes this idx as the trailing `caller_fn_idx`
    // arg for every Request.* / Response.* effect call. Has to land
    // BEFORE the pre-pass snapshot below, otherwise data section ends
    // up with one more passive segment than the data count section
    // declared, and the validator rejects the module.
    let wrapper_caller_fn_idx: Option<u32> = handler_wrapper.as_ref().map(|_| {
        caller_fn_collector
            .borrow_mut()
            .register("aver_http_handle")
    });

    // Pre-pass over user fn bodies — populates `caller_fn_collector`
    // with every fn name that emits caller_fn at a call site. Needed
    // before data count + data section emit because the count of
    // passive segments is `string_literals + collector.names`, and
    // data count section must precede the code section. Real body
    // emit later in the code section calls `register` again with the
    // same names; the collector is idempotent so the idx assignment
    // matches what the call sites observed during this probe.
    for (i, fd) in fn_defs.iter().enumerate() {
        let self_wasm_idx = import_count + 1 + (i as u32);
        let mut probe = Function::new([]);
        let _ = emit_fn_body(
            &mut probe,
            fd,
            &fn_map,
            self_wasm_idx,
            &registry,
            &effect_idx_lookup,
            &caller_fn_collector,
            wasip2_lowering.as_ref(),
        )?;
    }
    let caller_fn_segment_count = caller_fn_collector.borrow().names.len() as u32;

    // ── Data count section (must precede code when using passive
    //     segments via array.new_data / data.drop).
    let total_segment_count = registry.string_literals.len() as u32 + caller_fn_segment_count;
    if total_segment_count > 0 {
        let count = DataCountSection {
            count: total_segment_count,
        };
        module.section(&count);
    }

    // ── Code section ───────────────────────────────────────────────
    let mut codes = CodeSection::new();

    // Entry-point body. Three shapes, one slot:
    //
    // - AverBridge `_start: () -> ()` — call main, drop any return.
    //   JS host observes side effects via `aver/*` imports.
    // - Wasip2 / CliCommand `wasi:cli/run.run: () -> i32` — same
    //   call+drop, then `i32.const 0` (Ok in `result<_, _>`).
    // - Wasip2 / HttpProxy `wasi:http/incoming-handler.handle:
    //   (request, outparam) -> ()` — body is the full per-request
    //   choreography emitted via `emit_aver_http_handle`. `main`
    //   is never invoked (it's emitted as a normal user fn and
    //   never called from here); its `HttpServer.listen(_, _)`
    //   call lowered to a no-op upstream.
    if proxy_mode {
        let user_handler_idx = handler_name
            .and_then(|name| fn_defs.iter().position(|fd| fd.name == name))
            .ok_or_else(|| {
                WasmGcError::Validation(format!(
                    "proxy handler `{}` doesn't match any fn in this module",
                    handler_name.unwrap_or("?")
                ))
            })?;
        let user_handler_wasm_idx = import_count + 1 + (user_handler_idx as u32);

        let string_idx = registry
            .string_array_type_idx
            .ok_or_else(|| WasmGcError::Validation("proxy mode requires String slot".into()))?;
        let http_request_idx = registry.record_type_idx("HttpRequest").ok_or_else(|| {
            WasmGcError::Validation("proxy mode requires HttpRequest record slot".into())
        })?;
        let http_response_idx = registry.record_type_idx("HttpResponse").ok_or_else(|| {
            WasmGcError::Validation("proxy mode requires HttpResponse record slot".into())
        })?;
        let map_slots = registry
            .map_slots("Map<String,List<String>>")
            .ok_or_else(|| {
                WasmGcError::Validation(
                    "proxy mode requires Map<String, List<String>> slots".into(),
                )
            })?;
        let list_string_idx = registry.list_type_idx("List<String>").ok_or_else(|| {
            WasmGcError::Validation("proxy mode requires List<String> slot".into())
        })?;
        let opt_list_string_idx = registry
            .option_type_idx("Option<List<String>>")
            .ok_or_else(|| {
                WasmGcError::Validation("proxy mode requires Option<List<String>> slot".into())
            })?;
        let cabi = cabi_realloc
            .as_ref()
            .ok_or_else(|| WasmGcError::Validation("proxy mode requires cabi_realloc".into()))?
            .fn_idx;
        let bridge_ref = bridge
            .as_ref()
            .ok_or_else(|| WasmGcError::Validation("proxy mode requires bridge helpers".into()))?;
        let map_h = map_helpers
            .kv_helpers("Map<String,List<String>>")
            .ok_or_else(|| {
                WasmGcError::Validation(
                    "proxy mode requires Map<String, List<String>> kv helpers".into(),
                )
            })?;
        let lookup = |slot: super::wasip2_imports::Wasip2ImportSlot,
                      name: &'static str|
         -> Result<u32, WasmGcError> {
            wasip2_imports.lookup_wasm_fn_idx(slot).ok_or_else(|| {
                WasmGcError::Validation(format!(
                    "proxy mode requires {name} import (slot not allocated)"
                ))
            })
        };
        use super::wasip2_imports::Wasip2ImportSlot as Slot;
        let indices = super::wasip2_http_server::ServerHandlerIndices {
            fn_type: start_type_idx,
            fn_idx: start_wasm_idx,
            string_type_idx: string_idx,
            http_request_type_idx: http_request_idx,
            http_response_type_idx: http_response_idx,
            headers_keys_array_type_idx: map_slots.keys_array,
            headers_values_array_type_idx: map_slots.values_array,
            headers_map_type_idx: map_slots.map,
            list_string_type_idx: list_string_idx,
            option_list_string_type_idx: opt_list_string_idx,
        };
        let helpers = super::wasip2_http_server::ServerHandlerHelperFns {
            cabi_realloc_fn: cabi,
            str_to_lm_fn: bridge_ref.to_lm_fn,
            from_lm_fn: bridge_ref.from_lm_fn,
            incoming_request_method_fn: lookup(
                Slot::HttpTypesIncomingRequestMethod,
                "incoming-request.method",
            )?,
            incoming_request_path_with_query_fn: lookup(
                Slot::HttpTypesIncomingRequestPathWithQuery,
                "incoming-request.path-with-query",
            )?,
            incoming_request_headers_fn: lookup(
                Slot::HttpTypesIncomingRequestHeaders,
                "incoming-request.headers",
            )?,
            incoming_request_consume_fn: lookup(
                Slot::HttpTypesIncomingRequestConsume,
                "incoming-request.consume",
            )?,
            drop_incoming_request_fn: lookup(
                Slot::HttpTypesResourceDropIncomingRequest,
                "[resource-drop]incoming-request",
            )?,
            fields_entries_fn: lookup(Slot::HttpTypesFieldsEntries, "fields.entries")?,
            drop_fields_fn: lookup(Slot::HttpTypesResourceDropFields, "[resource-drop]fields")?,
            incoming_body_stream_fn: lookup(
                Slot::HttpTypesIncomingBodyStream,
                "incoming-body.stream",
            )?,
            incoming_body_finish_fn: lookup(
                Slot::HttpTypesIncomingBodyFinish,
                "incoming-body.finish",
            )?,
            drop_incoming_body_fn: lookup(
                Slot::HttpTypesResourceDropIncomingBody,
                "[resource-drop]incoming-body",
            )?,
            blocking_read_fn: lookup(Slot::InputStreamBlockingRead, "input-stream.blocking-read")?,
            drop_input_stream_fn: lookup(
                Slot::IoStreamsResourceDropInputStream,
                "[resource-drop]input-stream",
            )?,
            drop_future_trailers_fn: lookup(
                Slot::HttpTypesResourceDropFutureTrailers,
                "[resource-drop]future-trailers",
            )?,
            fields_new_fn: lookup(Slot::HttpTypesFieldsNew, "[constructor]fields")?,
            fields_append_fn: lookup(Slot::HttpTypesFieldsAppend, "fields.append")?,
            outgoing_response_new_fn: lookup(
                Slot::HttpTypesOutgoingResponseNew,
                "[constructor]outgoing-response",
            )?,
            set_status_code_fn: lookup(
                Slot::HttpTypesOutgoingResponseSetStatusCode,
                "outgoing-response.set-status-code",
            )?,
            outgoing_response_body_fn: lookup(
                Slot::HttpTypesOutgoingResponseBody,
                "outgoing-response.body",
            )?,
            outgoing_body_write_fn: lookup(
                Slot::HttpTypesOutgoingBodyWrite,
                "outgoing-body.write",
            )?,
            outgoing_body_finish_fn: lookup(
                Slot::HttpTypesOutgoingBodyFinish,
                "outgoing-body.finish",
            )?,
            blocking_write_fn: lookup(
                Slot::OutputStreamBlockingWriteAndFlush,
                "output-stream.blocking-write-and-flush",
            )?,
            drop_output_stream_fn: lookup(
                Slot::IoStreamsResourceDropOutputStream,
                "[resource-drop]output-stream",
            )?,
            drop_outgoing_body_fn: lookup(
                Slot::HttpTypesResourceDropOutgoingBody,
                "[resource-drop]outgoing-body",
            )?,
            response_outparam_set_fn: lookup(
                Slot::HttpTypesResponseOutparamSet,
                "[static]response-outparam.set",
            )?,
            map_set_fn: map_h.set,
            map_get_fn: map_h.get,
            user_handler_fn: user_handler_wasm_idx,
        };
        codes.function(&super::wasip2_http_server::emit_aver_http_handle(
            &indices, &helpers,
        ));
    } else {
        let mut start = Function::new([]);
        if let Some(idx) = main_idx {
            let main_idx_wasm = import_count + 1 + (idx as u32);
            let main_returns_value = !fn_defs[idx].return_type.trim().eq("Unit");
            start.instruction(&Instruction::Call(main_idx_wasm));
            if main_returns_value {
                start.instruction(&Instruction::Drop);
            }
        }
        if start_returns_i32 {
            start.instruction(&Instruction::I32Const(0));
        }
        start.instruction(&Instruction::End);
        codes.function(&start);
    }

    for (i, fd) in fn_defs.iter().enumerate() {
        let self_wasm_idx = import_count + 1 + (i as u32);
        // Dry run: discover extra locals by emitting into a throwaway
        // fn. Cheaper than threading a separate pre-pass.
        let mut probe = Function::new([]);
        let extra_locals_dry = emit_fn_body(
            &mut probe,
            fd,
            &fn_map,
            self_wasm_idx,
            &registry,
            &effect_idx_lookup,
            &caller_fn_collector,
            wasip2_lowering.as_ref(),
        )?;

        let local_groups: Vec<(u32, ValType)> = extra_locals_dry.iter().map(|v| (1, *v)).collect();
        let mut func = Function::new(local_groups);
        let _ = emit_fn_body(
            &mut func,
            fd,
            &fn_map,
            self_wasm_idx,
            &registry,
            &effect_idx_lookup,
            &caller_fn_collector,
            wasip2_lowering.as_ref(),
        )?;
        codes.function(&func);
    }

    // Builtin helper bodies — emitted after user fns so their own
    // wasm fn indices come last. Bodies are stubs today (Unreachable);
    // real impls land in `builtins/` per phase 3c roadmap.
    builtin_registry.emit_helper_bodies(&mut codes, &registry)?;

    // Map helper bodies (hash, eq, empty, set, get, len per
    // instantiation) — emitted last so their wasm fn indices line up
    // with what `MapHelperRegistry::assign_slots` recorded.
    // Snapshot list / vector eq+hash fn idxes so map record-key
    // helpers can dispatch `List<T>` / `Vector<T>` field types
    // without cross-module lookups.
    let mut compound_eq_hash_lookup: HashMap<String, (u32, u32)> = HashMap::new();
    for canonical in &registry.list_order {
        if let Some(o) = list_helpers.list_ops_for(canonical)
            && let (Some(eq_fn), Some(hash_fn)) = (o.eq, o.hash)
        {
            compound_eq_hash_lookup.insert(canonical.clone(), (eq_fn, hash_fn));
        }
    }
    for canonical in &registry.list_order {
        // vfl_ops keyed by list canonical, but the `Vector<T>`
        // canonical is the right pseudo-K name for record-field
        // dispatch — translate.
        if let Some(elem) = TypeRegistry::list_element_type(canonical)
            && let Some(o) = list_helpers.vfl_ops_for(canonical)
            && let (Some(eq_fn), Some(hash_fn)) = (o.eq, o.hash)
        {
            compound_eq_hash_lookup.insert(format!("Vector<{}>", elem.trim()), (eq_fn, hash_fn));
        }
    }
    // Map<K,V> structural eq + commutative hash — per-instantiation
    // helpers live in MapHelperRegistry::kv. Threading them into the
    // compound lookup lets record/sum/list/vec field dispatch call
    // `__eq_Map<K,V>` / `__hash_Map<K,V>` uniformly with carriers.
    for canonical in &registry.map_order {
        if let Some(h) = map_helpers.kv_helpers(canonical) {
            compound_eq_hash_lookup.insert(canonical.clone(), (h.eq, h.hash));
        }
    }
    // Carrier eq+hash lookup — Option/Result/Tuple instantiations
    // get their helpers from eq_helpers / hash_helpers; map keys
    // proxy through these. Build the pair map by zipping the two
    // registries' fn idxs by canonical.
    let mut carrier_eq_hash_lookup: HashMap<String, (u32, u32)> = HashMap::new();
    for (name, kind) in eq_helpers_registry.iter() {
        use super::body::eq_helpers::EqKind as EK;
        if matches!(kind, EK::OptionEq | EK::ResultEq | EK::TupleEq)
            && let Some(eq_fn) = eq_helpers_registry.lookup_fn_idx(name)
            && let Some(hash_fn) = hash_helpers_registry.lookup_fn_idx(name)
        {
            carrier_eq_hash_lookup.insert(name.to_string(), (eq_fn, hash_fn));
        }
    }
    map_helpers.emit_helper_bodies(
        &mut codes,
        &registry,
        &compound_eq_hash_lookup,
        &carrier_eq_hash_lookup,
    )?;

    // List / Vector.fromList / String.split-join helper bodies.
    // Snapshot eq-helper fn idxs so list/vec eq+hash bodies can
    // dispatch nominal-element `==`/hash through `Call(__eq_<X>)`.
    // Merge in list_helpers' own list/vec canonicals so `List<List<X>>`
    // / `List<Vector<X>>` element dispatch finds the inner helper.
    let string_eq_fn_idx = builtin_registry.lookup_wasm_fn_idx(BuiltinName::StringEq);
    let mut eq_helper_fn_idx_map: HashMap<String, u32> = eq_helpers_registry
        .iter()
        .filter_map(|(n, _k)| {
            eq_helpers_registry
                .lookup_fn_idx(n)
                .map(|i| (n.to_string(), i))
        })
        .collect();
    let mut hash_helper_fn_idx_map: HashMap<String, u32> = hash_helpers_registry
        .iter()
        .filter_map(|(n, _k)| {
            hash_helpers_registry
                .lookup_fn_idx(n)
                .map(|i| (n.to_string(), i))
        })
        .collect();
    for (canonical, (eq_fn, hash_fn)) in &compound_eq_hash_lookup {
        eq_helper_fn_idx_map.insert(canonical.clone(), *eq_fn);
        hash_helper_fn_idx_map.insert(canonical.clone(), *hash_fn);
    }
    list_helpers.emit_helper_bodies(
        &mut codes,
        &registry,
        string_eq_fn_idx,
        &eq_helper_fn_idx_map,
        &hash_helper_fn_idx_map,
    )?;

    // Per-(record/sum) `__eq_<TypeName>` helper bodies — emit after
    // list helpers so any String fields can call `__wasmgc_string_eq`
    // by the index recorded above. The compound eq lookup forwards
    // `List<T>` / `Vector<T>` fn idxs so a record field of type
    // `List<Option<Int>>` (etc.) can dispatch via
    // `Call(__eq_List<…>)`. Same shape on the hash side.
    let compound_eq_lookup: HashMap<String, u32> = compound_eq_hash_lookup
        .iter()
        .map(|(n, (eq, _))| (n.clone(), *eq))
        .collect();
    let compound_hash_lookup: HashMap<String, u32> = compound_eq_hash_lookup
        .iter()
        .map(|(n, (_, h))| (n.clone(), *h))
        .collect();
    eq_helpers_registry.emit_helper_bodies(
        &mut codes,
        &registry,
        string_eq_fn_idx,
        &compound_eq_lookup,
    )?;
    // `__hash_<X>` helper bodies — emitted right after eq helpers so
    // every nominal/carrier hash dispatch finds its target fn_idx.
    hash_helpers_registry.emit_helper_bodies(
        &mut codes,
        &registry,
        string_eq_fn_idx,
        &compound_hash_lookup,
    )?;

    if let Some(hw) = &handler_wrapper {
        let user_handler_wasm_idx = import_count + 1 + (hw.user_handler_idx as u32);
        // Reserve a caller_fn idx for the synthesised wrapper itself.
        // `emit_handler_wrapper` pushes this constant before every
        // host-effect `Call` to satisfy the ABI's trailing
        // `caller_fn_idx: i32` param (added in 0.16). The idx was
        // pre-registered above the pre-pass so the data count section
        // already accounts for the segment.
        let wrapper_caller_fn_idx = wrapper_caller_fn_idx
            .expect("handler_wrapper present implies wrapper_caller_fn_idx pre-registered");
        codes.function(&emit_handler_wrapper(
            &registry,
            &fn_map,
            user_handler_wasm_idx,
            wrapper_caller_fn_idx,
        )?);
        codes.function(&emit_list_string_cons(&registry)?);
        let _ = hw.list_cons_type; // type idx already consumed by emit_function_section
    }

    if bridge.is_some() {
        emit_bridge_bodies(&mut codes, &registry)?;
    }

    if cabi_realloc.is_some() {
        // `wasip2_globals` is `Some` whenever `cabi_realloc` is —
        // both gate on `wasip2_imports.import_count() > 0` and
        // `Wasip2Globals::bump_alloc_ptr` is allocated
        // unconditionally on that path. Unwrap is sound;
        // `expect` carries a louder message than a silent panic
        // if the invariant ever drifts.
        let bump_global = wasip2_globals
            .as_ref()
            .expect("cabi_realloc emit requires Wasip2Globals (same gate)")
            .bump_alloc_ptr;
        codes.function(&emit_cabi_realloc(bump_global));
    }
    if let Some(d) = &decode_list_string {
        codes.function(&emit_decode_list_string(
            d.string_type_idx,
            d.list_string_type_idx,
        ));
    }
    if let Some(c) = &console_read_line {
        let stdin_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.stdin_handle)
            .expect("console_read_line emit requires stdin_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("console_read_line emit requires cabi_realloc fn idx (gate matches)")
            .fn_idx;
        let get_stdin = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::CliStdinGetStdin)
            .expect("console_read_line emit requires CliStdinGetStdin fn idx (gate matches)");
        let blocking_read = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
            .expect("console_read_line emit requires InputStreamBlockingRead fn idx");
        codes.function(&emit_console_read_line(
            c.string_type_idx,
            c.result_string_string_type_idx,
            stdin_global,
            cabi,
            get_stdin,
            blocking_read,
        ));
    }
    if time_sleep.is_some() {
        let cabi = cabi_realloc
            .as_ref()
            .expect("time_sleep emit requires cabi_realloc fn idx (gate matches)")
            .fn_idx;
        let subscribe = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::ClocksMonotonicSubscribeDuration,
            )
            .expect("time_sleep emit requires subscribe-duration fn idx (gate matches)");
        let poll = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollPoll)
            .expect("time_sleep emit requires poll fn idx (gate matches)");
        let drop_pollable = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable)
            .expect("time_sleep emit requires drop-pollable fn idx (gate matches)");
        codes.function(&emit_time_sleep(cabi, subscribe, poll, drop_pollable));
    }
    if disk_exists.is_some() {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_exists emit requires disk_preopen_handle global (gate matches)");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_exists emit requires cabi_realloc fn idx (gate matches)")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_exists emit requires bridge (string marshalling)")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_exists emit requires get-directories fn idx (gate matches)");
        let stat_at = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesStatAt)
            .expect("disk_exists emit requires stat-at fn idx (gate matches)");
        codes.function(&emit_disk_exists(
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            stat_at,
        ));
    }
    if let Some(rt) = &disk_read_text {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_read_text emit requires disk_preopen_handle global (gate matches)");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_read_text emit requires cabi_realloc fn idx (gate matches)")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_read_text emit requires bridge (string marshalling)")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_read_text emit requires get-directories fn idx");
        let open_at = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .expect("disk_read_text emit requires open-at fn idx");
        let read_via_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesReadViaStream,
            )
            .expect("disk_read_text emit requires read-via-stream fn idx");
        let blocking_read = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
            .expect("disk_read_text emit requires blocking-read fn idx");
        let drop_descriptor = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .expect("disk_read_text emit requires drop-descriptor fn idx");
        let drop_input_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
            )
            .expect("disk_read_text emit requires drop-input-stream fn idx");
        codes.function(&emit_disk_read_text(
            rt.string_type_idx,
            rt.result_string_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            open_at,
            read_via_stream,
            blocking_read,
            drop_descriptor,
            drop_input_stream,
        ));
    }
    if let Some(wt) = &disk_write_text {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_write_text emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_write_text emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_write_text emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_write_text emit requires get-directories fn idx");
        let open_at = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .expect("disk_write_text emit requires open-at fn idx");
        let write_via_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesWriteViaStream,
            )
            .expect("disk_write_text emit requires write-via-stream fn idx");
        let blocking_write = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
            )
            .expect("disk_write_text emit requires blocking-write-and-flush fn idx");
        let drop_descriptor = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .expect("disk_write_text emit requires drop-descriptor fn idx");
        let drop_output_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
            )
            .expect("disk_write_text emit requires drop-output-stream fn idx");
        codes.function(&emit_disk_write_text(
            wt.string_type_idx,
            wt.result_unit_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            open_at,
            write_via_stream,
            blocking_write,
            drop_descriptor,
            drop_output_stream,
            false, // is_append: writeText uses CREATE | TRUNCATE + write-via-stream
        ));
    }
    if let Some(at) = &disk_append_text {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_append_text emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_append_text emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_append_text emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_append_text emit requires get-directories fn idx");
        let open_at = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .expect("disk_append_text emit requires open-at fn idx");
        let append_via_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesAppendViaStream,
            )
            .expect("disk_append_text emit requires append-via-stream fn idx");
        let blocking_write = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
            )
            .expect("disk_append_text emit requires blocking-write-and-flush fn idx");
        let drop_descriptor = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .expect("disk_append_text emit requires drop-descriptor fn idx");
        let drop_output_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
            )
            .expect("disk_append_text emit requires drop-output-stream fn idx");
        codes.function(&emit_disk_write_text(
            at.string_type_idx,
            at.result_unit_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            open_at,
            append_via_stream,
            blocking_write,
            drop_descriptor,
            drop_output_stream,
            true, // is_append: CREATE only + append-via-stream (no offset arg)
        ));
    }
    // Three single-call ops share `emit_disk_simple_path_op` —
    // identical pipeline (preopen + path + 4-byte retptr + tag
    // check), only the wasi op fn idx and Err message differ.
    if let Some(d) = &disk_delete {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_delete emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_delete emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_delete emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_delete emit requires get-directories fn idx");
        let op_fn = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesUnlinkFileAt,
            )
            .expect("disk_delete emit requires unlink-file-at fn idx");
        codes.function(&emit_disk_simple_path_op(
            d.string_type_idx,
            d.result_unit_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            op_fn,
            b"delete failed",
        ));
    }
    if let Some(d) = &disk_delete_dir {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_delete_dir emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_delete_dir emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_delete_dir emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_delete_dir emit requires get-directories fn idx");
        let op_fn = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesRemoveDirectoryAt,
            )
            .expect("disk_delete_dir emit requires remove-directory-at fn idx");
        codes.function(&emit_disk_simple_path_op(
            d.string_type_idx,
            d.result_unit_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            op_fn,
            b"deleteDir failed",
        ));
    }
    if let Some(d) = &disk_make_dir {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_make_dir emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_make_dir emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_make_dir emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_make_dir emit requires get-directories fn idx");
        let op_fn = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesCreateDirectoryAt,
            )
            .expect("disk_make_dir emit requires create-directory-at fn idx");
        codes.function(&emit_disk_simple_path_op(
            d.string_type_idx,
            d.result_unit_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            op_fn,
            b"makeDir failed",
        ));
    }
    if let Some(ld) = &disk_list_dir {
        let preopen_global = wasip2_globals
            .as_ref()
            .and_then(|g| g.disk_preopen_handle)
            .expect("disk_list_dir emit requires disk_preopen_handle global");
        let cabi = cabi_realloc
            .as_ref()
            .expect("disk_list_dir emit requires cabi_realloc fn idx")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("disk_list_dir emit requires bridge")
            .to_lm_fn;
        let get_directories = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemPreopensGetDirectories,
            )
            .expect("disk_list_dir emit requires get-directories fn idx");
        let open_at = wasip2_imports
            .lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesOpenAt)
            .expect("disk_list_dir emit requires open-at fn idx");
        let read_directory = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesReadDirectory,
            )
            .expect("disk_list_dir emit requires read-directory fn idx");
        let read_dir_entry = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesDirectoryEntryStreamReadDirectoryEntry,
            )
            .expect("disk_list_dir emit requires read-directory-entry fn idx");
        let drop_descriptor = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDescriptor,
            )
            .expect("disk_list_dir emit requires drop-descriptor fn idx");
        let drop_dir_stream = wasip2_imports
            .lookup_wasm_fn_idx(
                super::wasip2_imports::Wasip2ImportSlot::FilesystemTypesResourceDropDirectoryEntryStream,
            )
            .expect("disk_list_dir emit requires drop-directory-entry-stream fn idx");
        codes.function(&emit_disk_list_dir(
            ld.string_type_idx,
            ld.list_string_type_idx,
            ld.result_list_string_string_type_idx,
            preopen_global,
            cabi,
            str_to_lm,
            get_directories,
            open_at,
            read_directory,
            read_dir_entry,
            drop_descriptor,
            drop_dir_stream,
        ));
    }
    if let Some(hg) = &http_get {
        let cabi = cabi_realloc
            .as_ref()
            .expect("http_get emit requires cabi_realloc fn idx (gate matches)")
            .fn_idx;
        let str_to_lm = bridge
            .as_ref()
            .expect("http_get emit requires bridge (string marshalling)")
            .to_lm_fn;
        let lookup = |slot: super::wasip2_imports::Wasip2ImportSlot, name: &'static str| -> u32 {
            wasip2_imports
                .lookup_wasm_fn_idx(slot)
                .unwrap_or_else(|| panic!("http_get emit requires {name} fn idx"))
        };
        let helpers = super::wasip2_http::HttpGetHelperFns {
            cabi_realloc_fn: cabi,
            str_to_lm_fn: str_to_lm,
            fields_new_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsNew,
                "HttpTypesFieldsNew",
            ),
            outgoing_request_new_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestNew,
                "HttpTypesOutgoingRequestNew",
            ),
            set_scheme_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetScheme,
                "HttpTypesOutgoingRequestSetScheme",
            ),
            set_authority_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetAuthority,
                "HttpTypesOutgoingRequestSetAuthority",
            ),
            set_path_with_query_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetPathWithQuery,
                "HttpTypesOutgoingRequestSetPathWithQuery",
            ),
            handle_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpOutgoingHandlerHandle,
                "HttpOutgoingHandlerHandle",
            ),
            future_subscribe_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesFutureIncomingResponseSubscribe,
                "HttpTypesFutureIncomingResponseSubscribe",
            ),
            poll_fn: lookup(super::wasip2_imports::Wasip2ImportSlot::IoPollPoll, "IoPollPoll"),
            drop_pollable_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable,
                "IoPollResourceDropPollable",
            ),
            future_get_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesFutureIncomingResponseGet,
                "HttpTypesFutureIncomingResponseGet",
            ),
            status_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseStatus,
                "HttpTypesIncomingResponseStatus",
            ),
            consume_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseConsume,
                "HttpTypesIncomingResponseConsume",
            ),
            body_stream_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingBodyStream,
                "HttpTypesIncomingBodyStream",
            ),
            blocking_read_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead,
                "InputStreamBlockingRead",
            ),
            body_finish_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingBodyFinish,
                "HttpTypesIncomingBodyFinish",
            ),
            drop_input_stream_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
                "IoStreamsResourceDropInputStream",
            ),
            drop_outgoing_request_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropOutgoingRequest,
                "HttpTypesResourceDropOutgoingRequest",
            ),
            drop_future_response_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFutureIncomingResponse,
                "HttpTypesResourceDropFutureIncomingResponse",
            ),
            drop_incoming_response_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropIncomingResponse,
                "HttpTypesResourceDropIncomingResponse",
            ),
            drop_future_trailers_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFutureTrailers,
                "HttpTypesResourceDropFutureTrailers",
            ),
            // Step F + G additions.
            drop_incoming_body_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropIncomingBody,
                "HttpTypesResourceDropIncomingBody",
            ),
            headers_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesIncomingResponseHeaders,
                "HttpTypesIncomingResponseHeaders",
            ),
            entries_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsEntries,
                "HttpTypesFieldsEntries",
            ),
            drop_fields_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropFields,
                "HttpTypesResourceDropFields",
            ),
            from_lm_fn: bridge
                .as_ref()
                .expect("http_get emit requires bridge (from_lm helper)")
                .from_lm_fn,
            map_set_fn: fn_map
                .map_helpers
                .get("Map<String,List<String>>")
                .expect("http_get emit requires Map<String,List<String>> helpers")
                .set,
            map_get_fn: fn_map
                .map_helpers
                .get("Map<String,List<String>>")
                .expect("http_get emit requires Map<String,List<String>> helpers")
                .get,
            set_method_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestSetMethod,
                "HttpTypesOutgoingRequestSetMethod",
            ),
            outgoing_request_body_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingRequestBody,
                "HttpTypesOutgoingRequestBody",
            ),
            outgoing_body_write_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingBodyWrite,
                "HttpTypesOutgoingBodyWrite",
            ),
            outgoing_body_finish_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesOutgoingBodyFinish,
                "HttpTypesOutgoingBodyFinish",
            ),
            fields_append_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesFieldsAppend,
                "HttpTypesFieldsAppend",
            ),
            drop_outgoing_body_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::HttpTypesResourceDropOutgoingBody,
                "HttpTypesResourceDropOutgoingBody",
            ),
            blocking_write_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
                "OutputStreamBlockingWriteAndFlush",
            ),
            drop_output_stream_fn: lookup(
                super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
                "IoStreamsResourceDropOutputStream",
            ),
        };
        codes.function(&super::wasip2_http::emit_http_get(hg, &helpers));
    }
    if let Some(e) = &env_get_lookup {
        codes.function(&emit_env_get_lookup(
            e.string_type_idx,
            e.option_string_type_idx,
        ));
    }
    if let Some(fmt) = &format_iso8601 {
        codes.function(&emit_format_iso8601(fmt.string_type_idx));
    }

    factory_exports.emit_bodies(&mut codes, &registry)?;

    // `__caller_fn_count` + `__caller_fn_name` bodies. Emitted after
    // every helper so their fn idxs land last in the code section,
    // matching the function section allocation order. The collector
    // is fully populated at this point — every user-fn body ran
    // through the pre-pass and the real-emit pass.
    if let Some((_count_fn_idx, _name_fn_idx)) = caller_fn_table_fns {
        let names = caller_fn_collector.borrow();
        let string_idx = registry
            .string_array_type_idx
            .expect("caller_fn name table requires the $string slot");
        // Caller-fn name segments occupy the data section slot range
        // [string_literals.len()..string_literals.len()+names.len()];
        // `array.new_data` in `__caller_fn_name(i)` reads from those
        // idxs.
        let segment_base = registry.string_literals.len() as u32;

        // __caller_fn_count: pure constant.
        let mut count_fn = Function::new([]);
        count_fn.instruction(&Instruction::I32Const(names.names.len() as i32));
        count_fn.instruction(&Instruction::End);
        codes.function(&count_fn);

        // __caller_fn_name(idx) -> ref null $string. Switch on idx
        // via `br_table`; each arm materialises the matching String
        // ref via `array.new_data`. A trailing default arm returns
        // ref.null for out-of-range idxs (host shouldn't pass them,
        // but the wasm validator wants a fallthrough).
        let string_ref_ty = ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(string_idx),
        });
        let mut name_fn = Function::new([]);
        let block_ty = wasm_encoder::BlockType::Result(string_ref_ty);
        name_fn.instruction(&Instruction::Block(block_ty));
        for (i, fn_name) in names.names.iter().enumerate() {
            let bytes = fn_name.as_bytes();
            // Inner block: if idx == i, this arm emits the ref and
            // breaks out of the outer block. Otherwise falls through
            // to the next arm.
            name_fn.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
            // if local 0 != i { br 0 } — skip to next arm.
            name_fn.instruction(&Instruction::LocalGet(0));
            name_fn.instruction(&Instruction::I32Const(i as i32));
            name_fn.instruction(&Instruction::I32Ne);
            name_fn.instruction(&Instruction::BrIf(0));
            // Match: emit ref + break to outer.
            name_fn.instruction(&Instruction::I32Const(0));
            name_fn.instruction(&Instruction::I32Const(bytes.len() as i32));
            name_fn.instruction(&Instruction::ArrayNewData {
                array_type_index: string_idx,
                array_data_index: segment_base + i as u32,
            });
            name_fn.instruction(&Instruction::Br(1));
            name_fn.instruction(&Instruction::End);
        }
        // Default arm — out-of-range idx returns ref.null.
        name_fn.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
            string_idx,
        )));
        name_fn.instruction(&Instruction::End);
        name_fn.instruction(&Instruction::End);
        codes.function(&name_fn);
    }

    module.section(&codes);

    // ── Data section ───────────────────────────────────────────────
    // Passive segments holding String literal byte sequences. Emitted
    // last; `array.new_data $string $segment_idx` reads from these.
    // Order: pre-walked program literals first, caller_fn names
    // second. `__caller_fn_name`'s body uses
    // `segment_base = registry.string_literals.len()` so its arms
    // hit the right slots regardless of how many literals the
    // program has.
    if total_segment_count > 0 {
        let mut data = DataSection::new();
        for bytes in &registry.string_literals {
            data.passive(bytes.iter().copied());
        }
        let names = caller_fn_collector.borrow();
        for fn_name in &names.names {
            data.passive(fn_name.as_bytes().iter().copied());
        }
        module.section(&data);
    }

    let bytes = module.finish();
    if let Err(e) = validate(&bytes) {
        // Dump invalid bytes for `wasm-tools print` inspection.
        let _ = std::fs::write("/tmp/aver_wasm_gc_invalid.wasm", &bytes);
        return Err(e);
    }
    Ok(bytes)
}

fn emit_user_types(
    types: &mut TypeSection,
    items: &[TopLevel],
    registry: &TypeRegistry,
) -> Result<(), WasmGcError> {
    // ALL user types — records, variants, string array, vectors,
    // results, lists, options, maps, builtin records — go into a
    // single explicit rec group. Inside a rec group wasm-gc allows
    // forward references between members, which lifts the strict
    // bottom-up ordering constraint that otherwise made
    // `Vector<List<Int>>` / `List<Map<K, V>>` / any cross-collection
    // nesting impossible to express. Type indices follow registry
    // insertion order exactly the way they did before the rec group;
    // the difference is that members can refer to peers at higher
    // indices without crossing a group boundary.
    use wasm_encoder::{ArrayType, CompositeInnerType, CompositeType, StructType, SubType};
    // Each entry pairs a registry-recorded type idx with the subtype
    // shape. Sorting by idx at the end guarantees the rec-group emit
    // position matches what `vector_type_idx` / `list_type_idx` /
    // `option_type_idx` / `map_slots` / `record_type_idx` recorded —
    // critical because eager registrations (`Option<Vector<T>>`,
    // `List<K>` for Map keys, etc.) interleave categories so the
    // per-collection iteration order no longer matches insertion
    // order.
    let mut entries: Vec<(u32, SubType)> = Vec::new();
    let mk_struct = |fields: Vec<wasm_encoder::FieldType>| SubType {
        is_final: true,
        supertype_idx: None,
        composite_type: CompositeType {
            inner: CompositeInnerType::Struct(StructType {
                fields: fields.into_boxed_slice(),
            }),
            shared: false,
            descriptor: None,
            describes: None,
        },
    };
    let mk_array = |elem: wasm_encoder::FieldType| SubType {
        is_final: true,
        supertype_idx: None,
        composite_type: CompositeType {
            inner: CompositeInnerType::Array(ArrayType(elem)),
            shared: false,
            descriptor: None,
            describes: None,
        },
    };
    // Records / variants — registered first in `TypeRegistry::build`,
    // idx assigned in source order. Look up the recorded idx for each.
    for item in items {
        match item {
            TopLevel::TypeDef(TypeDef::Product { name, fields, .. }) => {
                let st = record_struct_type(fields, registry)?;
                let idx = registry
                    .record_type_idx(name)
                    .ok_or(WasmGcError::Validation(format!(
                        "record `{name}` not registered"
                    )))?;
                entries.push((idx, mk_struct(st.fields.to_vec())));
            }
            TopLevel::TypeDef(TypeDef::Sum {
                name: parent,
                variants,
                ..
            }) => {
                for v in variants {
                    let mut fields = Vec::new();
                    for ty in &v.fields {
                        let val_ty = super::types::aver_to_wasm(ty, Some(registry))?.ok_or(
                            WasmGcError::Validation(format!(
                                "variant `{}` field of type {ty} has no wasm representation",
                                v.name
                            )),
                        )?;
                        fields.push(wasm_encoder::FieldType {
                            element_type: wasm_encoder::StorageType::Val(val_ty),
                            mutable: false,
                        });
                    }
                    // Look up by (parent, variant) so two sumtypes
                    // sharing a bare variant name (e.g. payment_ops's
                    // `Query.ProviderSummary` and `QueryOutput.
                    // ProviderSummary`) each emit their own struct
                    // type idx with their own field shape — instead of
                    // both nadpisując the same entry under the `bare`
                    // key.
                    let info =
                        registry
                            .variant_in(parent, &v.name)
                            .ok_or(WasmGcError::Validation(format!(
                                "variant `{parent}.{}` not registered",
                                v.name
                            )))?;
                    entries.push((info.type_idx, mk_struct(fields)));
                }
            }
            _ => {}
        }
    }

    // String slot.
    if let Some(idx) = registry.string_array_type_idx {
        entries.push((
            idx,
            mk_array(wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::I8,
                mutable: true,
            }),
        ));
    }

    // Vector<T> instantiations.
    for canonical in &registry.vector_order {
        let element =
            TypeRegistry::vector_element_type(canonical).ok_or(WasmGcError::Validation(
                format!("registered vector `{canonical}` has no parsable element type"),
            ))?;
        let elem_val =
            super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("Vector element type `{element}` has no wasm representation"),
            ))?;
        let idx = registry
            .vector_type_idx(canonical)
            .ok_or(WasmGcError::Validation(format!(
                "vector `{canonical}` not registered"
            )))?;
        entries.push((
            idx,
            mk_array(wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::Val(elem_val),
                mutable: true,
            }),
        ));
    }

    // `Result<T, E>` — `(struct (mut i32 tag) (mut T ok) (mut E err))`.
    // Unit on either side has no wasm value; we use a dummy `i32` slot
    // so the struct shape stays uniform. The slot is never read for
    // Unit-typed sides — pattern matching only inspects the tag and
    // unwraps the *other* side.
    for canonical in &registry.result_order {
        let (t_aver, e_aver) =
            TypeRegistry::result_te(canonical).ok_or(WasmGcError::Validation(format!(
                "registered result `{canonical}` has no parsable T, E"
            )))?;
        let t_val = super::types::aver_to_wasm(t_aver, Some(registry))?.unwrap_or(ValType::I32);
        let e_val = super::types::aver_to_wasm(e_aver, Some(registry))?.unwrap_or(ValType::I32);
        let idx = registry
            .result_type_idx(canonical)
            .ok_or(WasmGcError::Validation(format!(
                "result `{canonical}` not registered"
            )))?;
        entries.push((
            idx,
            mk_struct(vec![
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(ValType::I32),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(t_val),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(e_val),
                    mutable: true,
                },
            ]),
        ));
    }

    // `List<T>` — recursive Cons cell.
    for canonical in &registry.list_order {
        let element = TypeRegistry::list_element_type(canonical).ok_or(WasmGcError::Validation(
            format!("registered list `{canonical}` has no parsable element type"),
        ))?;
        let elem_val =
            super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("List element type `{element}` has no wasm representation"),
            ))?;
        let own_idx = registry
            .list_type_idx(canonical)
            .expect("just-registered list slot");
        let tail_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(own_idx),
        });
        entries.push((
            own_idx,
            mk_struct(vec![
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(elem_val),
                    mutable: false,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(tail_ref),
                    mutable: false,
                },
            ]),
        ));
    }

    // Option<T> — `(struct (mut i32 tag) (mut T value))`.
    for canonical in &registry.option_order {
        let element =
            TypeRegistry::option_element_type(canonical).ok_or(WasmGcError::Validation(
                format!("registered option `{canonical}` has no parsable element type"),
            ))?;
        let elem_val =
            super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("Option element type `{element}` has no wasm representation"),
            ))?;
        let idx = registry
            .option_type_idx(canonical)
            .ok_or(WasmGcError::Validation(format!(
                "option `{canonical}` not registered"
            )))?;
        entries.push((
            idx,
            mk_struct(vec![
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(ValType::I32),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(elem_val),
                    mutable: true,
                },
            ]),
        ));
    }

    // `Map<K, V>` — three wasm types per registered instantiation
    // (keys array, values array, map struct).
    for canonical in &registry.map_order {
        let (k_aver, v_aver) = super::types::parse_map_kv(canonical).ok_or(
            WasmGcError::Validation(format!("registered map `{canonical}` has no parsable K, V")),
        )?;
        let v_val =
            super::types::aver_to_wasm(v_aver, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("Map value type `{v_aver}` has no wasm representation"),
            ))?;
        // Keys array element: for primitive K, a `(ref null
        // $primitive_key_box_K)` so the empty-slot marker stays
        // uniform; for ref K (String / record), the K's own ref.
        let key_storage_val = if let Some(box_idx) = registry.primitive_key_box_idx(k_aver) {
            ValType::Ref(wasm_encoder::RefType {
                nullable: true,
                heap_type: wasm_encoder::HeapType::Concrete(box_idx),
            })
        } else {
            super::types::aver_to_wasm(k_aver, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("Map key type `{k_aver}` has no wasm representation"),
            ))?
        };
        let slots = registry
            .map_slots(canonical)
            .expect("just-registered map slots");
        entries.push((
            slots.keys_array,
            mk_array(wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::Val(key_storage_val),
                mutable: true,
            }),
        ));
        entries.push((
            slots.values_array,
            mk_array(wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::Val(v_val),
                mutable: true,
            }),
        ));
        let keys_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(slots.keys_array),
        });
        let values_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
            nullable: true,
            heap_type: wasm_encoder::HeapType::Concrete(slots.values_array),
        });
        entries.push((
            slots.map,
            mk_struct(vec![
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(ValType::I32),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(ValType::I32),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(keys_ref),
                    mutable: true,
                },
                wasm_encoder::FieldType {
                    element_type: wasm_encoder::StorageType::Val(values_ref),
                    mutable: true,
                },
            ]),
        ));
    }

    // Primitive map-key boxes — `(struct (mut K_val))` per
    // primitive K used as a Map<K, *>. Boxing primitive keys keeps
    // the open-addressing layout's `keys[i] == null` empty marker
    // uniform across all K kinds (raw i64/f64/i32 has no null).
    for k_aver in &registry.primitive_key_box_order {
        let k_val =
            super::types::aver_to_wasm(k_aver, Some(registry))?.ok_or(WasmGcError::Validation(
                format!("primitive key box: K=`{k_aver}` has no wasm representation"),
            ))?;
        let idx = registry
            .primitive_key_box_idx(k_aver)
            .ok_or(WasmGcError::Validation(format!(
                "primitive key box for `{k_aver}` not registered"
            )))?;
        entries.push((
            idx,
            mk_struct(vec![wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::Val(k_val),
                mutable: true,
            }]),
        ));
    }

    // `Tuple<A, B, ..., N>` — `(struct (mut A) (mut B) ... (mut N))`.
    // Variadic arity: 2-tuples used by Map.entries / Map.fromList /
    // List.zip; 3+ tuples used by user code (`scoreTriple`,
    // `scoreQuad`) and `(...)!` independent products.
    for canonical in &registry.tuple_order {
        let elems = TypeRegistry::tuple_elements(canonical).ok_or(WasmGcError::Validation(
            format!("registered tuple `{canonical}` has no parsable elements"),
        ))?;
        let mut fields: Vec<wasm_encoder::FieldType> = Vec::with_capacity(elems.len());
        for elem_aver in &elems {
            // Unit tuple element → i32 placeholder slot (same logic as
            // Result<Unit, E>): keeps the struct shape uniform; the
            // slot is never read because Unit has no observable value.
            let elem_val =
                super::types::aver_to_wasm(elem_aver, Some(registry))?.unwrap_or(ValType::I32);
            fields.push(wasm_encoder::FieldType {
                element_type: wasm_encoder::StorageType::Val(elem_val),
                mutable: true,
            });
        }
        let idx = registry
            .tuple_type_idx(canonical)
            .ok_or(WasmGcError::Validation(format!(
                "tuple `{canonical}` not registered"
            )))?;
        entries.push((idx, mk_struct(fields)));
    }

    // Built-in records (HttpRequest / HttpResponse / Tcp.Connection /
    // Terminal.Size) — registered with their own deferred idx.
    //
    // Skip names the user already redeclared with `record <Name>` —
    // the items pass above pushed their entry with the same registry
    // idx, so a second push from the builtin pass would duplicate the
    // struct in the rec group and slide every subsequent type index
    // up by one. Validator then complains "type index N is not a
    // function type" because effect imports / fn types end up
    // referring to the duplicated user-record slots instead of the
    // function-type slots they reserved.
    let user_record_names: std::collections::HashSet<&str> = items
        .iter()
        .filter_map(|item| match item {
            TopLevel::TypeDef(TypeDef::Product { name, .. }) => Some(name.as_str()),
            _ => None,
        })
        .collect();
    for record in crate::codegen::builtin_records::BUILTIN_RECORDS {
        if !registry.records.contains_key(record.aver_name) {
            continue;
        }
        if user_record_names.contains(record.aver_name) {
            continue;
        }
        let fields = registry
            .record_fields
            .get(record.aver_name)
            .expect("builtin record registered without fields");
        let st = super::types::record_struct_type(fields, registry)?;
        let idx = registry
            .record_type_idx(record.aver_name)
            .ok_or(WasmGcError::Validation(format!(
                "builtin record `{}` not registered",
                record.aver_name
            )))?;
        entries.push((idx, mk_struct(st.fields.to_vec())));
    }

    // Sort entries by registry-recorded type idx so the rec-group
    // emit position matches every recorded `*_type_idx` lookup. The
    // sort is stable; equal idx values would mean a registry bug.
    entries.sort_by_key(|(idx, _)| *idx);
    let subtypes: Vec<SubType> = entries.into_iter().map(|(_, t)| t).collect();

    // The rec group counts as ONE type-section entry (single 0x4e
    // prefix + N subtypes), so route through `ty()` which advances
    // `num_added` by 1 for the whole group.
    types.ty().rec(subtypes);
    Ok(())
}

/// Walk a fn body looking for dotted builtin calls and register each
/// unique one in `registry`. Discovery happens once per module before
/// any wasm bytes get emitted, so slot allocation can run with the
/// full set known.
fn discover_builtins_in_fn(
    fd: &FnDef,
    builtins: &mut BuiltinRegistry,
    effects: &mut EffectRegistry,
    eq_helpers: &mut EqHelperRegistry,
    type_registry: &TypeRegistry,
) {
    let crate::ast::FnBody::Block(stmts) = fd.body.as_ref();
    for stmt in stmts {
        discover_builtins_in_stmt(stmt, builtins, effects, eq_helpers, type_registry);
    }
}

fn discover_builtins_in_stmt(
    stmt: &Stmt,
    builtins: &mut BuiltinRegistry,
    effects: &mut EffectRegistry,
    eq_helpers: &mut EqHelperRegistry,
    type_registry: &TypeRegistry,
) {
    match stmt {
        Stmt::Binding(_, _, e) | Stmt::Expr(e) => {
            discover_builtins_in_expr(&e.node, builtins, effects, eq_helpers, type_registry)
        }
    }
}

/// Recursively walks `t` and registers every nominal record/sum it
/// reaches in `eq_helpers`. Needed for `==` on collection types
/// whose element/key/value type is nominal — `List<Tree>`,
/// `Map<Color, Tree>`, `Option<Box>`, etc. Without this, the
/// helper-body emit (`emit_list_eq`, `emit_record_eq_inline`,
/// `emit_eq_record`) would dispatch by `Call(__eq_<Tree>)` against
/// an unregistered slot.
fn register_nominal_in_type(
    t: &AverType,
    eq_helpers: &mut EqHelperRegistry,
    type_registry: &super::types::TypeRegistry,
) {
    let canonical: String = t.display().chars().filter(|c| !c.is_whitespace()).collect();
    match t {
        AverType::Named(name) => {
            if type_registry.record_fields.contains_key(name) {
                eq_helpers.register_transitive(name, EqKind::Record, type_registry);
            } else if type_registry
                .variants
                .values()
                .flat_map(|v| v.iter())
                .any(|v| &v.parent == name)
            {
                eq_helpers.register_transitive(name, EqKind::Sum, type_registry);
            }
        }
        AverType::Option(inner) => {
            eq_helpers.register_transitive(&canonical, EqKind::OptionEq, type_registry);
            register_nominal_in_type(inner, eq_helpers, type_registry);
        }
        AverType::Result(ok, err) => {
            eq_helpers.register_transitive(&canonical, EqKind::ResultEq, type_registry);
            register_nominal_in_type(ok, eq_helpers, type_registry);
            register_nominal_in_type(err, eq_helpers, type_registry);
        }
        AverType::Tuple(items) => {
            eq_helpers.register_transitive(&canonical, EqKind::TupleEq, type_registry);
            for item in items {
                register_nominal_in_type(item, eq_helpers, type_registry);
            }
        }
        AverType::List(inner) | AverType::Vector(inner) => {
            register_nominal_in_type(inner, eq_helpers, type_registry);
        }
        AverType::Map(k, v) => {
            register_nominal_in_type(k, eq_helpers, type_registry);
            register_nominal_in_type(v, eq_helpers, type_registry);
        }
        _ => {}
    }
}

fn discover_builtins_in_expr(
    expr: &Expr,
    builtins: &mut BuiltinRegistry,
    effects: &mut EffectRegistry,
    eq_helpers: &mut EqHelperRegistry,
    type_registry: &TypeRegistry,
) {
    use crate::ast::StrPart;
    match expr {
        Expr::FnCall(callee, args) => {
            if let Expr::Attr(_parent, member) = &callee.node
                && let Some(parent_name) = expr_to_dotted_head(&callee.node)
            {
                let dotted = format!("{parent_name}.{member}");
                if let Some(name) = BuiltinName::from_dotted(&dotted) {
                    builtins.register(name);
                }
                if let Some(name) = EffectName::from_dotted(&dotted) {
                    effects.register(name);
                }
                // `Args.get()` (no args, returns List<String>) lowers
                // inline as `args_len + loop args_get(i) cons` — no
                // single host import. Force-register both effects here
                // so `emit_args_get_inline` can look them up by name.
                if dotted == "Args.get" && args.is_empty() {
                    effects.register(EffectName::ArgsLen);
                    effects.register(EffectName::ArgsGet);
                }
                // `Int.mod` lowers to a per-site `i64.rem_s` plus a
                // proxied `__int_mod_euclid` Call to fold the negative
                // result back into `[0, |b|)`. The helper isn't a
                // surface builtin (no `from_dotted` mapping); register
                // explicitly here whenever discovery hits an `Int.mod`
                // call. Both the unfused Result-wrap shape and the
                // fused `Result.withDefault(Int.mod(...), default)`
                // shape need it.
                if dotted == "Int.mod" {
                    builtins.register(BuiltinName::IntModEuclid);
                }
            }
            discover_builtins_in_expr(&callee.node, builtins, effects, eq_helpers, type_registry);
            for arg in args {
                discover_builtins_in_expr(&arg.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::BinOp(op, l, r) => {
            // String `+` lowers to `__wasmgc_concat_n`; String `==`/`!=`
            // lower to `__wasmgc_string_eq`. Both helpers must be
            // registered up front so emit can `Call` them by index.
            // Read the operand type off the typed AST — Step 3 stamps
            // every node's `ty`.
            if let Some(t) = l.ty()
                && t.display().trim() == "String"
            {
                use crate::ast::BinOp as Op;
                match op {
                    Op::Add => builtins.register(BuiltinName::StringConcatN),
                    Op::Eq | Op::Neq => builtins.register(BuiltinName::StringEq),
                    Op::Lt | Op::Gt | Op::Lte | Op::Gte => {
                        builtins.register(BuiltinName::StringCompare);
                    }
                    _ => {}
                }
            }
            // Sum/record `==`/`!=` need a per-type `__eq_<TypeName>`
            // helper — register on discovery so the slot is allocated
            // before emit runs the BinOp dispatch.
            use crate::ast::BinOp as Op;
            if matches!(op, Op::Eq | Op::Neq)
                && let Some(t) = l.ty()
                && let AverType::Named(name) = t
            {
                if type_registry.record_fields.contains_key(name) {
                    eq_helpers.register_transitive(name, EqKind::Record, type_registry);
                } else if type_registry
                    .variants
                    .values()
                    .flat_map(|v| v.iter())
                    .any(|v| &v.parent == name)
                {
                    eq_helpers.register_transitive(name, EqKind::Sum, type_registry);
                }
            }
            // List / Vector / Map / Option / Result / Tuple `==` —
            // dispatch reaches the per-element/key __eq_<X> through
            // the helper bodies, so any nominal element type also
            // needs an __eq slot. Walk the operand type recursively
            // and register every nominal we hit.
            if matches!(op, Op::Eq | Op::Neq)
                && let Some(t) = l.ty()
            {
                register_nominal_in_type(t, eq_helpers, type_registry);
            }
            discover_builtins_in_expr(&l.node, builtins, effects, eq_helpers, type_registry);
            discover_builtins_in_expr(&r.node, builtins, effects, eq_helpers, type_registry);
        }
        Expr::Match { subject, arms } => {
            discover_builtins_in_expr(&subject.node, builtins, effects, eq_helpers, type_registry);
            // String-subject match (`match path { "/" -> ... }`)
            // needs `StringEq` to compare each non-default arm's
            // literal against the subject. Register it eagerly when
            // any arm is `Pattern::Literal(Str(_))`.
            if arms.iter().any(|a| {
                matches!(
                    &a.pattern,
                    crate::ast::Pattern::Literal(crate::ast::Literal::Str(_))
                )
            }) {
                builtins.register(BuiltinName::StringEq);
            }
            for arm in arms {
                discover_builtins_in_expr(
                    &arm.body.node,
                    builtins,
                    effects,
                    eq_helpers,
                    type_registry,
                );
            }
        }
        Expr::TailCall(boxed) => {
            for arg in &boxed.args {
                discover_builtins_in_expr(&arg.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::Attr(obj, _) => {
            discover_builtins_in_expr(&obj.node, builtins, effects, eq_helpers, type_registry)
        }
        Expr::ErrorProp(inner) => {
            discover_builtins_in_expr(&inner.node, builtins, effects, eq_helpers, type_registry)
        }
        Expr::Constructor(_, payload) => {
            if let Some(p) = payload.as_deref() {
                discover_builtins_in_expr(&p.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::RecordCreate { fields, .. } => {
            for (_, e) in fields {
                discover_builtins_in_expr(&e.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::RecordUpdate { base, updates, .. } => {
            discover_builtins_in_expr(&base.node, builtins, effects, eq_helpers, type_registry);
            for (_, e) in updates {
                discover_builtins_in_expr(&e.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        // `InterpolatedStr` lowers to `array.new_fixed` + the variadic
        // concat helper. Register it here so the helper's wasm fn
        // index is allocated by the time emission runs. Each Parsed
        // part may also need `String.fromInt` (if its type is Int) —
        // we conservatively register that too; unused registrations
        // are stripped by `wasm-opt -Oz`.
        Expr::InterpolatedStr(parts) => {
            // Variadic concat is mandatory; the per-type stringifiers
            // are registered conservatively whenever interpolation
            // exists in the program — unused registrations get DCE'd
            // by `wasm-opt -Oz`. Cheaper than a per-part type-driven
            // walk.
            builtins.register(BuiltinName::StringConcatN);
            builtins.register(BuiltinName::StringFromInt);
            builtins.register(BuiltinName::StringFromFloat);
            builtins.register(BuiltinName::StringFromBool);
            for p in parts {
                if let StrPart::Parsed(inner) = p {
                    discover_builtins_in_expr(
                        &inner.node,
                        builtins,
                        effects,
                        eq_helpers,
                        type_registry,
                    );
                }
            }
        }
        Expr::List(items) => {
            for item in items {
                discover_builtins_in_expr(&item.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::Tuple(items) => {
            for item in items {
                discover_builtins_in_expr(&item.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::IndependentProduct(items, _) => {
            // `?!` and `!` lower as sequential evaluation in wasm-gc,
            // but the recorder still needs the structural-scope
            // markers (`enter_group`, `set_branch`, `exit_group`) so
            // cross-backend traces from VM/self-host (which annotate
            // group_id / branch_path / effect_occurrence per effect)
            // line up with what wasm-gc emits. Eagerly register the
            // three host imports as soon as discovery sees an
            // independent product anywhere in the program.
            effects.register(EffectName::RecordEnterGroup);
            effects.register(EffectName::RecordSetBranch);
            effects.register(EffectName::RecordExitGroup);
            for item in items {
                discover_builtins_in_expr(&item.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        Expr::MapLiteral(entries) => {
            for (k, v) in entries {
                discover_builtins_in_expr(&k.node, builtins, effects, eq_helpers, type_registry);
                discover_builtins_in_expr(&v.node, builtins, effects, eq_helpers, type_registry);
            }
        }
        _ => {}
    }
}

/// True iff any reachable fn body calls `String.split` or `String.join`.
/// Used to gate registration of the (T=String) split/join helpers in
/// `lists::ListHelperRegistry::assign_slots`.
fn items_use_string_split_join(items: &[TopLevel]) -> bool {
    use crate::ast::{Expr, FnBody, Stmt};
    fn walk(e: &Expr) -> bool {
        match e {
            Expr::FnCall(callee, args) => {
                if let Expr::Attr(_parent, member) = &callee.node
                    && let Some(p) = expr_to_dotted_head(&callee.node)
                    && p == "String"
                    && (member == "split" || member == "join")
                {
                    return true;
                }
                walk(&callee.node) || args.iter().any(|a| walk(&a.node))
            }
            Expr::BinOp(_, l, r) => walk(&l.node) || walk(&r.node),
            Expr::Match { subject, arms } => {
                walk(&subject.node) || arms.iter().any(|a| walk(&a.body.node))
            }
            Expr::TailCall(boxed) => boxed.args.iter().any(|a| walk(&a.node)),
            Expr::Attr(obj, _) => walk(&obj.node),
            Expr::RecordCreate { fields, .. } => fields.iter().any(|(_, e)| walk(&e.node)),
            Expr::Constructor(_, payload) => {
                payload.as_deref().map(|p| walk(&p.node)).unwrap_or(false)
            }
            Expr::List(items) => items.iter().any(|x| walk(&x.node)),
            Expr::InterpolatedStr(_) => false,
            _ => false,
        }
    }
    for item in items {
        if let TopLevel::FnDef(fd) = item {
            let FnBody::Block(stmts) = fd.body.as_ref();
            for stmt in stmts {
                let e = match stmt {
                    Stmt::Binding(_, _, e) | Stmt::Expr(e) => &e.node,
                };
                if walk(e) {
                    return true;
                }
            }
        }
    }
    false
}

/// Extract `Parent` from an `Attr(Parent, _)` callee — the parent is
/// either an Ident or a Resolved local. Anything else (chained Attr,
/// fn call result) returns None and the dispatch falls through to a
/// regular fn call.
fn expr_to_dotted_head(expr: &Expr) -> Option<&str> {
    if let Expr::Attr(parent, _) = expr {
        match &parent.node {
            Expr::Ident(n) => Some(n.as_str()),
            Expr::Resolved { name, .. } => Some(name.as_str()),
            _ => None,
        }
    } else {
        None
    }
}

/// `__rt_list_string_cons(head, tail) -> list`. Lets the JS host
/// build a `(ref null $list_String)` from outside without going
/// through user code; used by the host bridge that satisfies
/// `request_headers_load`.
fn emit_list_string_cons(registry: &TypeRegistry) -> Result<wasm_encoder::Function, WasmGcError> {
    let list_idx = registry
        .list_type_idx("List<String>")
        .ok_or(WasmGcError::Validation(
            "list_cons helper requires List<String> slot".into(),
        ))?;
    let mut f = wasm_encoder::Function::new([]);
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::StructNew(list_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// Wasm-owned value factory exports. Effect imports that return
/// structured GC refs (`Option<String>`, records, `Result<T,E>`) can't
/// be implemented in JS directly because JS has no API to construct a
/// wasm-gc struct/variant. Instead, the binary exports per-type
/// constructor helpers; the host calls them and gets back a wasm-owned
/// ref it can hand straight to the importing code.
///
/// This is the same per-instantiation pattern as `__rt_string_from_lm`
/// and the per-(K,V) Map probes — pre-1.0 we ship one helper pair per
/// effect that needs it. Generic factories aren't worth the slot churn
/// while only three effects (`Terminal.readKey`, `Terminal.size`,
/// `Console.readLine`) cross the boundary with structured returns.
#[derive(Default)]
struct FactoryExports {
    /// `__rt_option_string_some(s)` / `__rt_option_string_none()` —
    /// emitted when `Terminal.readKey` is registered.
    opt_string_some: Option<FactorySlot>,
    opt_string_none: Option<FactorySlot>,
    /// `__rt_record_terminal_size_make(width, height)` — emitted when
    /// `Terminal.size` is registered.
    terminal_size_make: Option<FactorySlot>,
    /// `__rt_result_string_string_ok(s)` / `_err(s)` — emitted when
    /// `Console.readLine` (or any host effect that reports back a
    /// `Result<String, String>`, e.g. `Disk.readText`) is registered.
    result_string_string_ok: Option<FactorySlot>,
    result_string_string_err: Option<FactorySlot>,
    /// `__rt_result_unit_string_ok()` / `_err(s)` — emitted when any
    /// effect with a `Result<Unit, String>` return shape is registered
    /// (e.g. `Disk.writeText`, `Disk.delete`, `Tcp.close`).
    result_unit_string_ok: Option<FactorySlot>,
    result_unit_string_err: Option<FactorySlot>,
    /// `__rt_result_list_string_string_ok(list)` / `_err(s)` — emitted
    /// when an effect returning `Result<List<String>, String>` is
    /// registered (e.g. `Disk.listDir`).
    result_list_string_string_ok: Option<FactorySlot>,
    result_list_string_string_err: Option<FactorySlot>,
    /// `__rt_list_string_cons(head, tail) -> List<String>` /
    /// `__rt_list_string_nil() -> List<String>` — emitted when the
    /// host has to materialise a `List<String>` from the outside (the
    /// only case so far is `Disk.listDir`'s success arm).
    list_string_cons: Option<FactorySlot>,
    list_string_nil: Option<FactorySlot>,
    /// `__rt_record_tcp_connection_make(id, host, port)` — emitted
    /// when any `Tcp.*` effect is registered. The host hands the
    /// resulting record back as a Connection handle; subsequent
    /// `Tcp.writeLine / readLine / close` calls extract the `id`
    /// field on the host side to look up the underlying socket.
    tcp_connection_make: Option<FactorySlot>,
    /// `__rt_tcp_connection_id(c) -> String` — getter the host uses
    /// to recover the socket-pool key when dispatching writeLine /
    /// readLine / close.
    tcp_connection_id: Option<FactorySlot>,
    /// `__rt_result_tcp_connection_string_ok(c)` /
    /// `__rt_result_tcp_connection_string_err(e)` — emitted when
    /// `Tcp.connect` is registered.
    result_tcp_connection_string_ok: Option<FactorySlot>,
    result_tcp_connection_string_err: Option<FactorySlot>,
    /// `__rt_record_http_response_make(status, body, headers)` — emitted
    /// when any `Http.*` verb effect is registered.
    http_response_make: Option<FactorySlot>,
    /// `__rt_result_http_response_string_ok(r)` /
    /// `__rt_result_http_response_string_err(e)` — same gate.
    result_http_response_string_ok: Option<FactorySlot>,
    result_http_response_string_err: Option<FactorySlot>,
    /// `__rt_map_string_list_string_empty()` — empty headers map for
    /// the host to attach to its synthesised HttpResponse refs.
    map_string_list_string_empty: Option<FactorySlot>,
}

#[derive(Clone, Copy)]
struct FactorySlot {
    type_idx: u32,
    fn_idx: u32,
}

fn allocate_factory_exports(
    types: &mut TypeSection,
    next_type_idx: &mut u32,
    next_fn_idx: &mut u32,
    registry: &TypeRegistry,
    effect_registry: &EffectRegistry,
) -> Result<FactoryExports, WasmGcError> {
    let mut fx = FactoryExports::default();

    // Option<String> factories — driven by `Terminal.readKey`.
    if effect_registry
        .iter()
        .any(|e| e == EffectName::TerminalReadKey)
    {
        let opt_idx = registry
            .option_type_idx("Option<String>")
            .ok_or(WasmGcError::Validation(
                "Terminal.readKey factory requires Option<String> slot".into(),
            ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Terminal.readKey factory requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let opt_ref = ref_null(opt_idx);

        types.ty().function([s_ref], [opt_ref]);
        fx.opt_string_some = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([], [opt_ref]);
        fx.opt_string_none = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // Terminal.Size record factory — driven by `Terminal.size`.
    if effect_registry
        .iter()
        .any(|e| e == EffectName::TerminalSize)
    {
        let rec_idx = registry
            .record_type_idx("Terminal.Size")
            .ok_or(WasmGcError::Validation(
                "Terminal.size factory requires Terminal.Size record slot".into(),
            ))?;
        let rec_ref = ref_null(rec_idx);
        types.ty().function([ValType::I64, ValType::I64], [rec_ref]);
        fx.terminal_size_make = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // Result<String,String> factories — driven by any effect whose
    // host impl yields back a `Result<String, String>`.
    let needs_result_string_string = effect_registry.iter().any(|e| {
        matches!(
            e,
            EffectName::ConsoleReadLine
                | EffectName::DiskReadText
                | EffectName::TcpReadLine
                | EffectName::TcpSend
        )
    });
    if needs_result_string_string {
        let res_idx =
            registry
                .result_type_idx("Result<String,String>")
                .ok_or(WasmGcError::Validation(
                    "Result<String,String> factory required but slot not registered".into(),
                ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Result<String,String> factory requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let res_ref = ref_null(res_idx);

        types.ty().function([s_ref], [res_ref]);
        fx.result_string_string_ok = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref], [res_ref]);
        fx.result_string_string_err = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // Result<Unit, String> factories — Disk.{writeText, appendText,
    // delete, deleteDir, makeDir} all yield this shape; same for the
    // shape-equivalent Tcp.{writeLine, close, ping} effects.
    let needs_result_unit_string = effect_registry.iter().any(|e| {
        matches!(
            e,
            EffectName::DiskWriteText
                | EffectName::DiskAppendText
                | EffectName::DiskDelete
                | EffectName::DiskDeleteDir
                | EffectName::DiskMakeDir
                | EffectName::TcpWriteLine
                | EffectName::TcpClose
                | EffectName::TcpPing
        )
    });
    if needs_result_unit_string {
        let res_idx =
            registry
                .result_type_idx("Result<Unit,String>")
                .ok_or(WasmGcError::Validation(
                    "Result<Unit,String> factory required but slot not registered".into(),
                ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Result<Unit,String> factory requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let res_ref = ref_null(res_idx);

        types.ty().function([], [res_ref]);
        fx.result_unit_string_ok = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref], [res_ref]);
        fx.result_unit_string_err = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // Tcp.Connection record + Result<Tcp.Connection, String> — driven
    // by any Tcp.* effect (connect returns one; the rest consume one).
    let needs_tcp_connection = effect_registry.iter().any(|e| {
        matches!(
            e,
            EffectName::TcpConnect
                | EffectName::TcpWriteLine
                | EffectName::TcpReadLine
                | EffectName::TcpClose
        )
    });
    if needs_tcp_connection {
        let rec_idx = registry
            .record_type_idx("Tcp.Connection")
            .ok_or(WasmGcError::Validation(
                "Tcp.connect factory requires Tcp.Connection record slot".into(),
            ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Tcp.connect factory requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let rec_ref = ref_null(rec_idx);

        types.ty().function([s_ref, s_ref, ValType::I64], [rec_ref]);
        fx.tcp_connection_make = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([rec_ref], [s_ref]);
        fx.tcp_connection_id = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }
    if effect_registry
        .iter()
        .any(|e| matches!(e, EffectName::TcpConnect))
    {
        let res_idx = registry
            .result_type_idx("Result<Tcp.Connection,String>")
            .ok_or(WasmGcError::Validation(
                "Tcp.connect requires Result<Tcp.Connection,String> slot".into(),
            ))?;
        let rec_idx = registry
            .record_type_idx("Tcp.Connection")
            .ok_or(WasmGcError::Validation(
                "Tcp.connect requires Tcp.Connection record slot".into(),
            ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Tcp.connect requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let rec_ref = ref_null(rec_idx);
        let res_ref = ref_null(res_idx);

        types.ty().function([rec_ref], [res_ref]);
        fx.result_tcp_connection_string_ok = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref], [res_ref]);
        fx.result_tcp_connection_string_err = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // HTTP response factories — driven by any verb effect.
    let needs_http_response = effect_registry.iter().any(|e| {
        matches!(
            e,
            EffectName::HttpGet
                | EffectName::HttpHead
                | EffectName::HttpDelete
                | EffectName::HttpPost
                | EffectName::HttpPut
                | EffectName::HttpPatch
        )
    });
    if needs_http_response {
        let res_idx = registry
            .result_type_idx("Result<HttpResponse,String>")
            .ok_or(WasmGcError::Validation(
                "Http.* requires Result<HttpResponse,String> slot".into(),
            ))?;
        let rec_idx = registry
            .record_type_idx("HttpResponse")
            .ok_or(WasmGcError::Validation(
                "Http.* requires HttpResponse record slot".into(),
            ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Http.* requires String slot".into(),
            ))?;
        let map_slots =
            registry
                .map_slots("Map<String,List<String>>")
                .ok_or(WasmGcError::Validation(
                    "Http.* requires Map<String,List<String>> slot".into(),
                ))?;
        let s_ref = ref_null(s_idx);
        let rec_ref = ref_null(rec_idx);
        let res_ref = ref_null(res_idx);
        let map_ref = ref_null(map_slots.map);
        let keys_ref = ref_null(map_slots.keys_array);
        let values_ref = ref_null(map_slots.values_array);
        let _ = (keys_ref, values_ref);

        types
            .ty()
            .function([ValType::I64, s_ref, map_ref], [rec_ref]);
        fx.http_response_make = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([rec_ref], [res_ref]);
        fx.result_http_response_string_ok = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref], [res_ref]);
        fx.result_http_response_string_err = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([], [map_ref]);
        fx.map_string_list_string_empty = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    // Result<List<String>, String> + List<String> builders — driven by
    // `Disk.listDir`.
    let needs_list_string_pair = effect_registry
        .iter()
        .any(|e| matches!(e, EffectName::DiskListDir));
    if needs_list_string_pair {
        let res_idx = registry
            .result_type_idx("Result<List<String>,String>")
            .ok_or(WasmGcError::Validation(
                "Result<List<String>,String> factory required but slot not registered".into(),
            ))?;
        let list_idx = registry
            .list_type_idx("List<String>")
            .ok_or(WasmGcError::Validation(
                "Result<List<String>,String> factory requires List<String> slot".into(),
            ))?;
        let s_idx = registry
            .string_array_type_idx
            .ok_or(WasmGcError::Validation(
                "Result<List<String>,String> factory requires String slot".into(),
            ))?;
        let s_ref = ref_null(s_idx);
        let list_ref = ref_null(list_idx);
        let res_ref = ref_null(res_idx);

        types.ty().function([list_ref], [res_ref]);
        fx.result_list_string_string_ok = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref], [res_ref]);
        fx.result_list_string_string_err = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([s_ref, list_ref], [list_ref]);
        fx.list_string_cons = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;

        types.ty().function([], [list_ref]);
        fx.list_string_nil = Some(FactorySlot {
            type_idx: *next_type_idx,
            fn_idx: *next_fn_idx,
        });
        *next_type_idx += 1;
        *next_fn_idx += 1;
    }

    Ok(fx)
}

fn ref_null(type_idx: u32) -> ValType {
    ValType::Ref(wasm_encoder::RefType {
        nullable: true,
        heap_type: wasm_encoder::HeapType::Concrete(type_idx),
    })
}

impl FactoryExports {
    fn emit_function_entries(&self, funcs: &mut FunctionSection) {
        for slot in self.iter_slots() {
            funcs.function(slot.type_idx);
        }
    }

    fn emit_exports(&self, exports: &mut ExportSection) {
        if let Some(s) = self.opt_string_some {
            exports.export("__rt_option_string_some", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.opt_string_none {
            exports.export("__rt_option_string_none", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.terminal_size_make {
            exports.export("__rt_record_terminal_size_make", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_string_string_ok {
            exports.export("__rt_result_string_string_ok", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_string_string_err {
            exports.export("__rt_result_string_string_err", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_unit_string_ok {
            exports.export("__rt_result_unit_string_ok", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_unit_string_err {
            exports.export("__rt_result_unit_string_err", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_list_string_string_ok {
            exports.export(
                "__rt_result_list_string_string_ok",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.result_list_string_string_err {
            exports.export(
                "__rt_result_list_string_string_err",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.list_string_cons {
            exports.export("__rt_list_string_cons", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.list_string_nil {
            exports.export("__rt_list_string_nil", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.tcp_connection_make {
            exports.export(
                "__rt_record_tcp_connection_make",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.tcp_connection_id {
            exports.export("__rt_tcp_connection_id", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_tcp_connection_string_ok {
            exports.export(
                "__rt_result_tcp_connection_string_ok",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.result_tcp_connection_string_err {
            exports.export(
                "__rt_result_tcp_connection_string_err",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.http_response_make {
            exports.export("__rt_record_http_response_make", ExportKind::Func, s.fn_idx);
        }
        if let Some(s) = self.result_http_response_string_ok {
            exports.export(
                "__rt_result_http_response_string_ok",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.result_http_response_string_err {
            exports.export(
                "__rt_result_http_response_string_err",
                ExportKind::Func,
                s.fn_idx,
            );
        }
        if let Some(s) = self.map_string_list_string_empty {
            exports.export(
                "__rt_map_string_list_string_empty",
                ExportKind::Func,
                s.fn_idx,
            );
        }
    }

    fn emit_bodies(
        &self,
        codes: &mut CodeSection,
        registry: &TypeRegistry,
    ) -> Result<(), WasmGcError> {
        if self.opt_string_some.is_some() {
            codes.function(&emit_factory_option_string_some(registry)?);
        }
        if self.opt_string_none.is_some() {
            codes.function(&emit_factory_option_string_none(registry)?);
        }
        if self.terminal_size_make.is_some() {
            codes.function(&emit_factory_terminal_size_make(registry)?);
        }
        if self.result_string_string_ok.is_some() {
            codes.function(&emit_factory_result_string_string_ok(registry)?);
        }
        if self.result_string_string_err.is_some() {
            codes.function(&emit_factory_result_string_string_err(registry)?);
        }
        if self.result_unit_string_ok.is_some() {
            codes.function(&emit_factory_result_unit_string_ok(registry)?);
        }
        if self.result_unit_string_err.is_some() {
            codes.function(&emit_factory_result_unit_string_err(registry)?);
        }
        if self.result_list_string_string_ok.is_some() {
            codes.function(&emit_factory_result_list_string_string_ok(registry)?);
        }
        if self.result_list_string_string_err.is_some() {
            codes.function(&emit_factory_result_list_string_string_err(registry)?);
        }
        if self.list_string_cons.is_some() {
            codes.function(&emit_factory_list_string_cons(registry)?);
        }
        if self.list_string_nil.is_some() {
            codes.function(&emit_factory_list_string_nil(registry)?);
        }
        if self.tcp_connection_make.is_some() {
            codes.function(&emit_factory_tcp_connection_make(registry)?);
        }
        if self.tcp_connection_id.is_some() {
            codes.function(&emit_factory_tcp_connection_id(registry)?);
        }
        if self.result_tcp_connection_string_ok.is_some() {
            codes.function(&emit_factory_result_tcp_connection_string_ok(registry)?);
        }
        if self.result_tcp_connection_string_err.is_some() {
            codes.function(&emit_factory_result_tcp_connection_string_err(registry)?);
        }
        if self.http_response_make.is_some() {
            codes.function(&emit_factory_http_response_make(registry)?);
        }
        if self.result_http_response_string_ok.is_some() {
            codes.function(&emit_factory_result_http_response_string_ok(registry)?);
        }
        if self.result_http_response_string_err.is_some() {
            codes.function(&emit_factory_result_http_response_string_err(registry)?);
        }
        if self.map_string_list_string_empty.is_some() {
            codes.function(&emit_factory_map_string_list_string_empty(registry)?);
        }
        Ok(())
    }

    fn iter_slots(&self) -> impl Iterator<Item = FactorySlot> + '_ {
        [
            self.opt_string_some,
            self.opt_string_none,
            self.terminal_size_make,
            self.result_string_string_ok,
            self.result_string_string_err,
            self.result_unit_string_ok,
            self.result_unit_string_err,
            self.result_list_string_string_ok,
            self.result_list_string_string_err,
            self.list_string_cons,
            self.list_string_nil,
            self.tcp_connection_make,
            self.tcp_connection_id,
            self.result_tcp_connection_string_ok,
            self.result_tcp_connection_string_err,
            self.http_response_make,
            self.result_http_response_string_ok,
            self.result_http_response_string_err,
            self.map_string_list_string_empty,
        ]
        .into_iter()
        .flatten()
    }
}

fn emit_factory_option_string_some(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let opt_idx = registry
        .option_type_idx("Option<String>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(opt_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_option_string_none(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let opt_idx = registry
        .option_type_idx("Option<String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(opt_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_terminal_size_make(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let rec_idx = registry
        .record_type_idx("Terminal.Size")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // params (width: i64, height: i64) → struct in declaration order.
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::StructNew(rec_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_string_string_ok(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<String,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // Result layout matches `emit_result_constructor`: tag, T, E.
    // Ok: tag=1, payload=arg, E=null.
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_string_string_err(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<String,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // Err: tag=0, T=null, payload=arg.
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// `Result<Unit, String>::Ok(())` factory — Unit lowers to the i32
/// placeholder slot in the Result struct.
fn emit_factory_result_unit_string_ok(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<Unit,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // tag=1, T=i32 placeholder, E=null
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_unit_string_err(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<Unit,String>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // tag=0, T=i32 placeholder, E=arg
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_list_string_string_ok(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<List<String>,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // tag=1, T=arg (List<String> ref), E=null
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_list_string_string_err(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<List<String>,String>")
        .expect("checked at allocation");
    let list_idx = registry
        .list_type_idx("List<String>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    // tag=0, T=null List<String>, E=arg
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        list_idx,
    )));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// `__rt_list_string_cons(head, tail) -> List<String>`. Same struct
/// shape as user-emitted Cons cells (head field, tail ref).
fn emit_factory_list_string_cons(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let list_idx = registry
        .list_type_idx("List<String>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::StructNew(list_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_list_string_nil(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let list_idx = registry
        .list_type_idx("List<String>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        list_idx,
    )));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// `Tcp.Connection { id, host, port }` factory. Field order must
/// match the declaration in `builtin_records::TCP_CONNECTION`.
fn emit_factory_tcp_connection_make(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let rec_idx = registry
        .record_type_idx("Tcp.Connection")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::StructNew(rec_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// `__rt_tcp_connection_id(c)` — read field 0 of the record.
fn emit_factory_tcp_connection_id(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let rec_idx = registry
        .record_type_idx("Tcp.Connection")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::RefCastNonNull(
        wasm_encoder::HeapType::Concrete(rec_idx),
    ));
    f.instruction(&Instruction::StructGet {
        struct_type_index: rec_idx,
        field_index: 0,
    });
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_tcp_connection_string_ok(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<Tcp.Connection,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_tcp_connection_string_err(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<Tcp.Connection,String>")
        .expect("checked at allocation");
    let rec_idx = registry
        .record_type_idx("Tcp.Connection")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        rec_idx,
    )));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// `HttpResponse { status, body, headers }` factory.
fn emit_factory_http_response_make(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let rec_idx = registry
        .record_type_idx("HttpResponse")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::StructNew(rec_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_http_response_string_ok(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<HttpResponse,String>")
        .expect("checked at allocation");
    let s_idx = registry
        .string_array_type_idx
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        s_idx,
    )));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

fn emit_factory_result_http_response_string_err(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let res_idx = registry
        .result_type_idx("Result<HttpResponse,String>")
        .expect("checked at allocation");
    let rec_idx = registry
        .record_type_idx("HttpResponse")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        rec_idx,
    )));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::StructNew(res_idx));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// Empty `Map<String, List<String>>`. The map struct layout is `(size:
/// i32, cap: i32, keys_ref, values_ref)` per `MapSlots` — produce an
/// all-zero / null-ref map.
fn emit_factory_map_string_list_string_empty(
    registry: &TypeRegistry,
) -> Result<wasm_encoder::Function, WasmGcError> {
    let slots = registry
        .map_slots("Map<String,List<String>>")
        .expect("checked at allocation");
    let mut f = Function::new([]);
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        slots.keys_array,
    )));
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
        slots.values_array,
    )));
    f.instruction(&Instruction::StructNew(slots.map));
    f.instruction(&Instruction::End);
    Ok(f)
}

/// Slots reserved for the synthesised `aver_http_handle` wrapper.
struct HandlerWrapper {
    /// Position of the user's `(HttpRequest) -> HttpResponse` fn in
    /// `fn_defs`.
    user_handler_idx: usize,
    wrapper_type: u32,
    wrapper_fn: u32,
    /// Type + fn indices for `__rt_list_string_cons(head, tail) ->
    /// List<String>`. Lets the JS host build a `List<String>` from
    /// the outside (e.g. for the request-headers map's value lists).
    list_cons_type: u32,
    list_cons_fn: u32,
}

/// Synthesise the body of `aver_http_handle()`. Reads the request
/// fields via `Request.*` imports, allocates an `HttpRequest`,
/// invokes the user handler, walks the resulting `HttpResponse`'s
/// headers Map and dispatches one `Response.setHeader(name, value)`
/// per (key, value) pair before finalising via `Response.text(status,
/// body)`. Mirrors the `--bridge fetch` shape from the legacy
/// backend (`src/codegen/wasm/expr/emit.rs::emit_record_create`).
fn emit_handler_wrapper(
    registry: &TypeRegistry,
    fn_map: &super::body::FnMap,
    user_handler_wasm_idx: u32,
    caller_fn_idx: u32,
) -> Result<wasm_encoder::Function, WasmGcError> {
    use wasm_encoder::{BlockType, Function, HeapType, Instruction, RefType};

    let s_idx = registry
        .string_array_type_idx
        .ok_or(WasmGcError::Validation(
            "aver_http_handle wrapper requires String slot".into(),
        ))?;
    let req_idx = registry
        .records
        .get("HttpRequest")
        .copied()
        .ok_or(WasmGcError::Validation(
            "aver_http_handle wrapper requires HttpRequest record slot".into(),
        ))?;
    let resp_idx = registry
        .records
        .get("HttpResponse")
        .copied()
        .ok_or(WasmGcError::Validation(
            "aver_http_handle wrapper requires HttpResponse record slot".into(),
        ))?;
    let map_slots =
        registry
            .map_slots("Map<String,List<String>>")
            .ok_or(WasmGcError::Validation(
                "aver_http_handle wrapper requires `Map<String, List<String>>` slot".into(),
            ))?;
    let list_idx = registry
        .list_type_idx("List<String>")
        .ok_or(WasmGcError::Validation(
            "aver_http_handle wrapper requires `List<String>` slot".into(),
        ))?;

    let request_method_fn =
        fn_map
            .effects
            .get("Request.method")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Request.method effect not registered".into(),
            ))?;
    let request_url_fn =
        fn_map
            .effects
            .get("Request.url")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Request.url effect not registered".into(),
            ))?;
    let request_query_fn =
        fn_map
            .effects
            .get("Request.query")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Request.query effect not registered".into(),
            ))?;
    let request_body_fn =
        fn_map
            .effects
            .get("Request.body")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Request.body effect not registered".into(),
            ))?;
    let request_headers_load_fn =
        fn_map
            .effects
            .get("Request.headersLoad")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Request.headersLoad effect not registered".into(),
            ))?;
    let response_text_fn =
        fn_map
            .effects
            .get("Response.text")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Response.text effect not registered".into(),
            ))?;
    let response_set_header_fn =
        fn_map
            .effects
            .get("Response.setHeader")
            .copied()
            .ok_or(WasmGcError::Validation(
                "Response.setHeader effect not registered".into(),
            ))?;

    let s_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(s_idx),
    });
    let req_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(req_idx),
    });
    let resp_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(resp_idx),
    });
    let map_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(map_slots.map),
    });
    let keys_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(map_slots.keys_array),
    });
    let values_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(map_slots.values_array),
    });
    let list_ref = ValType::Ref(RefType {
        nullable: true,
        heap_type: HeapType::Concrete(list_idx),
    });

    // Locals layout (after the empty params):
    //  0=method, 1=url, 2=query, 3=body, 4=req_headers, 5=req,
    //  6=resp, 7=status, 8=resp_body, 9=resp_headers,
    // 10=keys_arr, 11=values_arr, 12=cap, 13=i,
    // 14=key, 15=values_list.
    let mut f = Function::new([
        (4, s_ref),
        (1, map_ref),
        (1, req_ref),
        (1, resp_ref),
        (1, ValType::I64),
        (1, s_ref),
        (1, map_ref),
        (1, keys_ref),
        (1, values_ref),
        (2, ValType::I32),
        (1, s_ref),
        (1, list_ref),
    ]);

    // Build HttpRequest from host effects. Each effect import has a
    // trailing `caller_fn_idx: i32` per the wasm-gc ABI (every host
    // import gained this in 0.16 for record/replay attribution); push
    // the wrapper's reserved idx as that arg.
    let push_caller = |f: &mut Function| {
        f.instruction(&Instruction::I32Const(caller_fn_idx as i32));
    };
    push_caller(&mut f);
    f.instruction(&Instruction::Call(request_method_fn));
    f.instruction(&Instruction::RefCastNullable(HeapType::Concrete(s_idx)));
    f.instruction(&Instruction::LocalSet(0));
    push_caller(&mut f);
    f.instruction(&Instruction::Call(request_url_fn));
    f.instruction(&Instruction::RefCastNullable(HeapType::Concrete(s_idx)));
    f.instruction(&Instruction::LocalSet(1));
    push_caller(&mut f);
    f.instruction(&Instruction::Call(request_query_fn));
    f.instruction(&Instruction::RefCastNullable(HeapType::Concrete(s_idx)));
    f.instruction(&Instruction::LocalSet(2));
    push_caller(&mut f);
    f.instruction(&Instruction::Call(request_body_fn));
    f.instruction(&Instruction::RefCastNullable(HeapType::Concrete(s_idx)));
    f.instruction(&Instruction::LocalSet(3));
    push_caller(&mut f);
    f.instruction(&Instruction::Call(request_headers_load_fn));
    f.instruction(&Instruction::LocalSet(4));

    // struct.new $http_request method url query body headers
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::LocalGet(3));
    f.instruction(&Instruction::LocalGet(4));
    f.instruction(&Instruction::StructNew(req_idx));
    f.instruction(&Instruction::LocalSet(5));

    // resp = handler(req)
    f.instruction(&Instruction::LocalGet(5));
    f.instruction(&Instruction::Call(user_handler_wasm_idx));
    f.instruction(&Instruction::LocalSet(6));

    // status = resp.status (i64)
    f.instruction(&Instruction::LocalGet(6));
    f.instruction(&Instruction::StructGet {
        struct_type_index: resp_idx,
        field_index: 0,
    });
    f.instruction(&Instruction::LocalSet(7));
    // resp_body = resp.body
    f.instruction(&Instruction::LocalGet(6));
    f.instruction(&Instruction::StructGet {
        struct_type_index: resp_idx,
        field_index: 1,
    });
    f.instruction(&Instruction::LocalSet(8));
    // resp_headers = resp.headers (Map ref)
    f.instruction(&Instruction::LocalGet(6));
    f.instruction(&Instruction::StructGet {
        struct_type_index: resp_idx,
        field_index: 2,
    });
    f.instruction(&Instruction::LocalSet(9));

    // Read map cap + arrays into iteration slots.
    f.instruction(&Instruction::LocalGet(9));
    f.instruction(&Instruction::StructGet {
        struct_type_index: map_slots.map,
        field_index: 1,
    });
    f.instruction(&Instruction::LocalSet(12));
    f.instruction(&Instruction::LocalGet(9));
    f.instruction(&Instruction::StructGet {
        struct_type_index: map_slots.map,
        field_index: 2,
    });
    f.instruction(&Instruction::LocalSet(10));
    f.instruction(&Instruction::LocalGet(9));
    f.instruction(&Instruction::StructGet {
        struct_type_index: map_slots.map,
        field_index: 3,
    });
    f.instruction(&Instruction::LocalSet(11));

    // i = 0
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::LocalSet(13));
    // outer block / loop over the keys array
    f.instruction(&Instruction::Block(BlockType::Empty));
    f.instruction(&Instruction::Loop(BlockType::Empty));
    // if i >= cap break
    f.instruction(&Instruction::LocalGet(13));
    f.instruction(&Instruction::LocalGet(12));
    f.instruction(&Instruction::I32GeU);
    f.instruction(&Instruction::BrIf(1));

    // key = keys_arr[i]
    f.instruction(&Instruction::LocalGet(10));
    f.instruction(&Instruction::LocalGet(13));
    f.instruction(&Instruction::ArrayGet(map_slots.keys_array));
    f.instruction(&Instruction::LocalSet(14));

    // if key non-null, walk values list
    f.instruction(&Instruction::LocalGet(14));
    f.instruction(&Instruction::RefIsNull);
    f.instruction(&Instruction::I32Eqz);
    f.instruction(&Instruction::If(BlockType::Empty));
    // values_list = values_arr[i]
    f.instruction(&Instruction::LocalGet(11));
    f.instruction(&Instruction::LocalGet(13));
    f.instruction(&Instruction::ArrayGet(map_slots.values_array));
    f.instruction(&Instruction::LocalSet(15));
    // Walk list: while not null: response_set_header(key, head); cur = tail.
    f.instruction(&Instruction::Block(BlockType::Empty));
    f.instruction(&Instruction::Loop(BlockType::Empty));
    f.instruction(&Instruction::LocalGet(15));
    f.instruction(&Instruction::RefIsNull);
    f.instruction(&Instruction::BrIf(1));
    // response_set_header(key, list.head, caller_fn_idx)
    f.instruction(&Instruction::LocalGet(14));
    f.instruction(&Instruction::LocalGet(15));
    f.instruction(&Instruction::StructGet {
        struct_type_index: list_idx,
        field_index: 0,
    });
    push_caller(&mut f);
    f.instruction(&Instruction::Call(response_set_header_fn));
    // cur = cur.tail
    f.instruction(&Instruction::LocalGet(15));
    f.instruction(&Instruction::StructGet {
        struct_type_index: list_idx,
        field_index: 1,
    });
    f.instruction(&Instruction::LocalSet(15));
    f.instruction(&Instruction::Br(0));
    f.instruction(&Instruction::End); // list loop
    f.instruction(&Instruction::End); // list block
    f.instruction(&Instruction::End); // if key non-null

    // i++
    f.instruction(&Instruction::LocalGet(13));
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::I32Add);
    f.instruction(&Instruction::LocalSet(13));
    f.instruction(&Instruction::Br(0));
    f.instruction(&Instruction::End); // outer loop
    f.instruction(&Instruction::End); // outer block

    // response_text(status, body, caller_fn_idx)
    f.instruction(&Instruction::LocalGet(7));
    f.instruction(&Instruction::LocalGet(8));
    push_caller(&mut f);
    f.instruction(&Instruction::Call(response_text_fn));

    f.instruction(&Instruction::End);
    Ok(f)
}

/// Wasm fn-type and fn-idx slots for the two `__rt_string_*` host
/// bridge exports plus the linear-memory transport buffer.
///
/// Why this exists: a JS host (e.g. Cloudflare Workers via
/// `tools/edge/`) can't directly allocate or read engine-managed
/// `(array i8)` refs without JS String Builtins (stage-4 standard,
/// not yet enabled on every host). Per-byte exports (one JS↔wasm
/// boundary crossing per byte) would dominate the workload — ~100 ns
/// per crossing × 50 KB body = 10 ms just for I/O, eclipsing the
/// actual fractal render. So we expose a tiny linear memory as a
/// bulk transport buffer and two bulk-copy helpers. JS writes a
/// UTF-8 buffer into the LM with `TextEncoder.encodeInto`, calls
/// `__rt_string_from_lm(len)` once to materialise it as a guest
/// `(array i8)`. For the return path, `__rt_string_to_lm(s)` copies
/// `s.len` bytes back to LM and returns the count; JS reads them
/// with `TextDecoder.decode(memory.subarray(0, len))`. One boundary
/// crossing per direction; the inner copy loop runs at native speed
/// inside wasm.
struct BridgeIndices {
    from_lm_type: u32,
    to_lm_type: u32,
    pages_type: u32,
    grow_type: u32,
    from_lm_fn: u32,
    to_lm_fn: u32,
    pages_fn: u32,
    grow_fn: u32,
}

struct BridgeTypeSlots {
    from_lm_type: u32,
    to_lm_type: u32,
    pages_type: u32,
    grow_type: u32,
}

fn emit_bridge_types(
    types: &mut TypeSection,
    registry: &TypeRegistry,
    next_type_idx: &mut u32,
) -> Result<BridgeTypeSlots, WasmGcError> {
    let s_idx = registry
        .string_array_type_idx
        .ok_or(WasmGcError::Validation(
            "bridge helpers require String slot to be allocated".into(),
        ))?;
    let s_ref = ValType::Ref(wasm_encoder::RefType {
        nullable: true,
        heap_type: wasm_encoder::HeapType::Concrete(s_idx),
    });
    // from_lm : (len: i32) -> string  (reads bytes from LM[0..len])
    types.ty().function([ValType::I32], [s_ref]);
    let from_lm = *next_type_idx;
    *next_type_idx += 1;
    // to_lm : (s: string) -> i32      (writes s into LM[0..s.len], returns s.len)
    types.ty().function([s_ref], [ValType::I32]);
    let to_lm = *next_type_idx;
    *next_type_idx += 1;
    // pages : () -> i32  (= memory.size, in 64 KiB pages)
    types.ty().function([], [ValType::I32]);
    let pages = *next_type_idx;
    *next_type_idx += 1;
    // grow : (pages: i32) -> i32  (= memory.grow result; -1 on fail)
    types.ty().function([ValType::I32], [ValType::I32]);
    let grow = *next_type_idx;
    *next_type_idx += 1;
    Ok(BridgeTypeSlots {
        from_lm_type: from_lm,
        to_lm_type: to_lm,
        pages_type: pages,
        grow_type: grow,
    })
}

fn emit_bridge_bodies(codes: &mut CodeSection, registry: &TypeRegistry) -> Result<(), WasmGcError> {
    let s_idx = registry
        .string_array_type_idx
        .expect("bridge bodies emitted only when string slot exists");
    let padding = wat_helper::padding_types(s_idx);

    // from_lm(len) → string. Allocate `(array i8)` of `len`, then
    // copy LM[0..len] byte-by-byte. Loop over `i32.load8_u` + `array.set`.
    let from_lm_wat = format!(
        r#"
        (module
          {padding}
          (type $string (array (mut i8)))
          (memory 1)
          (func (export "helper") (param $len i32) (result (ref null $string))
            (local $arr (ref null $string))
            (local $i i32)
            local.get $len
            array.new_default $string
            local.set $arr
            i32.const 0
            local.set $i
            (block $break
              (loop $next
                local.get $i
                local.get $len
                i32.ge_u
                br_if $break

                local.get $arr
                local.get $i
                local.get $i
                i32.load8_u
                array.set $string

                local.get $i
                i32.const 1
                i32.add
                local.set $i
                br $next))
            local.get $arr)
        )
    "#
    );
    codes.function(&wat_helper::compile_wat_helper(&from_lm_wat)?);

    // to_lm(s) → i32 (= s.len). Auto-grow memory if `s.len` exceeds
    // current LM capacity, then loop-write bytes to LM[0..s.len].
    let to_lm_wat = format!(
        r#"
        (module
          {padding}
          (type $string (array (mut i8)))
          (memory 1)
          (func (export "helper") (param $s (ref null $string)) (result i32)
            (local $len i32)
            (local $i i32)
            (local $needed i32)
            (local $current i32)
            local.get $s
            array.len
            local.set $len

            ;; needed = (len + 65535) >> 16
            local.get $len
            i32.const 65535
            i32.add
            i32.const 16
            i32.shr_u
            local.set $needed

            memory.size
            local.set $current

            local.get $needed
            local.get $current
            i32.gt_u
            (if
              (then
                local.get $needed
                local.get $current
                i32.sub
                memory.grow
                drop))

            i32.const 0
            local.set $i
            (block $break
              (loop $next
                local.get $i
                local.get $len
                i32.ge_u
                br_if $break

                local.get $i
                local.get $s
                local.get $i
                array.get_u $string
                i32.store8

                local.get $i
                i32.const 1
                i32.add
                local.set $i
                br $next))
            local.get $len)
        )
    "#
    );
    codes.function(&wat_helper::compile_wat_helper(&to_lm_wat)?);

    // pages() -> i32 (= memory.size). Trivially small; wasm-encoder.
    let mut pages = wasm_encoder::Function::new([]);
    pages.instruction(&Instruction::MemorySize(0));
    pages.instruction(&Instruction::End);
    codes.function(&pages);

    // grow(pages) -> i32 (= memory.grow result; -1 on fail).
    let mut grow = wasm_encoder::Function::new([]);
    grow.instruction(&Instruction::LocalGet(0));
    grow.instruction(&Instruction::MemoryGrow(0));
    grow.instruction(&Instruction::End);
    codes.function(&grow);
    Ok(())
}

fn validate(bytes: &[u8]) -> Result<(), WasmGcError> {
    use wasmparser::{Validator, WasmFeatures};

    let features = WasmFeatures::default()
        | WasmFeatures::GC
        | WasmFeatures::REFERENCE_TYPES
        | WasmFeatures::FUNCTION_REFERENCES
        | WasmFeatures::TAIL_CALL;
    let mut validator = Validator::new_with_features(features);
    validator
        .validate_all(bytes)
        .map_err(|e| WasmGcError::Validation(format!("{e}")))?;
    Ok(())
}