1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
//! 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 the MIR body emitter
//! (`body::emit_fn_body_via_mir`), with an `unreachable` trap stub
//! for the rare shape it doesn't cover (a first-class fn value with
//! no funcref-table slot — a builtin/variant `FnValue` or a
//! let-bound fn-value call).
//!
//! First-class `Fn` values lower to an `i32` dense index into a single
//! funcref table (table 0); `Fn`-param calls dispatch via
//! `call_indirect`. The Table section (after Function) sizes the table,
//! the Element section (after Export) initialises it, and the per-sig
//! `call_indirect` functypes are pre-registered in the Type section.
//!
//! Validation runs `wasmparser` with GC + tail-call features before
//! returning bytes.
use std::collections::HashMap;
use wasm_encoder::{
CodeSection, ConstExpr, DataCountSection, DataSection, ElementSection, Elements, EntityType,
ExportKind, ExportSection, Function, FunctionSection, ImportSection, Instruction, Module,
RefType, TableSection, TableType, 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>,
/// Phase 4 (0.20) — caches the `wasi:sockets/instance-network.
/// instance-network` handle for the program's lifetime. -1
/// sentinel = "not yet fetched". Populated when any Tcp.*
/// effect that needs a network capability is registered
/// (`Tcp.connect`, `Tcp.send`, `Tcp.ping`). Never dropped —
/// wasmtime releases at component exit.
network_handle: Option<u32>,
/// Phase 4 (0.20) — connection-pool array reference. Initialised
/// to `ref.null $tcp_pool` and lazy-allocated to
/// `array.new_default $tcp_pool 256` on the first call into the
/// connect/send pipeline. Holds `(ref null $tcp_slot)` entries
/// indexed by integer parsed out of `Tcp.Connection.id`
/// (`"tcp-N"`). Populated whenever the TCP pool slot type
/// (`tcp_pool_type_idx`) is allocated by `TypeRegistry`.
tcp_pool: Option<u32>,
/// Phase 4 (0.20) — monotonic counter for the next pool slot
/// allocation. Starts at `0`, bumps after each `Tcp.connect`
/// success. Wraps modulo 256 (pool capacity); a `Tcp.connect`
/// past 256 live connections will reuse a stale slot today —
/// good enough for v1, exhaustion handling lands as a follow-up
/// once the pipeline is real.
tcp_next_id: Option<u32>,
}
use super::body::hash_helpers::{HashHelperRegistry, HashKind};
use super::body::{FnEntry, FnMap, emit_fn_body_via_mir};
use super::builtins::{BuiltinName, BuiltinRegistry};
use super::effects::{EffectName, EffectRegistry};
use super::maps::MapHelperRegistry;
use super::types::{
TypeRegistry, param_types_with_repr, record_struct_type, return_results_with_repr,
};
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::{FnDef, TopLevel, TypeDef};
/// Emit a trap-stub body into `func`: just `unreachable; end`.
///
/// Used for the residual fn shapes the MIR body emitter doesn't cover.
/// First-class `Fn`-param dispatch now lowers to `call_indirect` on the
/// funcref table, so the only fns that still trap are those reaching a
/// first-class fn value with no table slot — a `FnValue` of a builtin /
/// variant, or a `LocalSlot` whose name is a let-bound fn value rather
/// than a `Fn` param. `unreachable` is a polymorphic stack-type
/// instruction, so it validates for ANY fn signature with zero extra
/// locals.
fn emit_trap_stub_body(func: &mut Function) {
func.instruction(&Instruction::Unreachable);
func.instruction(&Instruction::End);
}
pub(super) fn emit_module_with(
items: &[TopLevel],
handler_name: Option<&str>,
target: super::TargetMode,
) -> Result<(Vec<u8>, usize), WasmGcError> {
let fn_defs: Vec<&FnDef> = items
.iter()
.filter_map(|it| match it {
TopLevel::FnDef(fd) => Some(fd),
_ => None,
})
.collect();
let view = super::view::WasmGcLinkedView::build(items, &fn_defs)?;
let symbol_table = view.symbol_table;
let resolved_fn_defs = view.resolved_fn_defs;
let mut registry =
TypeRegistry::build_with_handler(items, &resolved_fn_defs, handler_name.is_some());
// Lower the post-link resolved fns to MIR and run the shared
// `optimize` pipeline — the SAME six passes the VM consumes
// (`ir::mir::optimize`). MIR is the only codegen path. Hoisted to
// before the type section so the address-taken-fn scan + the
// `call_indirect` functype pre-registration (first-class `Fn`
// support) can run while `next_type_idx` is still being assembled;
// the body-emit loop below reads it back.
//
// The body walk emits the optimized form for the variants it
// covers; the shape it does NOT cover is a let-bound first-class fn
// value or a builtin/variant `FnValue` (no funcref-table slot),
// for which it returns `None`. Such fns get a `unreachable`
// trap-stub body (`emit_trap_stub_body`).
// ETAP-2 carrier-`i64`: derive the per-carrier-type proven bound ONCE,
// up front. The wasm-gc input `items` is the already-FLATTENED program
// (`flatten_multimodule` inlined every dep into entry scope, mirroring
// this view's `SymbolTable::build(items, &[])`), so the carrier type +
// its smart constructor both live in `entry_items` and `dep_modules` is
// empty. The same table feeds (a) the MIR `bare_i64` rewrite (an
// optional per-slot raw-i64 perf path, gated off in this slice) AND (b)
// the type registry's `eligible_carriers` set, which is THE size lever:
// every eligible carrier erases to a native `i64` in `aver_to_wasm`. An
// empty table (no opaque-bounded carrier) keeps the pre-slice all-`Int`
// lowering byte-for-byte.
let carrier_intervals = {
let empty_prefixes: std::collections::HashSet<String> = std::collections::HashSet::new();
let empty_recursive: std::collections::HashSet<crate::ir::FnId> =
std::collections::HashSet::new();
let inputs = crate::codegen::proof_lower::ProofLowerInputs {
entry_items: items,
dep_modules: &[],
module_prefixes: &empty_prefixes,
recursive_fns: &empty_recursive,
symbol_table: &symbol_table,
program_shape: None,
};
crate::codegen::proof_lower::carrier_interval_table(&inputs)
};
// The codegen size lever: a carrier whose proven bound is recognized AND
// `fits_i64` erases to native `i64` everywhere it appears (slots, record
// fields, Option/Result payloads, `Vector<Carrier>` elements). A bound
// too wide for `i64` (or an unrecognized invariant, already omitted from
// the table upstream) is excluded here, so the carrier stays `$AverInt`.
//
// `AVER_NO_CARRIER_I64=1` is the differential / size-measurement escape
// hatch: it forces the all-`$AverInt` carrier representation (empty
// eligible set), so a coords-heavy toy can be compiled both ways to
// measure the struct-field size win, and any divergence the carrier path
// introduces can be bisected against the boxed baseline.
// Lower + optimize the resolved fns to MIR ONCE, up front — the typed MIR
// is the RESOLVED-IR source of truth for Map-key types: every node carries
// an `Option<Type>` stamp, so `discover_instantiations` surfaces every
// `Map<K, V>` the program actually uses, including ones with NO textual
// annotation (a local-binding `m: Map<…>` whose annotation Scan 2's string
// walk never reaches, or a fully INFERRED `m = Map.set({}, c, 5)`). The
// box/unbox boundary rewrite (`rewrite_for_wasm_gc`) is layered on top of
// THIS same `optimized` value below — building it here avoids a second
// lower+optimize pass while making the inferred Map-key types available to
// the carrier-eligibility scan.
let optimized_mir: crate::ir::mir::MirProgram = {
let mir_items: Vec<crate::ir::hir::ResolvedTopLevel> = resolved_fn_defs
.iter()
.cloned()
.map(crate::ir::hir::ResolvedTopLevel::FnDef)
.collect();
crate::ir::mir::optimize(crate::ir::mir::lower_program(&mir_items))
};
let eligible_carriers: std::collections::HashSet<String> =
if std::env::var("AVER_NO_CARRIER_I64").is_ok() {
std::collections::HashSet::new()
} else {
// Proven-bound candidates: the carrier's invariant is recognized
// AND `fits_i64`. This is necessary but NOT sufficient — it does
// not prove every value went through the gate, nor that the
// carrier's codegen is only exercised in positions the i64
// erasure supports.
let proven: std::collections::HashSet<String> = carrier_intervals
.iter()
.filter(|(_, (iv, known))| *known && iv.fits_i64())
.map(|(name, _)| name.clone())
.collect();
// Fail-closed tightening (unless explicitly disabled for a
// revert-test): subtract carriers that are constructed ungated
// (bare ctor bypass) or used as a `Map` KEY (direct/transitive).
// Either trip keeps that carrier BOXED, matching the VM and the
// pre-slice boxed wasm-gc path. `AVER_CARRIER_I64_SKIP_DEMOTION=1`
// restores the un-tightened set so the regression revert-tests
// can show the hole returning (trap / validation error).
if std::env::var("AVER_CARRIER_I64_SKIP_DEMOTION").is_ok() {
proven
} else {
let inputs = crate::codegen::proof_lower::ProofLowerInputs {
entry_items: items,
dep_modules: &[],
module_prefixes: &std::collections::HashSet::new(),
recursive_fns: &std::collections::HashSet::new(),
symbol_table: &symbol_table,
program_shape: None,
};
// RESOLVED-IR Map-key types: the typed-MIR instantiation
// registry carries every `Map<K, V>` the program uses, keyed
// off inference, so a carrier used as a Map KEY via a local
// binding OR pure inference (no annotation anywhere) is still
// demoted. This is the complete source of truth; the textual
// annotation scan inside `carrier_eligibility_demotions` stays
// as a cheap backstop.
let resolved_map_keys: Vec<crate::ast::Type> =
crate::ir::mir::discover_instantiations(&optimized_mir)
.maps
.into_iter()
.map(|(k, _v)| k)
.collect();
let demoted = crate::codegen::proof_lower::carrier_eligibility_demotions(
&inputs,
&proven,
&carrier_intervals,
&resolved_map_keys,
);
proven.difference(&demoted).cloned().collect()
}
};
// ETAP-2 carrier-`i64`: the per-slot raw-i64 carrier ARITHMETIC path (the
// `bare_i64` analysis + rewrite) must key off the SAME carrier set the
// registry's STORAGE erasure uses — `eligible_carriers`, i.e. the proven
// bound MINUS the fail-closed demotions (Map-key / bare-ctor) AND empty
// under `AVER_NO_CARRIER_I64=1`. Otherwise the analysis would flag a
// `.value` read raw (skip the project bridge) for a carrier the registry
// kept as `$AverInt` storage — reading an i64 from an `$AverInt` slot,
// a wasm validation error. So restrict the carrier table to the eligible
// names before threading it into the rewrite.
let bare_carrier_intervals: crate::ir::mir::bare_i64::CarrierIntervals = carrier_intervals
.iter()
.filter(|(name, _)| eligible_carriers.contains(name.as_str()))
.map(|(name, iv)| (name.clone(), *iv))
.collect();
registry.set_eligible_carriers(eligible_carriers);
// ETAP-2 multi-field carrier-`i64`: the per-`(record, field)` eligible
// table — a `Coord { x: Int, y: Int }` whose 2-arg smart ctor bounds each
// field. Each eligible field erases to a native `i64` struct field (the
// size lever, identical to the single-field-leaf composition). Computed
// here so the storage erasure (`record_struct_type` reads the registry's
// eligible-field set) AND the body-emit bridges (construct / direct-read)
// key off ONE table. Empty under `AVER_NO_CARRIER_I64=1` (the differential
// baseline) and on any program with no bounded multi-field record.
let field_carrier_intervals: crate::ir::mir::bare_i64::FieldCarrierIntervals =
if std::env::var("AVER_NO_CARRIER_I64").is_ok() {
crate::ir::mir::bare_i64::FieldCarrierIntervals::new()
} else {
let inputs = crate::codegen::proof_lower::ProofLowerInputs {
entry_items: items,
dep_modules: &[],
module_prefixes: &std::collections::HashSet::new(),
recursive_fns: &std::collections::HashSet::new(),
symbol_table: &symbol_table,
program_shape: None,
};
// The inference-complete instantiation registry (every `Map`,
// `List`, `Vector`, `Tuple`, `Option`, `Result` the program uses)
// drives the multi-field demotion: a bounded record used as a Map
// KEY, a Map VALUE, or any container element keeps all its fields
// boxed (its container-element/value codegen stores the boxed
// `$AverInt` record, so an i64-erased field fails wasm validation).
let instantiations = crate::ir::mir::discover_instantiations(&optimized_mir);
crate::codegen::proof_lower::field_carrier_eligible_intervals(&inputs, &instantiations)
};
let eligible_carrier_fields: std::collections::HashSet<(String, String)> =
field_carrier_intervals
.iter()
.filter(|(_, (iv, known))| *known && iv.fits_i64())
.map(|((rec, field), _)| (rec.clone(), field.clone()))
.collect();
registry.set_eligible_carrier_fields(eligible_carrier_fields);
let mir_program: crate::ir::mir::MirProgram = {
// Reuse the `optimized` MIR built above for carrier-eligibility
// Map-key discovery — the box/unbox boundary rewrite is the only
// step layered on top, and it does not change the type stamps the
// instantiation scan consumed.
let optimized = optimized_mir;
// ETAP-2 SLICE 2b: make Int representation EXPLICIT for the wasm-gc
// codegen. The rewrite tags each fn's bare slots / params / return on
// `MirFn::repr` and inserts `Box`/`Unbox` boundary nodes; the body
// emitter + signature path (gated by `ENABLE_BARE_SLOTS`) then flip a
// proven-bounded Int slot to a native `i64`. Unlike the Rust backend,
// wasm-gc lowers a mutual tail-call to a DIRECT `return_call` to the
// callee's own functype, so every member of a >1-fn recurrence cycle
// must agree on its bare signature — `mutual_recursion_box_set`
// over-approximates by boxing every such member (fail-closed). The
// analysis itself still bails to all-Boxed for multi-module /
// external-caller fragments (`bare_i64::analyze`), so a dependency
// fragment never goes bare.
let boxed =
crate::ir::mir::optimize::bare_i64_rewrite::mutual_recursion_box_set(&optimized);
// The eligible-carrier bound (`bare_carrier_intervals`) seeds the MIR
// rewrite's per-slot raw-i64 carrier path (`CARRIER_BARE_ELIGIBLE ==
// true`): a bare carrier's `.value` reads native i64 and arithmetic
// over it runs as `i64.add/sub/mul` where the interval fixpoint proves
// the result fits i64. Restricted to the registry's eligible set above,
// so the analysis never goes raw for a carrier the storage kept boxed.
crate::ir::mir::optimize::bare_i64_rewrite::rewrite_for_wasm_gc(
optimized,
&boxed,
&bare_carrier_intervals,
&field_carrier_intervals,
)
};
// 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());
// 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 &resolved_fn_defs {
discover_builtins_in_fn(
fd,
&mut builtin_registry,
&mut effect_registry,
&mut eq_helpers_registry,
®istry,
&symbol_table,
);
}
// bignum slice 1 — when the opt-in `$AverInt` representation is
// active, register the full arithmetic prelude. Registration is
// unconditional (not per-op-discovered) because the literal /
// BinOp / Neg re-point sites all assume these fn indices exist;
// `wasm-opt -Oz` strips any helper a given program never reaches.
if registry.bignum {
for b in [
// Shared sub-routines FIRST, so the arithmetic helpers that `call`
// them have a known fn index. `wasm-opt -Oz` DCEs any a given
// program never reaches.
BuiltinName::AintDecompose,
BuiltinName::AintNormalize,
BuiltinName::AintStrip,
BuiltinName::AintUmagCmp,
BuiltinName::AintFromI64,
BuiltinName::AintAdd,
BuiltinName::AintSub,
BuiltinName::AintMul,
BuiltinName::AintNeg,
BuiltinName::AintAbs,
BuiltinName::AintDivmod,
BuiltinName::AintCmp,
BuiltinName::AintEq,
// slice 4 (eq+hash gap) — value hash agreeing with `__aint_eq`,
// for Map/Set Int keys and record/sum Int fields (the inline
// `i32.wrap_i64` over a raw value is invalid on an `$aint` ref,
// and collision-collapses every Big to one bucket).
BuiltinName::AintHash,
// slice 3 — decimal parse / Float bridges / index extraction.
// Registered alongside the arithmetic prelude so the conversion
// + index re-point sites can assume the fn indices exist; -Oz
// strips the unused ones.
BuiltinName::AintToF64,
BuiltinName::AintFromF64,
BuiltinName::AintToIndex,
// Saturating Int→i64 lowering for an Int ARGUMENT into an
// i64-typed builtin slot (`List.take`/`drop` counts,
// `String.charAt`/`slice` indices, `Char.fromCode`).
BuiltinName::AintToI64Sat,
// CHECKED Int→i64 lowering for an Int argument crossing the
// host EFFECT boundary (`Random` bounds, `Time.sleep` ms, a
// network port, a `Terminal` coordinate). A Big TRAPS instead
// of saturating, so an out-of-range effect arg rejects on
// wasm-gc exactly as the VM's checked `to_i64()` errors.
BuiltinName::AintToI64Checked,
// `Int = ℤ` size lever: the LEAN i64 decimal formatter, registered
// as a SECOND `String.fromInt` helper alongside the `$AverInt`
// bignum formatter. A raw-i64 (bare/carrier) stringify routes here
// directly (no box, no bignum formatter); the bignum `StringFromInt`
// is then referenced ONLY by genuine `$AverInt` stringifies, so an
// all-raw program never calls it and `wasm-opt -Oz` DCEs it. This
// itoa body is far smaller than the ~536 B long-division formatter,
// and -Oz strips it too when no raw stringify reaches it.
BuiltinName::StringFromIntI64,
] {
builtin_registry.register(b);
}
}
// 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 ®istry.list_order {
if let Some(elem) = super::types::TypeRegistry::list_element_type(canonical) {
nominal_seed.push(elem.trim().to_string());
}
}
for canonical in ®istry.vector_order {
if let Some(elem) = super::types::TypeRegistry::vector_element_type(canonical) {
nominal_seed.push(elem.trim().to_string());
}
}
for canonical in ®istry.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 {
// ETAP-2 carrier-`i64`: an eligible carrier is `i64`-erased — it has
// no struct, so a per-type `__eq_/__hash_<Carrier>` helper would emit
// a body that `struct.get`s an `i64` (invalid wasm). Its eq/hash is
// the raw `i64.eq` / `i32.wrap_i64` inlined at every use site, so skip
// the helper registration entirely (mirrors `register_field_type`).
if registry.is_eligible_carrier(name) {
continue;
}
if registry.record_fields.contains_key(name) {
eq_helpers_registry.register_transitive(name, EqKind::Record, ®istry);
hash_helpers_registry.register_transitive(name, HashKind::Record, ®istry);
} else if registry
.variants
.values()
.flat_map(|v| v.iter())
.any(|v| &v.parent == name)
{
eq_helpers_registry.register_transitive(name, EqKind::Sum, ®istry);
hash_helpers_registry.register_transitive(name, HashKind::Sum, ®istry);
} 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, ®istry);
hash_helpers_registry.register_transitive(name, HashKind::OptionHash, ®istry);
} else if name.starts_with("Result<") && name.ends_with('>') {
eq_helpers_registry.register_transitive(name, EqKind::ResultEq, ®istry);
hash_helpers_registry.register_transitive(name, HashKind::ResultHash, ®istry);
} else if name.starts_with("Tuple<") && name.ends_with('>') {
eq_helpers_registry.register_transitive(name, EqKind::TupleEq, ®istry);
hash_helpers_registry.register_transitive(name, HashKind::TupleHash, ®istry);
}
}
// 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, ®istry);
}
// 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(®istry) {
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 ®istry.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, ®istry)?;
// 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(®istry)?;
let r = name.results(®istry)?;
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);
}
// ── Phase 4 / 0.20 "Pulse" — wasi:sockets/* ──────
//
// The Tcp.* surface shares one connect pipeline,
// one read loop, one write loop, plus the
// timeout-race for ping. Each effect registers
// exactly the slots its lowering needs; the union
// covers the whole choreography. Reuses from the
// HTTP path: input-stream/output-stream blocking
// read/write + drops, io/poll.poll + drop pollable,
// monotonic-clock subscribe-duration (ping only).
EffectName::TcpConnect => {
wasip2_imports
.register(Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
);
wasip2_imports
.register(Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpStartConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpFinishConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpSubscribe);
// Drop socket on every error path inside the
// connect helper (Phase 4.2.2c: start-connect
// Err, finish-connect Err). On the happy path
// Phase 4.2.2d will keep it live and store in
// the pool slot.
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket);
// Phase 4.2.2e — stale-slot recovery (pool
// wraparound after 256+ connects) shuts the
// old socket down and drops its streams
// before reusing the slot.
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpShutdown);
wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
wasip2_imports
.register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
wasip2_imports.register(Wasip2ImportSlot::IoPollPoll);
wasip2_imports.register(Wasip2ImportSlot::IoPollResourceDropPollable);
}
EffectName::TcpWriteLine => {
wasip2_imports
.register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
}
EffectName::TcpReadLine => {
wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
}
EffectName::TcpClose => {
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpShutdown);
wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
wasip2_imports
.register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket);
}
EffectName::TcpSend => {
// Phase 4.7+ pass 4 — `__rt_tcp_send` is ephemeral
// (inline dial + raw bytes + shutdown(send) +
// read-to-EOF, no pool slot). Slot union is the
// wasi:sockets/* dial set plus the wasi:io stream
// pair used by the write + read loops; no overlap
// with `Tcp.connect`'s pool path.
wasip2_imports
.register(Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
);
wasip2_imports
.register(Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpStartConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpFinishConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpSubscribe);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpShutdown);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket);
wasip2_imports.register(Wasip2ImportSlot::IoPollPoll);
wasip2_imports.register(Wasip2ImportSlot::IoPollResourceDropPollable);
wasip2_imports
.register(Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush);
wasip2_imports.register(Wasip2ImportSlot::InputStreamBlockingRead);
wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
wasip2_imports
.register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
}
EffectName::TcpPing => {
// Phase 4.7+ pass 5 — `__rt_tcp_ping` is ephemeral
// (inline dial + drop streams + drop socket, no
// pool slot, no shutdown). Slot union is the
// wasi:sockets/* dial set plus the stream-drop
// pair used to release the never-read streams
// after a successful finish-connect. No
// monotonic-clock timeout race yet —
// `subscribe-duration` lands when a real
// source-level timeout knob shows up.
wasip2_imports
.register(Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses);
wasip2_imports
.register(Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
);
wasip2_imports.register(
Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
);
wasip2_imports
.register(Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpStartConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpFinishConnect);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpSubscribe);
wasip2_imports.register(Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket);
wasip2_imports.register(Wasip2ImportSlot::IoStreamsResourceDropInputStream);
wasip2_imports
.register(Wasip2ImportSlot::IoStreamsResourceDropOutputStream);
wasip2_imports.register(Wasip2ImportSlot::IoPollPoll);
wasip2_imports.register(Wasip2ImportSlot::IoPollResourceDropPollable);
}
_ => {} // 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).
// ETAP-2 SLICE 2a: source the per-fn Int repr from the MIR fn so the
// functype here, the `SlotTable` params-prefix, and the
// `call_indirect` `fn_sig_key` all read the SAME repr (the invariant
// they must agree on byte-for-byte). On the un-rewritten wasm-gc MIR
// every repr is default-empty, so `*_with_repr` emits the boxed
// signature `param_types` / `return_results` already produced — and
// the gate (`ENABLE_BARE_SLOTS`) is off besides. `fn_defs[i]` is
// position-aligned with `resolved_fn_defs[i]`.
let default_repr = crate::ir::mir::MirFnRepr::default();
let mut fn_type_indices: Vec<u32> = Vec::with_capacity(fn_defs.len());
for (i, fd) in fn_defs.iter().enumerate() {
let repr = mir_program
.fn_by_id(resolved_fn_defs[i].fn_id)
.map(|mf| &mf.repr)
.unwrap_or(&default_repr);
let params = param_types_with_repr(&fd.params, Some(®istry), &repr.bare_params)?;
let results = return_results_with_repr(&fd.return_type, Some(®istry), repr.bare_return)?;
types.ty().function(params, results);
fn_type_indices.push(next_type_idx);
next_type_idx += 1;
}
// 4b) `call_indirect` functypes for first-class `Fn`-param calls.
// One unique functype per distinct `Fn(..)` param signature
// reached by a `MirCallee::LocalSlot` call site. Emitted right
// after the user-fn types so `next_type_idx` stays monotonic;
// the body emitter looks each one up by the SAME `fn_sig_key`
// the registration computed (`call_indirect_types`). Each
// functype is byte-identical to the target fn's own functype
// (built from the same lowering), so a `Fn`-value index from
// the funcref table dispatches correctly through it.
let fn_params_by_id: HashMap<crate::ir::FnId, &[(String, crate::types::Type)]> =
resolved_fn_defs
.iter()
.map(|rfd| (rfd.fn_id, rfd.params.as_slice()))
.collect();
let mut call_indirect_types: HashMap<String, u32> = HashMap::new();
for (key, (params, results)) in
collect_call_indirect_sigs(&mir_program, &fn_params_by_id, ®istry)?
{
types.ty().function(params, results);
call_indirect_types.insert(key, 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(),
};
// ── Funcref table for first-class `Fn` values ──────────────────
//
// Every address-taken fn (referenced via `MirExpr::FnValue`) that
// resolves to a USER fn gets a dense table index `0..N`. A `Fn`
// value lowers to that i32 index (`from_mir`'s `FnValue` arm); a
// `Fn`-param call dispatches via `call_indirect` against this
// table (table 0). Names that don't match a user fn (builtins /
// variants) are excluded — those `FnValue` sites fall back to the
// trap stub. The i-th user fn lives at wasm fn idx
// `import_count + 1 + i` (`_start` is at `import_count`).
let mut funcref_table: HashMap<String, u32> = HashMap::new();
let mut funcref_wasm_idxs: Vec<u32> = Vec::new();
for name in collect_address_taken(&mir_program) {
if let Some(i) = fn_defs.iter().position(|fd| fd.name == name) {
let table_idx = funcref_wasm_idxs.len() as u32;
funcref_table.insert(name, table_idx);
funcref_wasm_idxs.push(import_count + 1 + (i as u32));
}
}
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(®istry)?;
let r = name.results(®istry)?;
types.ty().function(p, r);
}
// bignum slice 4 (eq+hash gap) — record the `__aint_eq` / `__aint_hash`
// fn indices on the registry now that `assign_slots` has run, so every
// Int eq+hash emitter (Map keys/values, Set members, record/sum fields,
// carrier payloads — all of which already receive `®istry`) can route
// through them without threading two extra `Option<u32>` params through
// a dozen helper functions across maps.rs / lists.rs / eq_helpers.rs /
// hash_helpers.rs. `Some` iff `bignum`.
if registry.bignum {
registry.aint_eq_fn_idx = builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintEq);
registry.aint_hash_fn_idx = builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintHash);
registry.aint_from_i64_fn_idx =
builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintFromI64);
registry.aint_to_i64_checked_fn_idx =
builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintToI64Checked);
// Shared sub-routine fn indices — the arithmetic helpers' WAT renders a
// `call <idx>` to these instead of inlining the body. `Some` since they
// are registered unconditionally above when `bignum`.
registry.aint_decompose_fn_idx =
builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintDecompose);
registry.aint_normalize_fn_idx =
builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintNormalize);
registry.aint_strip_fn_idx = builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintStrip);
registry.aint_umag_cmp_fn_idx =
builtin_registry.lookup_wasm_fn_idx(BuiltinName::AintUmagCmp);
}
// 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(
®istry.map_order,
®istry,
&mut next_builtin_fn_idx,
&mut next_type_idx,
)?;
map_helpers.emit_helper_types(&mut types, ®istry)?;
// 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 = fn_defs_use_string_split_join(&resolved_fn_defs);
let mut list_helpers = super::lists::ListHelperRegistry::default();
list_helpers.assign_slots(
®istry.list_order,
®istry.vector_order,
®istry.tuple_order,
needs_split_join,
®istry,
&mut next_builtin_fn_idx,
&mut next_type_idx,
)?;
list_helpers.emit_helper_types(&mut types, ®istry)?;
// 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, ®istry, &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(),
// `println_to_lm` reuses `to_lm_type` — same `(s: ref
// string) -> i32` shape. The body writes `'\n'` at
// LM[len] before returning `len + 1`.
println_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,
aint_from_i64_fn_idx: registry.aint_from_i64_fn_idx,
})
} else {
None
};
// Phase 4.x (0.20) — allocate the Tcp.* helper family in one
// sweep. wireup::allocate threads the gating checks +
// type/fn-idx bumps in a fixed order; register_funcs/emit
// sites below pattern-match on the resulting bundle.
let tcp = super::wasip2_tcp::wireup::allocate(
®istry,
&wasip2_imports,
&mut types,
&mut next_type_idx,
&mut next_builtin_fn_idx,
);
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,
®istry,
&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);
// println_to_lm reuses the to_lm wasm type (same
// `(s: ref string) -> i32` signature).
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);
}
// Tcp.* helper fns. Order is connect → format_id → parse_id →
// write_line → read_line → close → send → ping; wireup pins it
// so emit_*'s `Call(idx)` resolution stays stable.
super::wasip2_tcp::wireup::register_funcs(&mut funcs, &tcp);
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);
// ── Table section (funcref table for first-class `Fn` values) ──
//
// One funcref table (table 0) sized to the number of address-taken
// user fns. Each `Fn` value is a dense index into it; `Fn`-param
// calls dispatch via `call_indirect 0`. Emitted only when at least
// one fn is address-taken — empty programs skip the section. Binary
// section order: Table (id 4) follows Function (id 3) and precedes
// Memory (id 5).
if !funcref_wasm_idxs.is_empty() {
let n = funcref_wasm_idxs.len() as u64;
let mut tables = TableSection::new();
tables.table(TableType {
element_type: RefType::FUNCREF,
table64: false,
minimum: n,
maximum: Some(n),
shared: false,
});
module.section(&tables);
}
// ── 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
};
// Phase 4 (0.20) — wasi:sockets network handle cache,
// tcp_pool array, and tcp_next_id counter. All gated on
// the matching slot/type registrations so non-TCP programs
// pay nothing.
let network_handle = if wasip2_imports
.lookup_wasm_type_idx(
super::wasip2_imports::Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork,
)
.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 tcp_pool = if let Some(pool_type_idx) = registry.tcp_pool_type_idx {
globals.global(
wasm_encoder::GlobalType {
val_type: ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(pool_type_idx),
}),
mutable: true,
shared: false,
},
&wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::Concrete(pool_type_idx)),
);
let idx = next_global_idx;
next_global_idx += 1;
Some(idx)
} else {
None
};
let tcp_next_id = if registry.tcp_pool_type_idx.is_some() {
globals.global(
wasm_encoder::GlobalType {
val_type: ValType::I32,
mutable: true,
shared: false,
},
&wasm_encoder::ConstExpr::i32_const(0),
);
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,
network_handle,
tcp_pool,
tcp_next_id,
})
} 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),
println_to_lm_fn_idx: bridge.as_ref().map(|b| b.println_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),
tcp_connect_fn_idx: tcp.connect.as_ref().map(|t| t.fn_idx),
tcp_close_fn_idx: tcp.close.as_ref().map(|t| t.fn_idx),
tcp_write_line_fn_idx: tcp.write_line.as_ref().map(|t| t.fn_idx),
tcp_read_line_fn_idx: tcp.read_line.as_ref().map(|t| t.fn_idx),
tcp_send_fn_idx: tcp.send.as_ref().map(|t| t.fn_idx),
tcp_ping_fn_idx: tcp.ping.as_ref().map(|t| t.fn_idx),
network_handle_global: wasip2_globals.as_ref().and_then(|g| g.network_handle),
tcp_pool_global: wasip2_globals.as_ref().and_then(|g| g.tcp_pool),
tcp_next_id_global: wasip2_globals.as_ref().and_then(|g| g.tcp_next_id),
tcp_slot_type_idx: registry.tcp_slot_type_idx,
tcp_pool_type_idx: registry.tcp_pool_type_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 FnId → 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)
//
// `resolved_fn_defs` is position-aligned with `fn_defs`
// (`WasmGcLinkedView::build` errors if the resolver drops any
// fn), so `resolved_fn_defs[i].fn_id` is the FnId for
// `fn_defs[i]`. PR 9.3c switched this map from name-keyed to
// FnId-keyed — mirror of the FnKey/FnId dispatch shape in
// `CodegenContext::resolve_fn_def` (PR 9.3a).
let start_wasm_idx = import_count;
let mut by_id: HashMap<crate::ir::FnId, FnEntry> = HashMap::new();
for (i, fd) in fn_defs.iter().enumerate() {
let rfd = &resolved_fn_defs[i];
by_id.insert(
rfd.fn_id,
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 ®istry.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 ®istry.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 ®istry.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 ®istry.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 ®istry.map_order {
if let Some(h) = map_helpers.kv_helpers(canonical) {
eq_helpers_lookup.insert(canonical.clone(), h.eq);
}
}
// bignum slice 3 — capture the `__aint_eq` fn idx before
// `builtin_idx_lookup` is moved into `fn_map`, so the list/vec Int-
// element eq sites can route through it (an `i64.eq` on a `$AverInt`
// ref is invalid wasm — a latent slice-1/2 gap for any `Vector<Int>`
// / `List<Int>`).
let aint_eq_fn_idx = if registry.bignum {
builtin_idx_lookup.get("__aint_eq").copied()
} else {
None
};
let fn_map = FnMap {
by_id,
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,
funcref_table,
call_indirect_types,
};
// ── 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);
// `Int = ℤ`: `Int` entry params are the `$AverInt` carrier, so
// the host (`aver run --wasm-gc --expr`, record/replay) needs a
// way to build one from a machine-range i64 it parsed. Re-export
// the canonical Small constructor under a stable bridge name.
if let Some(idx) = registry.aint_from_i64_fn_idx {
exports.export("__rt_aint_from_i64", ExportKind::Func, idx);
}
}
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);
// ── Element section (active funcref-table init) ────────────────
//
// Active segment at table 0, offset 0, initialising every slot with
// the wasm fn idx of the i-th address-taken user fn (so table[i]
// points at the fn whose `Fn` value carries index `i`). Emitted
// only when the funcref table exists. Binary section order: Element
// (id 9) follows Export (id 7) and precedes the DataCount / Code
// sections below.
if !funcref_wasm_idxs.is_empty() {
let mut elements = ElementSection::new();
elements.active(
None,
&ConstExpr::i32_const(0),
Elements::Functions((&funcref_wasm_idxs[..]).into()),
);
module.section(&elements);
}
// (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")
});
// `mir_program` was lowered + optimized up front (before the type
// section), so the address-taken-fn scan + `call_indirect` functype
// pre-registration could run during type-section assembly. It is
// the SAME `optimize`d program the VM consumes.
//
// `mir_fn_for[i]` is `Some(&MirFn)` when the i-th fn lowered to
// MIR (always true on valid input — every resolved fn lowers).
// `mir_dispatch[i]` is the final per-fn decision: `true` when the
// MIR body emitter rendered the fn, `false` when it returned `None`
// and the fn got a trap-stub body instead. It is computed once in
// the caller_fn pre-pass below and reused verbatim by the dry-run +
// real code-emit loops, so all three see the same path per fn and
// the discovered locals / caller_fn registration stay consistent.
let mir_fn_for: Vec<Option<&crate::ir::mir::MirFn>> = resolved_fn_defs
.iter()
.map(|rfd| mir_program.fn_by_id(rfd.fn_id))
.collect();
let mut mir_dispatch: Vec<bool> = vec![false; fn_defs.len()];
// 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. This
// pass also decides MIR-emit vs trap-stub per fn (`mir_dispatch`):
// the chosen emitter runs here so its caller_fn registrations match
// the real code-emit loop. A trap-stub body emits no calls, so the
// pre-pass simply skips caller_fn collection for those fns.
for (i, _fd) in fn_defs.iter().enumerate() {
let self_wasm_idx = import_count + 1 + (i as u32);
let mut probe = Function::new([]);
let used_mir = match mir_fn_for[i] {
Some(mir_fn) => emit_fn_body_via_mir(
&mut probe,
&resolved_fn_defs[i],
mir_fn,
&mir_program,
&fn_map,
self_wasm_idx,
®istry,
&symbol_table,
&effect_idx_lookup,
&caller_fn_collector,
wasip2_lowering.as_ref(),
)?
.is_some(),
None => false,
};
mir_dispatch[i] = used_mir;
}
// `AVER_WASMGC_REQUIRE_MIR=1` turns the per-fn trap-stub fallback
// into a hard error that lists every fn which did NOT emit from MIR
// (today only higher-order verify-only shapes like `pairSpec`).
// Diagnostic / development only: the production path leaves it unset
// and emits the trap stub silently.
if std::env::var_os("AVER_WASMGC_REQUIRE_MIR").is_some() {
let fell_back: Vec<&str> = (0..mir_dispatch.len())
.filter(|&i| !mir_dispatch[i])
.map(|i| resolved_fn_defs[i].name.as_str())
.collect();
if !fell_back.is_empty() {
return Err(WasmGcError::Validation(format!(
"AVER_WASMGC_REQUIRE_MIR: {} of {} fns were not covered by the MIR body \
emitter (emitted a trap stub instead): {}",
fell_back.len(),
mir_dispatch.len(),
fell_back.join(", ")
)));
}
}
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,
aint_to_i64_checked_fn_idx: registry.aint_to_i64_checked_fn_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. The MIR /
// ResolvedExpr decision (`mir_dispatch[i]`) was fixed in the
// caller_fn pre-pass; reuse it here so the discovered locals
// match the body the real emit produces below.
// A fn the MIR walker doesn't cover (`mir_dispatch[i] == false`)
// gets a `unreachable` trap stub with zero extra locals —
// `unreachable` is polymorphic so it validates for any
// signature. So the dry-run only needs locals for the MIR path;
// the stub path contributes none.
let extra_locals_dry = if mir_dispatch[i] {
let mut probe = Function::new([]);
emit_fn_body_via_mir(
&mut probe,
&resolved_fn_defs[i],
mir_fn_for[i].expect("mir_dispatch ⇒ mir_fn_for is Some"),
&mir_program,
&fn_map,
self_wasm_idx,
®istry,
&symbol_table,
&effect_idx_lookup,
&caller_fn_collector,
wasip2_lowering.as_ref(),
)?
.ok_or_else(|| {
WasmGcError::Validation(format!(
"MIR dispatch desync for fn `{}` (dry-run)",
resolved_fn_defs[i].name
))
})?
} else {
Vec::new()
};
let local_groups: Vec<(u32, ValType)> = extra_locals_dry.iter().map(|v| (1, *v)).collect();
let mut func = Function::new(local_groups);
if mir_dispatch[i] {
emit_fn_body_via_mir(
&mut func,
&resolved_fn_defs[i],
mir_fn_for[i].expect("mir_dispatch ⇒ mir_fn_for is Some"),
&mir_program,
&fn_map,
self_wasm_idx,
®istry,
&symbol_table,
&effect_idx_lookup,
&caller_fn_collector,
wasip2_lowering.as_ref(),
)?
.ok_or_else(|| {
WasmGcError::Validation(format!(
"MIR dispatch desync for fn `{}` (emit)",
resolved_fn_defs[i].name
))
})?;
} else {
emit_trap_stub_body(&mut func);
}
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, ®istry)?;
// 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 ®istry.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 ®istry.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 ®istry.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,
®istry,
&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,
®istry,
string_eq_fn_idx,
&eq_helper_fn_idx_map,
&hash_helper_fn_idx_map,
aint_eq_fn_idx,
)?;
// 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,
®istry,
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,
®istry,
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(
®istry,
&fn_map,
user_handler_wasm_idx,
wrapper_caller_fn_idx,
)?);
codes.function(&emit_list_string_cons(®istry)?);
let _ = hw.list_cons_type; // type idx already consumed by emit_function_section
}
if bridge.is_some() {
emit_bridge_bodies(&mut codes, ®istry)?;
}
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));
}
// Phase 4.2.1 (0.20) — stub `__rt_tcp_connect` body. Reads the
// pre-registered "tcp: connect not yet implemented" data segment,
// wraps it via `__rt_result_tcp_connection_string_err`, returns.
// No wasi:sockets calls happen here yet; the real DNS / socket /
// connect pipeline replaces this body in Phase 4.2.2+.
if let Some(tc) = &tcp.connect {
let result_err_fn = factory_exports
.result_tcp_connection_string_err
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires \
__rt_result_tcp_connection_string_err factory slot"
.into(),
)
})?
.fn_idx;
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!("tcp.connect emit requires {name} fn idx"))
})
};
let instance_network_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork,
"SocketsInstanceNetworkInstanceNetwork",
)?;
let resolve_addresses_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses,
"SocketsIpNameLookupResolveAddresses",
)?;
let drop_resolve_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
"SocketsIpNameLookupResourceDropResolveAddressStream",
)?;
let stream_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
"SocketsIpNameLookupResolveAddressStreamSubscribe",
)?;
let poll_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollPoll,
"IoPollPoll",
)?;
let drop_pollable_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable,
"IoPollResourceDropPollable",
)?;
let resolve_next_address_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress,
"SocketsIpNameLookupResolveNextAddress",
)?;
let create_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket,
"SocketsTcpCreateSocketCreateTcpSocket",
)?;
let start_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpStartConnect,
"SocketsTcpStartConnect",
)?;
let socket_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpSubscribe,
"SocketsTcpSubscribe",
)?;
let finish_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpFinishConnect,
"SocketsTcpFinishConnect",
)?;
let drop_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket,
"SocketsTcpResourceDropTcpSocket",
)?;
let network_handle_global = wasip2_globals
.as_ref()
.and_then(|g| g.network_handle)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires network_handle global \
(Phase 4.1b wireup gate)"
.into(),
)
})?;
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.connect emit requires cabi_realloc fn idx".into())
})?;
let str_to_lm_fn = bridge.as_ref().map(|b| b.to_lm_fn).ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires bridge (__rt_string_to_lm fn idx)".into(),
)
})?;
let (_format_id_ty, format_id_fn) = tcp
.format_id
.expect("tcp_format_id allocated when tcp.connect is allocated");
let record_make_fn = factory_exports
.tcp_connection_make
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires __rt_record_tcp_connection_make factory slot".into(),
)
})?
.fn_idx;
let result_ok_fn = factory_exports
.result_tcp_connection_string_ok
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires __rt_result_tcp_connection_string_ok factory slot"
.into(),
)
})?
.fn_idx;
let tcp_next_id_global = wasip2_globals
.as_ref()
.and_then(|g| g.tcp_next_id)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires tcp_next_id global (Phase 4.1b gate)".into(),
)
})?;
let tcp_pool_global = wasip2_globals
.as_ref()
.and_then(|g| g.tcp_pool)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.connect emit requires tcp_pool global (Phase 4.1b gate)".into(),
)
})?;
let tcp_slot_type_idx = registry
.tcp_slot_type_idx
.expect("tcp_slot type slot allocated alongside tcp_pool when needs_tcp");
let tcp_pool_type_idx = registry
.tcp_pool_type_idx
.expect("tcp_pool type slot allocated alongside tcp_slot when needs_tcp");
// Phase 4.2.2e — stale-slot recovery needs `shutdown` +
// Phase 4.7+ fix #10 — pool wraparound now refuses with Err
// instead of force-dropping the live occupant, so the
// stale-recovery shutdown/drop trio is gone. close + helper
// emit still pulls those slots from `wasip2_imports`.
let bump_alloc_ptr_global = wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.connect emit requires bump_alloc_ptr global (Phase 4.2.2f rewind)");
let helpers = super::wasip2_tcp::TcpConnectHelperFns {
pool: super::wasip2_tcp::TcpConnectPool {
tcp_next_id_global,
tcp_pool_global,
tcp_slot_type_idx,
tcp_pool_type_idx,
bump_alloc_ptr_global,
},
dns: super::wasip2_tcp::TcpConnectDns {
instance_network_fn,
network_handle_global,
resolve_addresses_fn,
resolve_next_address_fn,
drop_resolve_stream_fn,
stream_subscribe_fn,
poll_fn,
drop_pollable_fn,
},
socket: super::wasip2_tcp::TcpConnectSocket {
create_tcp_socket_fn,
start_connect_fn,
finish_connect_fn,
socket_subscribe_fn,
drop_tcp_socket_fn,
},
materialize: super::wasip2_tcp::TcpConnectMaterialize {
cabi_realloc_fn,
str_to_lm_fn,
format_id_fn,
record_make_fn,
result_ok_fn,
result_err_fn,
},
};
codes.function(&super::wasip2_tcp::emit_tcp_connect_stub(tc, &helpers));
let string_type_idx = registry
.string_array_type_idx
.expect("tcp_format_id requires string slot");
let from_lm_fn = bridge.as_ref().map(|b| b.from_lm_fn).ok_or_else(|| {
WasmGcError::Validation(
"tcp_format_id requires bridge (__rt_string_from_lm fn idx)".into(),
)
})?;
codes.function(&super::wasip2_tcp::emit_tcp_format_id(
string_type_idx,
from_lm_fn,
));
}
// parse_id is emitted independently of connect — close / write /
// read can be the only consumers (e.g. a fn that takes a
// `Tcp.Connection` as input without ever calling `Tcp.connect`).
if tcp.parse_id.is_some() {
let string_type_idx = registry
.string_array_type_idx
.expect("tcp_parse_id allocated when registry has the string slot");
codes.function(&super::wasip2_tcp::emit_tcp_parse_id(string_type_idx));
}
// Code-section order MUST match allocation order in
// tcp_*_fn_type_idx blocks above: connect → format_id →
// parse_id → write_line → read_line → close → send. Diverging
// shifts every Call(idx) and surfaces as wasm validator
// type-mismatch errors at cryptic offsets.
if let Some(tw) = &tcp.write_line {
let (_, parse_id_fn) = tcp
.parse_id
.expect("tcp.write_line gated on tcp_parse_id allocation");
let str_to_lm_fn = bridge.as_ref().map(|b| b.to_lm_fn).ok_or_else(|| {
WasmGcError::Validation(
"tcp.write_line emit requires bridge (__rt_string_to_lm fn idx)".into(),
)
})?;
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.write_line emit requires cabi_realloc fn idx".into())
})?;
let blocking_write_fn = wasip2_imports
.lookup_wasm_fn_idx(
super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
)
.expect("tcp.write_line gate requires blocking-write slot");
let result_ok_fn = factory_exports
.result_unit_string_ok
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.write_line emit requires __rt_result_unit_string_ok factory slot".into(),
)
})?
.fn_idx;
let result_err_fn = factory_exports
.result_unit_string_err
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.write_line emit requires __rt_result_unit_string_err factory slot".into(),
)
})?
.fn_idx;
let tcp_pool_global = wasip2_globals
.as_ref()
.and_then(|g| g.tcp_pool)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.write_line emit requires tcp_pool global (Phase 4.1b gate)".into(),
)
})?;
let helpers = super::wasip2_tcp::TcpWriteLineHelperFns {
parse_id_fn,
str_to_lm_fn,
cabi_realloc_fn,
blocking_write_fn,
result_ok_fn,
result_err_fn,
tcp_pool_global,
bump_alloc_ptr_global: wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.write_line emit requires bump_alloc_ptr global"),
};
codes.function(&super::wasip2_tcp::emit_tcp_write_line(tw, &helpers));
}
if let Some(tr) = &tcp.read_line {
let (_, parse_id_fn) = tcp
.parse_id
.expect("tcp.read_line gated on tcp_parse_id allocation");
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.read_line emit requires cabi_realloc fn idx".into())
})?;
let blocking_read_fn = wasip2_imports
.lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead)
.expect("tcp.read_line gate requires blocking-read slot");
let tcp_pool_global = wasip2_globals
.as_ref()
.and_then(|g| g.tcp_pool)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.read_line emit requires tcp_pool global (Phase 4.1b gate)".into(),
)
})?;
let helpers = super::wasip2_tcp::TcpReadLineHelperFns {
parse_id_fn,
cabi_realloc_fn,
blocking_read_fn,
tcp_pool_global,
bump_alloc_ptr_global: wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.read_line emit requires bump_alloc_ptr global"),
};
codes.function(&super::wasip2_tcp::emit_tcp_read_line(tr, &helpers));
}
if let Some(tc) = &tcp.close {
let (_, parse_id_fn) = tcp
.parse_id
.expect("tcp.close gated on tcp_parse_id allocation");
let shutdown_fn = wasip2_imports
.lookup_wasm_fn_idx(super::wasip2_imports::Wasip2ImportSlot::SocketsTcpShutdown)
.expect("tcp.close gate requires shutdown slot");
let drop_input_stream_fn = wasip2_imports
.lookup_wasm_fn_idx(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
)
.expect("tcp.close gate requires drop-input-stream slot");
let drop_output_stream_fn = wasip2_imports
.lookup_wasm_fn_idx(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
)
.expect("tcp.close gate requires drop-output-stream slot");
let drop_tcp_socket_fn = wasip2_imports
.lookup_wasm_fn_idx(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket,
)
.expect("tcp.close gate requires drop-tcp-socket slot");
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.close emit requires cabi_realloc fn idx".into())
})?;
let result_ok_fn = factory_exports
.result_unit_string_ok
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.close emit requires __rt_result_unit_string_ok factory slot".into(),
)
})?
.fn_idx;
let result_err_fn = factory_exports
.result_unit_string_err
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.close emit requires __rt_result_unit_string_err factory slot \
(Phase 4.7+ cross-backend alignment surfaces stale-conn as Err)"
.into(),
)
})?
.fn_idx;
let tcp_pool_global = wasip2_globals
.as_ref()
.and_then(|g| g.tcp_pool)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.close emit requires tcp_pool global (Phase 4.1b gate)".into(),
)
})?;
let helpers = super::wasip2_tcp::TcpCloseHelperFns {
parse_id_fn,
cabi_realloc_fn,
shutdown_fn,
drop_input_stream_fn,
drop_output_stream_fn,
drop_tcp_socket_fn,
result_ok_fn,
result_err_fn,
tcp_pool_global,
bump_alloc_ptr_global: wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.close emit requires bump_alloc_ptr global"),
};
codes.function(&super::wasip2_tcp::emit_tcp_close(tc, &helpers));
}
if let Some(ts) = &tcp.send {
// Phase 4.7+ pass 4 — send no longer goes through
// `__rt_tcp_connect`. The dialing pipeline lives inline in
// `emit_tcp_send`, so we re-lookup every wasi-sockets
// import the body uses directly.
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!("tcp.send emit requires {name} fn idx"))
})
};
let instance_network_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork,
"SocketsInstanceNetworkInstanceNetwork",
)?;
let resolve_addresses_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses,
"SocketsIpNameLookupResolveAddresses",
)?;
let drop_resolve_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
"SocketsIpNameLookupResourceDropResolveAddressStream",
)?;
let stream_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
"SocketsIpNameLookupResolveAddressStreamSubscribe",
)?;
let poll_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollPoll,
"IoPollPoll",
)?;
let drop_pollable_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable,
"IoPollResourceDropPollable",
)?;
let resolve_next_address_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress,
"SocketsIpNameLookupResolveNextAddress",
)?;
let create_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket,
"SocketsTcpCreateSocketCreateTcpSocket",
)?;
let start_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpStartConnect,
"SocketsTcpStartConnect",
)?;
let socket_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpSubscribe,
"SocketsTcpSubscribe",
)?;
let finish_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpFinishConnect,
"SocketsTcpFinishConnect",
)?;
let drop_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket,
"SocketsTcpResourceDropTcpSocket",
)?;
let drop_input_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
"IoStreamsResourceDropInputStream",
)?;
let drop_output_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
"IoStreamsResourceDropOutputStream",
)?;
let str_to_lm_fn = bridge.as_ref().map(|b| b.to_lm_fn).ok_or_else(|| {
WasmGcError::Validation(
"tcp.send emit requires bridge (__rt_string_to_lm fn idx)".into(),
)
})?;
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.send emit requires cabi_realloc fn idx".into())
})?;
let blocking_write_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::OutputStreamBlockingWriteAndFlush,
"OutputStreamBlockingWriteAndFlush",
)?;
let blocking_read_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::InputStreamBlockingRead,
"InputStreamBlockingRead",
)?;
let shutdown_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpShutdown,
"SocketsTcpShutdown",
)?;
let network_handle_global = wasip2_globals
.as_ref()
.and_then(|g| g.network_handle)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.send emit requires network_handle global (Phase 4.1b wireup gate)".into(),
)
})?;
let bump_alloc_ptr_global = wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.send emit requires bump_alloc_ptr global");
let result_string_string_err_fn = factory_exports
.result_string_string_err
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.send emit requires __rt_result_string_string_err factory slot".into(),
)
})?
.fn_idx;
let helpers = super::wasip2_tcp::TcpSendHelperFns {
instance_network_fn,
network_handle_global,
resolve_addresses_fn,
resolve_next_address_fn,
drop_resolve_stream_fn,
stream_subscribe_fn,
poll_fn,
drop_pollable_fn,
create_tcp_socket_fn,
start_connect_fn,
finish_connect_fn,
socket_subscribe_fn,
drop_tcp_socket_fn,
drop_input_stream_fn,
drop_output_stream_fn,
str_to_lm_fn,
cabi_realloc_fn,
blocking_write_fn,
blocking_read_fn,
shutdown_fn,
bump_alloc_ptr_global,
result_string_string_err_fn,
};
codes.function(&super::wasip2_tcp::emit_tcp_send(ts, &helpers));
}
if let Some(tp) = &tcp.ping {
// Phase 4.7+ pass 5 fix #21 — ping is ephemeral (inline DNS
// + socket + connect, no pool). Same dial pipeline as
// `Tcp.send`, with a Result.Ok(()) tail instead of write +
// read. Re-resolves every wasi-sockets import the body uses
// directly, mirroring the send block above.
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!("tcp.ping emit requires {name} fn idx"))
})
};
let instance_network_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsInstanceNetworkInstanceNetwork,
"SocketsInstanceNetworkInstanceNetwork",
)?;
let resolve_addresses_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddresses,
"SocketsIpNameLookupResolveAddresses",
)?;
let drop_resolve_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResourceDropResolveAddressStream,
"SocketsIpNameLookupResourceDropResolveAddressStream",
)?;
let stream_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveAddressStreamSubscribe,
"SocketsIpNameLookupResolveAddressStreamSubscribe",
)?;
let poll_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollPoll,
"IoPollPoll",
)?;
let drop_pollable_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoPollResourceDropPollable,
"IoPollResourceDropPollable",
)?;
let resolve_next_address_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsIpNameLookupResolveNextAddress,
"SocketsIpNameLookupResolveNextAddress",
)?;
let create_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpCreateSocketCreateTcpSocket,
"SocketsTcpCreateSocketCreateTcpSocket",
)?;
let start_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpStartConnect,
"SocketsTcpStartConnect",
)?;
let socket_subscribe_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpSubscribe,
"SocketsTcpSubscribe",
)?;
let finish_connect_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpFinishConnect,
"SocketsTcpFinishConnect",
)?;
let drop_tcp_socket_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::SocketsTcpResourceDropTcpSocket,
"SocketsTcpResourceDropTcpSocket",
)?;
let drop_input_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropInputStream,
"IoStreamsResourceDropInputStream",
)?;
let drop_output_stream_fn = lookup(
super::wasip2_imports::Wasip2ImportSlot::IoStreamsResourceDropOutputStream,
"IoStreamsResourceDropOutputStream",
)?;
let str_to_lm_fn = bridge.as_ref().map(|b| b.to_lm_fn).ok_or_else(|| {
WasmGcError::Validation(
"tcp.ping emit requires bridge (__rt_string_to_lm fn idx)".into(),
)
})?;
let cabi_realloc_fn = cabi_realloc.as_ref().map(|c| c.fn_idx).ok_or_else(|| {
WasmGcError::Validation("tcp.ping emit requires cabi_realloc fn idx".into())
})?;
let network_handle_global = wasip2_globals
.as_ref()
.and_then(|g| g.network_handle)
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.ping emit requires network_handle global (Phase 4.1b wireup gate)".into(),
)
})?;
let bump_alloc_ptr_global = wasip2_globals
.as_ref()
.map(|g| g.bump_alloc_ptr)
.expect("tcp.ping emit requires bump_alloc_ptr global");
let result_unit_string_ok_fn = factory_exports
.result_unit_string_ok
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.ping emit requires __rt_result_unit_string_ok factory slot".into(),
)
})?
.fn_idx;
let result_unit_string_err_fn = factory_exports
.result_unit_string_err
.ok_or_else(|| {
WasmGcError::Validation(
"tcp.ping emit requires __rt_result_unit_string_err factory slot".into(),
)
})?
.fn_idx;
let helpers = super::wasip2_tcp::TcpPingHelperFns {
instance_network_fn,
network_handle_global,
resolve_addresses_fn,
resolve_next_address_fn,
drop_resolve_stream_fn,
stream_subscribe_fn,
poll_fn,
drop_pollable_fn,
create_tcp_socket_fn,
start_connect_fn,
finish_connect_fn,
socket_subscribe_fn,
drop_tcp_socket_fn,
drop_input_stream_fn,
drop_output_stream_fn,
str_to_lm_fn,
cabi_realloc_fn,
bump_alloc_ptr_global,
result_unit_string_ok_fn,
result_unit_string_err_fn,
};
codes.function(&super::wasip2_tcp::emit_tcp_ping(tp, &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, ®istry)?;
// `__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 ®istry.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);
}
// Second return value: how many fns the MIR body emitter actually
// rendered (the real `emit_fn_body_via_mir` Some/None decision fixed
// in the pre-pass, NOT the structural `coverage_report` predicate).
// The byte-differential test asserts this is non-zero so its
// byte-identity check can't pass vacuously with the MIR path dead.
let mir_emitted = mir_dispatch.iter().filter(|&&used| used).count();
// Surface the count to the multi-module games byte-differential,
// which drives `aver compile` as a subprocess and can't read the
// return value — `AVER_WASMGC_MIR_COUNT=1` prints it so the test can
// assert MIR actually fired on the (flattened) game.
if std::env::var_os("AVER_WASMGC_MIR_COUNT").is_some() {
eprintln!("AVER_WASMGC_MIR_EMITTED={mir_emitted}");
}
Ok((bytes, mir_emitted))
}
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(name, 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,
}),
));
}
// bignum slice 1 — `$AverInt` carrier + its `(array i64)` limb
// magnitude. Emitted only when the registry allocated them (opt-in
// flag + reachable Int arithmetic). The magnitude array slot sits
// one below the struct slot so the struct's `$mag` field references
// an already-defined idx (a single rec group makes forward refs
// legal too, but this keeps the layout obvious).
if let (Some(mag_idx), Some(struct_idx)) =
(registry.aint_mag_array_idx, registry.aint_struct_idx)
{
use wasm_encoder::{HeapType, RefType, StorageType, ValType};
// (array (mut i64)) — little-endian unsigned u64 limbs.
entries.push((
mag_idx,
mk_array(wasm_encoder::FieldType {
element_type: StorageType::Val(ValType::I64),
mutable: true,
}),
));
// (struct (field $small i64)
// (field $mag (ref null (array i64)))
// (field $sign i32))
// Mutable fields so a helper can renormalize in place when it
// demotes a Big to Small without a fresh allocation.
entries.push((
struct_idx,
mk_struct(vec![
wasm_encoder::FieldType {
element_type: StorageType::Val(ValType::I64),
mutable: true,
},
wasm_encoder::FieldType {
element_type: StorageType::Val(ValType::Ref(RefType {
nullable: true,
heap_type: HeapType::Concrete(mag_idx),
})),
mutable: true,
},
wasm_encoder::FieldType {
element_type: StorageType::Val(ValType::I32),
mutable: true,
},
]),
));
}
// Phase 4 (0.20) — TCP connection pool slot type + array type.
// `$tcp_slot` carries five mutable i32 fields per connection:
// 0 socket
// 1 in_stream
// 2 out_stream
// 3 in_use (1 while live, 0 after Tcp.close)
// 4 id_value (the full `tcp_next_id` snapshot when the
// slot was claimed — see Phase 4.7 fix #2)
// `$tcp_pool` is the `(array (mut $tcp_slot))` that holds 256 of
// them. The slot struct is emitted first so the array element
// type can name it by index without a forward reference.
if let Some(slot_idx) = registry.tcp_slot_type_idx {
entries.push((
slot_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(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(ValType::I32),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(ValType::I32),
mutable: true,
},
]),
));
}
if let Some(pool_idx) = registry.tcp_pool_type_idx {
let slot_idx = registry
.tcp_slot_type_idx
.expect("tcp_pool_type_idx allocated without matching tcp_slot_type_idx");
let slot_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(slot_idx),
});
entries.push((
pool_idx,
mk_array(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(slot_ref),
mutable: true,
}),
));
}
// Vector<T> instantiations.
for canonical in ®istry.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 ®istry.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 ®istry.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 ®istry.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 ®istry.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 ®istry.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 ®istry.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(record.aver_name, 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: &crate::ir::hir::ResolvedFnDef,
builtins: &mut BuiltinRegistry,
effects: &mut EffectRegistry,
eq_helpers: &mut EqHelperRegistry,
type_registry: &TypeRegistry,
symbol_table: &crate::ir::SymbolTable,
) {
let crate::ir::hir::ResolvedFnBody::Block(stmts) = fd.body.as_ref();
for stmt in stmts {
discover_builtins_in_stmt(
stmt,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
fn discover_builtins_in_stmt(
stmt: &crate::ir::hir::ResolvedStmt,
builtins: &mut BuiltinRegistry,
effects: &mut EffectRegistry,
eq_helpers: &mut EqHelperRegistry,
type_registry: &TypeRegistry,
symbol_table: &crate::ir::SymbolTable,
) {
match stmt {
crate::ir::hir::ResolvedStmt::Binding { value: e, .. }
| crate::ir::hir::ResolvedStmt::Expr(e) => discover_builtins_in_expr(
&e.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
),
}
}
/// 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.
/// Canonical wasm-gc `TypeRegistry` key for a `Type::Named` reference.
///
/// Resolves the bare/canonical name of a nominal type by routing through
/// the post-flatten `SymbolTable` when the typechecker stamped a `TypeId`.
/// Returns the registry key shape `TypeRegistry::build_with_handler`
/// inserts under: bare for non-colliding dep types (where the wasm-gc
/// link stage keeps the `TypeDef.name` as written) and canonical
/// `Prefix.Name` for the cross-module same-bare-name collision case
/// (where #180 Phase 6 PR 3's `flatten_multimodule` renamed the dep
/// `TypeDef.name`). Falls back to `name` for builtins / unresolved refs
/// whose `id` is `None`.
fn named_type_registry_key(symbol_table: &crate::ir::SymbolTable, ty: &AverType) -> Option<String> {
match ty {
AverType::Named {
id: Some(type_id), ..
} => Some(symbol_table.type_entry(*type_id).key.canonical()),
AverType::Named { id: None, name } => Some(name.clone()),
_ => None,
}
}
/// 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,
symbol_table: &crate::ir::SymbolTable,
) {
let canonical: String = t.display().chars().filter(|c| !c.is_whitespace()).collect();
match t {
AverType::Named { .. } => {
let Some(key) = named_type_registry_key(symbol_table, t) else {
return;
};
// ETAP-2 carrier-`i64`: an eligible carrier is `i64`-erased — no
// struct, no per-type helper (its eq/hash inlines raw at the use
// site). Skip so no `__eq_/__hash_<Carrier>` slot is allocated
// (a struct-shaped body over an `i64` is invalid wasm).
if type_registry.is_eligible_carrier(&key) {
return;
}
if type_registry.record_fields.contains_key(&key) {
eq_helpers.register_transitive(&key, EqKind::Record, type_registry);
} else if type_registry
.variants
.values()
.flat_map(|v| v.iter())
.any(|v| v.parent == key)
{
eq_helpers.register_transitive(&key, 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, symbol_table);
}
AverType::Result(ok, err) => {
eq_helpers.register_transitive(&canonical, EqKind::ResultEq, type_registry);
register_nominal_in_type(ok, eq_helpers, type_registry, symbol_table);
register_nominal_in_type(err, eq_helpers, type_registry, symbol_table);
}
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, symbol_table);
}
}
AverType::List(inner) | AverType::Vector(inner) => {
register_nominal_in_type(inner, eq_helpers, type_registry, symbol_table);
}
AverType::Map(k, v) => {
register_nominal_in_type(k, eq_helpers, type_registry, symbol_table);
register_nominal_in_type(v, eq_helpers, type_registry, symbol_table);
}
_ => {}
}
}
fn discover_builtins_in_expr(
expr: &crate::ir::hir::ResolvedExpr,
builtins: &mut BuiltinRegistry,
effects: &mut EffectRegistry,
eq_helpers: &mut EqHelperRegistry,
type_registry: &TypeRegistry,
symbol_table: &crate::ir::SymbolTable,
) {
use crate::ir::hir::{ResolvedCallee, ResolvedExpr, ResolvedStrPart};
match expr {
ResolvedExpr::Call(callee, args) => {
if let ResolvedCallee::Builtin(dotted) = callee {
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);
}
// `Int.div` is Euclidean (flooring) division — the partner of
// `Int.mod` — and folds through its own `__int_div_euclid`
// helper the same way. Register it whenever discovery hits an
// `Int.div` call (fused-withDefault or unfused).
if dotted == "Int.div" {
builtins.register(BuiltinName::IntDivEuclid);
}
}
for arg in args {
discover_builtins_in_expr(
&arg.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::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 the typed-key
// resolver so non-colliding dep types resolve to their
// registry-bare key and the cross-module same-bare-name
// collision case (#180 Phase 6 PR 3) resolves to the
// renamed canonical `Prefix.Name` key.
use crate::ast::BinOp as Op;
if matches!(op, Op::Eq | Op::Neq)
&& let Some(t) = l.ty()
&& matches!(t, AverType::Named { .. })
&& let Some(key) = named_type_registry_key(symbol_table, t)
{
// ETAP-2 carrier-`i64`: a direct carrier `==` lowers via the
// project box-bridge (each side boxed to `$AverInt`, compared
// with `__aint_eq`) — NOT a struct `__eq_<Carrier>` helper. An
// eligible carrier is `i64`-erased and gets no such helper.
if type_registry.is_eligible_carrier(&key) {
// no helper — handled inline
} else if type_registry.record_fields.contains_key(&key) {
eq_helpers.register_transitive(&key, EqKind::Record, type_registry);
} else if type_registry
.variants
.values()
.flat_map(|v| v.iter())
.any(|v| v.parent == key)
{
eq_helpers.register_transitive(&key, 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, symbol_table);
}
discover_builtins_in_expr(
&l.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
discover_builtins_in_expr(
&r.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
ResolvedExpr::Neg(inner) => {
discover_builtins_in_expr(
&inner.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
ResolvedExpr::Match { subject, arms } => {
discover_builtins_in_expr(
&subject.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
// 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::ir::hir::ResolvedPattern::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,
symbol_table,
);
}
}
ResolvedExpr::TailCall { args, .. } => {
for arg in args {
discover_builtins_in_expr(
&arg.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::Attr(obj, _) => discover_builtins_in_expr(
&obj.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
),
ResolvedExpr::ErrorProp(inner) => discover_builtins_in_expr(
&inner.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
),
ResolvedExpr::Ctor(_, args) => {
for a in args {
discover_builtins_in_expr(
&a.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::RecordCreate { fields, .. } => {
for (_, e) in fields {
discover_builtins_in_expr(
&e.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::RecordUpdate { base, updates, .. } => {
discover_builtins_in_expr(
&base.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
for (_, e) in updates {
discover_builtins_in_expr(
&e.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
// `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`.
ResolvedExpr::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 ResolvedStrPart::Parsed(inner) = p {
discover_builtins_in_expr(
&inner.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
}
ResolvedExpr::List(items) => {
for item in items {
discover_builtins_in_expr(
&item.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::Tuple(items) => {
for item in items {
discover_builtins_in_expr(
&item.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
ResolvedExpr::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,
symbol_table,
);
}
}
ResolvedExpr::MapLiteral(entries) => {
for (k, v) in entries {
discover_builtins_in_expr(
&k.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
discover_builtins_in_expr(
&v.node,
builtins,
effects,
eq_helpers,
type_registry,
symbol_table,
);
}
}
// A big-int literal lowers through `Int.fromString` (the string→bignum
// parser); register that helper so its wasm fn index is allocated.
ResolvedExpr::Literal(crate::ast::Literal::BigInt(_)) => {
builtins.register(BuiltinName::IntFromString);
}
_ => {}
}
}
/// Every fn name referenced as a value (`MirExpr::FnValue(name)`)
/// anywhere in the program, insertion-order deduped. These are the
/// "address-taken" fns — each needs a slot in the module's funcref
/// table so a `Fn`-param can carry its dense index. Mirror of the
/// full-tree walk shape `own_param.rs::visit_children` uses; built
/// here standalone so module assembly doesn't depend on optimizer
/// internals.
fn collect_address_taken(mir_program: &crate::ir::mir::MirProgram) -> Vec<String> {
use crate::ir::mir::{MirExpr, MirStrPart};
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut order: Vec<String> = Vec::new();
fn walk(
e: &crate::ir::mir::MirExpr,
seen: &mut std::collections::HashSet<String>,
order: &mut Vec<String>,
) {
match e {
MirExpr::Literal(_) | MirExpr::Local(_) => {}
MirExpr::FnValue(name) => {
if seen.insert(name.clone()) {
order.push(name.clone());
}
}
MirExpr::Let(l) => {
walk(&l.node.value.node, seen, order);
walk(&l.node.body.node, seen, order);
}
MirExpr::Call(c) => {
for a in &c.node.args {
walk(&a.node, seen, order);
}
}
MirExpr::TailCall(tc) => {
for a in &tc.node.args {
walk(&a.node, seen, order);
}
}
MirExpr::BinOp(b) => {
walk(&b.node.lhs.node, seen, order);
walk(&b.node.rhs.node, seen, order);
}
MirExpr::Neg(inner)
| MirExpr::Try(inner)
| MirExpr::Return(inner)
| MirExpr::Box(inner)
| MirExpr::Unbox(inner) => {
walk(&inner.node, seen, order);
}
MirExpr::Match(m) => {
walk(&m.node.subject.node, seen, order);
for arm in &m.node.arms {
walk(&arm.body.node, seen, order);
}
}
MirExpr::Construct(c) => {
for a in &c.node.args {
walk(&a.node, seen, order);
}
}
MirExpr::RecordCreate(r) => {
for field in &r.node.fields {
walk(&field.value.node, seen, order);
}
}
MirExpr::RecordUpdate(u) => {
walk(&u.node.base.node, seen, order);
for field in &u.node.updates {
walk(&field.value.node, seen, order);
}
}
MirExpr::Project(p) => walk(&p.node.base.node, seen, order),
MirExpr::IfThenElse(ite) => {
walk(&ite.node.cond.node, seen, order);
walk(&ite.node.then_branch.node, seen, order);
walk(&ite.node.else_branch.node, seen, order);
}
MirExpr::List(items) | MirExpr::Tuple(items) => {
for i in items {
walk(&i.node, seen, order);
}
}
MirExpr::MapLiteral(pairs) => {
for (k, v) in pairs {
walk(&k.node, seen, order);
walk(&v.node, seen, order);
}
}
MirExpr::InterpolatedStr(parts) => {
for p in parts {
if let MirStrPart::Expr(e) = p {
walk(&e.node, seen, order);
}
}
}
MirExpr::IndependentProduct(ip) => {
for i in &ip.node.items {
walk(&i.node, seen, order);
}
}
}
}
// Deterministic fn order — sort by FnId so the table index assigned
// to each name is stable across runs (HashMap iteration is not).
let mut fns: Vec<(&crate::ir::FnId, &crate::ir::mir::MirFn)> = mir_program.iter().collect();
fns.sort_by_key(|(id, _)| **id);
for (_, mir_fn) in fns {
walk(&mir_fn.body.node, &mut seen, &mut order);
}
order
}
/// Collect the unique `call_indirect` functypes the program needs: for
/// every `MirCallee::LocalSlot { name, .. }` call site, find the
/// enclosing fn's `Fn(..)` param whose name matches and lower its sig
/// to `(params, results)` + a dedupe key. Returns
/// `(key, (params, results))` per unique functype, in first-seen order.
/// LocalSlot names that are NOT a `Fn`-typed param (let-bound fn
/// values) are skipped — those call sites fall back to the trap stub.
///
/// `fn_params_by_id` resolves a `FnId` to the enclosing fn's params as
/// real `Type`s — the SAME `(String, Type)` slice `EmitCtx::params`
/// (the call-site key source) holds, so the key the body emitter
/// recomputes hits the entry registered here. (The `MirParam::ty`
/// string is a `{:?}` debug form, not parseable, so it can't be used.)
#[allow(clippy::type_complexity)]
fn collect_call_indirect_sigs(
mir_program: &crate::ir::mir::MirProgram,
fn_params_by_id: &HashMap<crate::ir::FnId, &[(String, crate::types::Type)]>,
registry: &super::types::TypeRegistry,
) -> Result<Vec<(String, (Vec<ValType>, Vec<ValType>))>, WasmGcError> {
use crate::ir::mir::{MirCallee, MirExpr, MirStrPart};
use crate::types::Type;
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut out: Vec<(String, (Vec<ValType>, Vec<ValType>))> = Vec::new();
// Walk `e`, calling `note(name)` for every `LocalSlot` callee name.
fn walk(e: &crate::ir::mir::MirExpr, note: &mut dyn FnMut(&str)) {
match e {
MirExpr::Literal(_) | MirExpr::Local(_) | MirExpr::FnValue(_) => {}
MirExpr::Let(l) => {
walk(&l.node.value.node, note);
walk(&l.node.body.node, note);
}
MirExpr::Call(c) => {
if let MirCallee::LocalSlot { name, .. } = &c.node.callee {
note(name);
}
for a in &c.node.args {
walk(&a.node, note);
}
}
MirExpr::TailCall(tc) => {
for a in &tc.node.args {
walk(&a.node, note);
}
}
MirExpr::BinOp(b) => {
walk(&b.node.lhs.node, note);
walk(&b.node.rhs.node, note);
}
MirExpr::Neg(inner)
| MirExpr::Try(inner)
| MirExpr::Return(inner)
| MirExpr::Box(inner)
| MirExpr::Unbox(inner) => walk(&inner.node, note),
MirExpr::Match(m) => {
walk(&m.node.subject.node, note);
for arm in &m.node.arms {
walk(&arm.body.node, note);
}
}
MirExpr::Construct(c) => {
for a in &c.node.args {
walk(&a.node, note);
}
}
MirExpr::RecordCreate(r) => {
for field in &r.node.fields {
walk(&field.value.node, note);
}
}
MirExpr::RecordUpdate(u) => {
walk(&u.node.base.node, note);
for field in &u.node.updates {
walk(&field.value.node, note);
}
}
MirExpr::Project(p) => walk(&p.node.base.node, note),
MirExpr::IfThenElse(ite) => {
walk(&ite.node.cond.node, note);
walk(&ite.node.then_branch.node, note);
walk(&ite.node.else_branch.node, note);
}
MirExpr::List(items) | MirExpr::Tuple(items) => {
for i in items {
walk(&i.node, note);
}
}
MirExpr::MapLiteral(pairs) => {
for (k, v) in pairs {
walk(&k.node, note);
walk(&v.node, note);
}
}
MirExpr::InterpolatedStr(parts) => {
for p in parts {
if let MirStrPart::Expr(e) = p {
walk(&e.node, note);
}
}
}
MirExpr::IndependentProduct(ip) => {
for i in &ip.node.items {
walk(&i.node, note);
}
}
}
}
let mut fns: Vec<(&crate::ir::FnId, &crate::ir::mir::MirFn)> = mir_program.iter().collect();
fns.sort_by_key(|(id, _)| **id);
for (fn_id, mir_fn) in fns {
let Some(params_real) = fn_params_by_id.get(fn_id) else {
continue;
};
// Per enclosing fn: collect every `LocalSlot` callee name.
let mut pending: Vec<String> = Vec::new();
walk(&mir_fn.body.node, &mut |name| {
pending.push(name.to_string())
});
for name in pending {
let Some((_, ty)) = params_real.iter().find(|(n, _)| *n == name) else {
// LocalSlot name isn't a param (let-bound fn value) →
// skip; that call site falls back to the trap stub.
continue;
};
let Type::Fn(args, ret, _) = ty else {
continue;
};
let (params, results) = super::types::fn_sig_wasm(args, ret, Some(registry))?;
let key = super::types::fn_sig_key(¶ms, &results);
if seen.insert(key.clone()) {
out.push((key, (params, results)));
}
}
}
Ok(out)
}
/// 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 fn_defs_use_string_split_join(fn_defs: &[crate::ir::hir::ResolvedFnDef]) -> bool {
use crate::ir::hir::{
ResolvedCallee, ResolvedExpr, ResolvedFnBody, ResolvedStmt, ResolvedStrPart,
};
fn walk(e: &ResolvedExpr) -> bool {
match e {
ResolvedExpr::Call(callee, args) => {
if let ResolvedCallee::Builtin(name) = callee
&& (name == "String.split" || name == "String.join")
{
return true;
}
args.iter().any(|a| walk(&a.node))
}
ResolvedExpr::BinOp(_, l, r) => walk(&l.node) || walk(&r.node),
ResolvedExpr::Neg(inner) => walk(&inner.node),
ResolvedExpr::Match { subject, arms } => {
walk(&subject.node) || arms.iter().any(|a| walk(&a.body.node))
}
ResolvedExpr::TailCall { args, .. } => args.iter().any(|a| walk(&a.node)),
ResolvedExpr::Attr(obj, _) => walk(&obj.node),
ResolvedExpr::RecordCreate { fields, .. } => fields.iter().any(|(_, e)| walk(&e.node)),
ResolvedExpr::Ctor(_, args) => args.iter().any(|a| walk(&a.node)),
ResolvedExpr::List(items)
| ResolvedExpr::Tuple(items)
| ResolvedExpr::IndependentProduct(items, _) => items.iter().any(|x| walk(&x.node)),
ResolvedExpr::ErrorProp(inner) => walk(&inner.node),
// A `String.split`/`String.join` can hide inside an interpolation
// (`"... {String.join(xs, sep)}"`) — the original arm returned
// `false` here, so a program that ONLY uses join via interpolation
// never registered the helper and the emitted call failed validation
// (examples/data/words.av). Walk the parsed parts. Over-detecting is
// safe: an unused helper is DCE'd by `wasm-opt`; under-detecting trapped.
ResolvedExpr::InterpolatedStr(parts) => parts
.iter()
.any(|p| matches!(p, ResolvedStrPart::Parsed(inner) if walk(&inner.node))),
_ => false,
}
}
for fd in fn_defs {
let ResolvedFnBody::Block(stmts) = fd.body.as_ref();
for stmt in stmts {
let e = match stmt {
ResolvedStmt::Binding { value: e, .. } | ResolvedStmt::Expr(e) => &e.node,
};
if walk(e) {
return true;
}
}
}
false
}
/// `__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.
// Tcp.send is ephemeral (Phase 4.7+ pass 4) — its body returns
// Result<String,String> directly and never materialises a
// Result<Unit,String>, so it's not in the union.
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 the pool-side Tcp.* effects (connect returns one; writeLine /
// readLine / close consume one). Tcp.send and Tcp.ping are
// ephemeral (Phase 4.7+ pass 4 + pass 5): neither materialises a
// `Tcp.Connection` nor calls `__rt_tcp_connect`, so they don't
// need the record/result slots.
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;
}
// `Result<Tcp.Connection, String>` factories — only Tcp.connect's
// emit body materialises this shape (the pool-allocate Ok arm + the
// dial-failure Err arms). Tcp.send / Tcp.ping went ephemeral in
// Phase 4.7+ (passes 4 / 5) and no longer route through it.
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.
// `Int = ℤ`: the host passes width/height as i64, but both
// `Terminal.Size` fields are the `$AverInt` carrier — lift each.
let lift = |f: &mut Function| -> Result<(), WasmGcError> {
if registry.bignum {
let from_i64 = registry
.aint_from_i64_fn_idx
.ok_or(WasmGcError::Validation(
"bignum Terminal.Size factory needs the __aint_from_i64 fn idx".into(),
))?;
f.instruction(&Instruction::Call(from_i64));
}
Ok(())
};
f.instruction(&Instruction::LocalGet(0));
lift(&mut f)?;
f.instruction(&Instruction::LocalGet(1));
lift(&mut f)?;
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));
// `Int = ℤ`: the host passes `port` as i64 (machine-range), but the
// `Tcp.Connection.port` field is the `$AverInt` carrier — lift it.
f.instruction(&Instruction::LocalGet(2));
if registry.bignum {
let from_i64 = registry
.aint_from_i64_fn_idx
.ok_or(WasmGcError::Validation(
"bignum Tcp.Connection factory needs the __aint_from_i64 fn idx".into(),
))?;
f.instruction(&Instruction::Call(from_i64));
}
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([]);
// `Int = ℤ`: the host passes the HTTP `status` as i64 (the ABI stays
// i64), but the `HttpResponse.status` field is the `$AverInt` carrier
// under bignum — lift it to a Small before `struct.new`.
f.instruction(&Instruction::LocalGet(0));
if registry.bignum {
let from_i64 = registry
.aint_from_i64_fn_idx
.ok_or(WasmGcError::Validation(
"bignum HttpResponse factory needs the __aint_from_i64 fn idx".into(),
))?;
f.instruction(&Instruction::Call(from_i64));
}
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 — under `Int = ℤ` the `HttpResponse.status` field is
// the `$AverInt` carrier (the factory lifts the host's i64 to a Small via
// `__aint_from_i64`), so lower it back to i64 before storing into the i64
// local the `Response.text` host import consumes. Mirror of
// `emit_factory_http_response_make`; saturating is safe — a status code
// always fits i64. Without this the wrapper stores a `(ref null $aint)` into
// an i64 local and the module fails wasm validation.
f.instruction(&Instruction::LocalGet(6));
f.instruction(&Instruction::StructGet {
struct_type_index: resp_idx,
field_index: 0,
});
if registry.bignum {
let to_i64 =
fn_map
.builtins
.get("__aint_to_i64_sat")
.copied()
.ok_or(WasmGcError::Validation(
"bignum aver_http_handle wrapper needs the __aint_to_i64_sat helper".into(),
))?;
f.instruction(&Instruction::Call(to_i64));
}
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,
println_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)?);
// println_to_lm(s) → i32 (= s.len + 1). Same shape as `to_lm`
// plus a `'\n'` (0x0A) byte at LM[len] before returning. Used
// by `Console.print` / `Console.error` / `Console.warn` on
// `--target wasip2` so the `Console.* == println!` semantic
// VM and AverBridge ship lives at the bridge layer instead of
// every call site appending the newline by hand. Body is a
// textual edit of `to_lm` with the trailing `local.get $len`
// swapped for "store '\n' at LM[len]; return len + 1".
let println_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 + 1 + 65535) >> 16
local.get $len
i32.const 1
i32.add
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))
;; LM[len] = '\n' (0x0A)
local.get $len
i32.const 10
i32.store8
;; return len + 1
local.get $len
i32.const 1
i32.add)
)
"#
);
codes.function(&wat_helper::compile_wat_helper(&println_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(())
}