wasmrun 0.19.0

A WebAssembly Runtime
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
/// WASM instruction executor
/// Handles execution context, stack, call frames, and instruction dispatch
use super::linker::Linker;
use super::memory::LinearMemory;
use super::module::{ImportKind, Module, ValueType};
use super::values::Value;
use std::io::Cursor;

/// Sentinel prefix for proc_exit errors so callers can extract the exit code.
pub const WASI_PROC_EXIT_PREFIX: &str = "__wasi_proc_exit:";

/// Result of instruction dispatch for control flow signaling
#[derive(Debug, Clone, PartialEq)]
enum ControlFlow {
    Continue,
    Return,
}

/// WASM instruction representation
/// Covers all instruction types from the WebAssembly specification
#[derive(Debug, Clone)]
pub enum Instruction {
    // Constants
    I32Const(i32),
    I64Const(i64),
    F32Const(f32),
    F64Const(f64),

    // Numeric operations - i32
    I32Clz,
    I32Ctz,
    I32Popcnt,
    I32Add,
    I32Sub,
    I32Mul,
    I32DivS,
    I32DivU,
    I32RemS,
    I32RemU,
    I32And,
    I32Or,
    I32Xor,
    I32Shl,
    I32ShrS,
    I32ShrU,
    I32Rotl,
    I32Rotr,
    I32Eqz,

    // Numeric operations - i64
    I64Clz,
    I64Ctz,
    I64Popcnt,
    I64Add,
    I64Sub,
    I64Mul,
    I64DivS,
    I64DivU,
    I64RemS,
    I64RemU,
    I64And,
    I64Or,
    I64Xor,
    I64Shl,
    I64ShrS,
    I64ShrU,
    I64Rotl,
    I64Rotr,
    I64Eqz,

    // Numeric operations - f32
    F32Add,
    F32Sub,
    F32Mul,
    F32Div,
    F32Sqrt,
    F32Min,
    F32Max,
    F32Ceil,
    F32Floor,
    F32Trunc,
    F32Nearest,
    F32Abs,
    F32Neg,
    F32Copysign,

    // Numeric operations - f64
    F64Add,
    F64Sub,
    F64Mul,
    F64Div,
    F64Sqrt,
    F64Min,
    F64Max,
    F64Ceil,
    F64Floor,
    F64Trunc,
    F64Nearest,
    F64Abs,
    F64Neg,
    F64Copysign,

    // Comparison - i32
    I32Eq,
    I32Ne,
    I32LtS,
    I32LtU,
    I32GtS,
    I32GtU,
    I32LeS,
    I32LeU,
    I32GeS,
    I32GeU,

    // Comparison - i64
    I64Eq,
    I64Ne,
    I64LtS,
    I64LtU,
    I64GtS,
    I64GtU,
    I64LeS,
    I64LeU,
    I64GeS,
    I64GeU,

    // Comparison - f32
    F32Eq,
    F32Ne,
    F32Lt,
    F32Gt,
    F32Le,
    F32Ge,

    // Comparison - f64
    F64Eq,
    F64Ne,
    F64Lt,
    F64Gt,
    F64Le,
    F64Ge,

    // Type conversions
    I32WrapI64,
    I32TruncF32S,
    I32TruncF32U,
    I32TruncF64S,
    I32TruncF64U,
    I64ExtendI32S,
    I64ExtendI32U,
    I64TruncF32S,
    I64TruncF32U,
    I64TruncF64S,
    I64TruncF64U,
    F32ConvertI32S,
    F32ConvertI32U,
    F32ConvertI64S,
    F32ConvertI64U,
    F32DemoteF64,
    F64ConvertI32S,
    F64ConvertI32U,
    F64ConvertI64S,
    F64ConvertI64U,
    F64PromoteF32,
    I32Reinterpret,
    I64Reinterpret,
    F32Reinterpret,
    F64Reinterpret,

    // Memory — each carries the offset immediate from the instruction encoding.
    // Effective address = stack_addr + offset.
    I32Load(u32),
    I64Load(u32),
    F32Load(u32),
    F64Load(u32),
    I32Load8S(u32),
    I32Load8U(u32),
    I32Load16S(u32),
    I32Load16U(u32),
    I64Load8S(u32),
    I64Load8U(u32),
    I64Load16S(u32),
    I64Load16U(u32),
    I64Load32S(u32),
    I64Load32U(u32),
    I32Store(u32),
    I64Store(u32),
    F32Store(u32),
    F64Store(u32),
    I32Store8(u32),
    I32Store16(u32),
    I64Store8(u32),
    I64Store16(u32),
    I64Store32(u32),
    MemorySize,
    MemoryGrow,

    // Sign-extension operators (WASM sign-extension proposal)
    I32Extend8S,
    I32Extend16S,
    I64Extend8S,
    I64Extend16S,
    I64Extend32S,

    // Bulk-memory (0xFC prefix) — WASM bulk-memory extension
    MemoryCopy,
    MemoryFill,
    MemoryInit(u32), // data segment index
    DataDrop(u32),   // data segment index

    // Local/Global
    LocalGet(u32),
    LocalSet(u32),
    LocalTee(u32),
    GlobalGet(u32),
    GlobalSet(u32),

    // Control flow
    Nop,
    Unreachable,
    Block(Option<ValueType>),
    Loop(Option<ValueType>),
    If(Option<ValueType>),
    Else,
    End,
    Br(u32),
    BrIf(u32),
    BrTable(Vec<u32>, u32),
    Return,
    Call(u32),
    CallIndirect(u32),
    Drop,
    Select,
}
/// Helper function to read a single byte
fn read_u8(cursor: &mut Cursor<&[u8]>) -> Result<u8, String> {
    let mut byte_buf = [0u8; 1];
    if std::io::Read::read(cursor, &mut byte_buf).is_err() {
        return Err("EOF while reading byte".to_string());
    }
    Ok(byte_buf[0])
}

/// Decode block type (for block, loop, if instructions)
fn decode_block_type(cursor: &mut Cursor<&[u8]>) -> Result<Option<ValueType>, String> {
    let byte = read_u8(cursor)?;
    match byte {
        0x40 => Ok(None), // empty block type (no result)
        0x7F => Ok(Some(ValueType::I32)),
        0x7E => Ok(Some(ValueType::I64)),
        0x7D => Ok(Some(ValueType::F32)),
        0x7C => Ok(Some(ValueType::F64)),
        // Function type index (0x00-0x3F) - for multi-value blocks
        // For now, treat as empty (no result)
        0x00..=0x3F => Ok(None),
        _ => Err(format!("Invalid block type: 0x{byte:02X}")),
    }
}

/// Helper function to decode a LEB128-encoded signed integer
fn decode_i32_leb128(cursor: &mut Cursor<&[u8]>) -> Result<i32, String> {
    let mut result: i32 = 0;
    let mut shift = 0;
    let mut byte_buf = [0u8; 1];

    loop {
        if std::io::Read::read(cursor, &mut byte_buf).is_err() {
            return Err("EOF while reading LEB128".to_string());
        }
        let byte = byte_buf[0];
        result |= ((byte & 0x7f) as i32) << shift;

        if (byte & 0x80) == 0 {
            // Sign extend if the sign bit in the final LEB128 byte is set and
            // shift+7 is still within the i32 range. At shift=28, the 5th byte
            // already contributes bit 31 directly, so no extension is needed.
            if shift + 7 < 32 && (byte & 0x40) != 0 {
                result |= (-1i32) << (shift + 7);
            }
            return Ok(result);
        }
        shift += 7;
        if shift >= 32 {
            return Err("LEB128 value too large for i32".to_string());
        }
    }
}

/// Helper function to decode a LEB128-encoded unsigned integer
fn decode_u32_leb128(cursor: &mut Cursor<&[u8]>) -> Result<u32, String> {
    let mut result: u32 = 0;
    let mut shift = 0;
    let mut byte_buf = [0u8; 1];

    loop {
        if std::io::Read::read(cursor, &mut byte_buf).is_err() {
            return Err("EOF while reading LEB128".to_string());
        }
        let byte = byte_buf[0];
        result |= ((byte & 0x7f) as u32) << shift;

        if (byte & 0x80) == 0 {
            return Ok(result);
        }
        shift += 7;
        if shift >= 35 {
            return Err("LEB128 value too large for u32".to_string());
        }
    }
}

/// Helper function to decode a LEB128-encoded signed i64
fn decode_i64_leb128(cursor: &mut Cursor<&[u8]>) -> Result<i64, String> {
    let mut result: i64 = 0;
    let mut shift = 0;
    let mut byte_buf = [0u8; 1];

    loop {
        if std::io::Read::read(cursor, &mut byte_buf).is_err() {
            return Err("EOF while reading LEB128".to_string());
        }
        let byte = byte_buf[0];
        result |= ((byte & 0x7f) as i64) << shift;

        if (byte & 0x80) == 0 {
            // Sign extend if the sign bit in the final LEB128 byte is set and
            // shift+7 is still within the i64 range.
            if shift + 7 < 64 && (byte & 0x40) != 0 {
                result |= (-1i64) << (shift + 7);
            }
            return Ok(result);
        }
        shift += 7;
        if shift >= 64 {
            return Err("LEB128 value too large for i64".to_string());
        }
    }
}

/// Decode a single WASM instruction from bytecode
pub fn decode_instruction(cursor: &mut Cursor<&[u8]>) -> Result<Instruction, String> {
    let mut byte_buf = [0u8; 1];
    if std::io::Read::read(cursor, &mut byte_buf).is_err() {
        return Err("EOF while reading instruction".to_string());
    }
    let byte = byte_buf[0];

    match byte {
        // Constants
        0x41 => Ok(Instruction::I32Const(decode_i32_leb128(cursor)?)),
        0x42 => Ok(Instruction::I64Const(decode_i64_leb128(cursor)?)),
        0x43 => {
            let mut buf = [0u8; 4];
            if std::io::Read::read(cursor, &mut buf).is_err() {
                return Err("EOF while reading f32".to_string());
            }
            Ok(Instruction::F32Const(f32::from_le_bytes(buf)))
        }
        0x44 => {
            let mut buf = [0u8; 8];
            if std::io::Read::read(cursor, &mut buf).is_err() {
                return Err("EOF while reading f64".to_string());
            }
            Ok(Instruction::F64Const(f64::from_le_bytes(buf)))
        }

        // i32 test
        0x45 => Ok(Instruction::I32Eqz),

        // i32 comparison
        0x46 => Ok(Instruction::I32Eq),
        0x47 => Ok(Instruction::I32Ne),
        0x48 => Ok(Instruction::I32LtS),
        0x49 => Ok(Instruction::I32LtU),
        0x4A => Ok(Instruction::I32GtS),
        0x4B => Ok(Instruction::I32GtU),
        0x4C => Ok(Instruction::I32LeS),
        0x4D => Ok(Instruction::I32LeU),
        0x4E => Ok(Instruction::I32GeS),
        0x4F => Ok(Instruction::I32GeU),

        // i64 test
        0x50 => Ok(Instruction::I64Eqz),

        // i64 comparison
        0x51 => Ok(Instruction::I64Eq),
        0x52 => Ok(Instruction::I64Ne),
        0x53 => Ok(Instruction::I64LtS),
        0x54 => Ok(Instruction::I64LtU),
        0x55 => Ok(Instruction::I64GtS),
        0x56 => Ok(Instruction::I64GtU),
        0x57 => Ok(Instruction::I64LeS),
        0x58 => Ok(Instruction::I64LeU),
        0x59 => Ok(Instruction::I64GeS),
        0x5A => Ok(Instruction::I64GeU),

        // f32 comparison
        0x5B => Ok(Instruction::F32Eq),
        0x5C => Ok(Instruction::F32Ne),
        0x5D => Ok(Instruction::F32Lt),
        0x5E => Ok(Instruction::F32Gt),
        0x5F => Ok(Instruction::F32Le),
        0x60 => Ok(Instruction::F32Ge),

        // f64 comparison
        0x61 => Ok(Instruction::F64Eq),
        0x62 => Ok(Instruction::F64Ne),
        0x63 => Ok(Instruction::F64Lt),
        0x64 => Ok(Instruction::F64Gt),
        0x65 => Ok(Instruction::F64Le),
        0x66 => Ok(Instruction::F64Ge),

        // i32 unary operations
        0x67 => Ok(Instruction::I32Clz),
        0x68 => Ok(Instruction::I32Ctz),
        0x69 => Ok(Instruction::I32Popcnt),

        // i32 arithmetic operations
        0x6A => Ok(Instruction::I32Add),
        0x6B => Ok(Instruction::I32Sub),
        0x6C => Ok(Instruction::I32Mul),
        0x6D => Ok(Instruction::I32DivS),
        0x6E => Ok(Instruction::I32DivU),
        0x6F => Ok(Instruction::I32RemS),
        0x70 => Ok(Instruction::I32RemU),
        0x71 => Ok(Instruction::I32And),
        0x72 => Ok(Instruction::I32Or),
        0x73 => Ok(Instruction::I32Xor),
        0x74 => Ok(Instruction::I32Shl),
        0x75 => Ok(Instruction::I32ShrS),
        0x76 => Ok(Instruction::I32ShrU),
        0x77 => Ok(Instruction::I32Rotl),
        0x78 => Ok(Instruction::I32Rotr),

        // i64 unary operations
        0x79 => Ok(Instruction::I64Clz),
        0x7A => Ok(Instruction::I64Ctz),
        0x7B => Ok(Instruction::I64Popcnt),

        // i64 arithmetic operations
        0x7C => Ok(Instruction::I64Add),
        0x7D => Ok(Instruction::I64Sub),
        0x7E => Ok(Instruction::I64Mul),
        0x7F => Ok(Instruction::I64DivS),
        0x80 => Ok(Instruction::I64DivU),
        0x81 => Ok(Instruction::I64RemS),
        0x82 => Ok(Instruction::I64RemU),
        0x83 => Ok(Instruction::I64And),
        0x84 => Ok(Instruction::I64Or),
        0x85 => Ok(Instruction::I64Xor),
        0x86 => Ok(Instruction::I64Shl),
        0x87 => Ok(Instruction::I64ShrS),
        0x88 => Ok(Instruction::I64ShrU),
        0x89 => Ok(Instruction::I64Rotl),
        0x8A => Ok(Instruction::I64Rotr),

        // f32 unary operations
        0x8B => Ok(Instruction::F32Abs),
        0x8C => Ok(Instruction::F32Neg),
        0x8D => Ok(Instruction::F32Ceil),
        0x8E => Ok(Instruction::F32Floor),
        0x8F => Ok(Instruction::F32Trunc),
        0x90 => Ok(Instruction::F32Nearest),
        0x91 => Ok(Instruction::F32Sqrt),

        // f32 binary operations
        0x92 => Ok(Instruction::F32Add),
        0x93 => Ok(Instruction::F32Sub),
        0x94 => Ok(Instruction::F32Mul),
        0x95 => Ok(Instruction::F32Div),
        0x96 => Ok(Instruction::F32Min),
        0x97 => Ok(Instruction::F32Max),
        0x98 => Ok(Instruction::F32Copysign),

        // f64 unary operations
        0x99 => Ok(Instruction::F64Abs),
        0x9A => Ok(Instruction::F64Neg),
        0x9B => Ok(Instruction::F64Ceil),
        0x9C => Ok(Instruction::F64Floor),
        0x9D => Ok(Instruction::F64Trunc),
        0x9E => Ok(Instruction::F64Nearest),
        0x9F => Ok(Instruction::F64Sqrt),

        // f64 binary operations
        0xA0 => Ok(Instruction::F64Add),
        0xA1 => Ok(Instruction::F64Sub),
        0xA2 => Ok(Instruction::F64Mul),
        0xA3 => Ok(Instruction::F64Div),
        0xA4 => Ok(Instruction::F64Min),
        0xA5 => Ok(Instruction::F64Max),
        0xA6 => Ok(Instruction::F64Copysign),

        // Type conversions
        0xA7 => Ok(Instruction::I32WrapI64),
        0xA8 => Ok(Instruction::I32TruncF32S),
        0xA9 => Ok(Instruction::I32TruncF32U),
        0xAA => Ok(Instruction::I32TruncF64S),
        0xAB => Ok(Instruction::I32TruncF64U),
        0xAC => Ok(Instruction::I64ExtendI32S),
        0xAD => Ok(Instruction::I64ExtendI32U),
        0xAE => Ok(Instruction::I64TruncF32S),
        0xAF => Ok(Instruction::I64TruncF32U),
        0xB0 => Ok(Instruction::I64TruncF64S),
        0xB1 => Ok(Instruction::I64TruncF64U),
        0xB2 => Ok(Instruction::F32ConvertI32S),
        0xB3 => Ok(Instruction::F32ConvertI32U),
        0xB4 => Ok(Instruction::F32ConvertI64S),
        0xB5 => Ok(Instruction::F32ConvertI64U),
        0xB6 => Ok(Instruction::F32DemoteF64),
        0xB7 => Ok(Instruction::F64ConvertI32S),
        0xB8 => Ok(Instruction::F64ConvertI32U),
        0xB9 => Ok(Instruction::F64ConvertI64S),
        0xBA => Ok(Instruction::F64ConvertI64U),
        0xBB => Ok(Instruction::F64PromoteF32),
        0xBC => Ok(Instruction::I32Reinterpret),
        0xBD => Ok(Instruction::I64Reinterpret),
        0xBE => Ok(Instruction::F32Reinterpret),
        0xBF => Ok(Instruction::F64Reinterpret),

        // Memory (each has memarg: align + offset)
        // offset is an immediate added to the stack address: effective_addr = stack_val + offset
        0x28 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Load(offset))
        }
        0x29 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load(offset))
        }
        0x2A => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::F32Load(offset))
        }
        0x2B => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::F64Load(offset))
        }
        0x2C => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Load8S(offset))
        }
        0x2D => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Load8U(offset))
        }
        0x2E => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Load16S(offset))
        }
        0x2F => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Load16U(offset))
        }
        0x30 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load8S(offset))
        }
        0x31 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load8U(offset))
        }
        0x32 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load16S(offset))
        }
        0x33 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load16U(offset))
        }
        0x34 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load32S(offset))
        }
        0x35 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Load32U(offset))
        }
        0x36 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Store(offset))
        }
        0x37 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Store(offset))
        }
        0x38 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::F32Store(offset))
        }
        0x39 => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::F64Store(offset))
        }
        0x3A => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Store8(offset))
        }
        0x3B => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I32Store16(offset))
        }
        0x3C => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Store8(offset))
        }
        0x3D => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Store16(offset))
        }
        0x3E => {
            let _align = decode_u32_leb128(cursor)?;
            let offset = decode_u32_leb128(cursor)?;
            Ok(Instruction::I64Store32(offset))
        }
        0x3F => {
            // memory.size - reads memory index (0x00)
            let _mem_idx = read_u8(cursor)?;
            Ok(Instruction::MemorySize)
        }
        0x40 => {
            // memory.grow - reads memory index (0x00)
            let _mem_idx = read_u8(cursor)?;
            Ok(Instruction::MemoryGrow)
        }

        // Local/Global
        0x20 => Ok(Instruction::LocalGet(decode_u32_leb128(cursor)?)),
        0x21 => Ok(Instruction::LocalSet(decode_u32_leb128(cursor)?)),
        0x22 => Ok(Instruction::LocalTee(decode_u32_leb128(cursor)?)),
        0x23 => Ok(Instruction::GlobalGet(decode_u32_leb128(cursor)?)),
        0x24 => Ok(Instruction::GlobalSet(decode_u32_leb128(cursor)?)),

        // Control flow
        0x00 => Ok(Instruction::Unreachable),
        0x01 => Ok(Instruction::Nop),
        0x02 => {
            // block - read block type
            let block_type = decode_block_type(cursor)?;
            Ok(Instruction::Block(block_type))
        }
        0x03 => {
            // loop - read block type
            let block_type = decode_block_type(cursor)?;
            Ok(Instruction::Loop(block_type))
        }
        0x04 => {
            // if - read block type
            let block_type = decode_block_type(cursor)?;
            Ok(Instruction::If(block_type))
        }
        0x05 => Ok(Instruction::Else),
        0x0B => Ok(Instruction::End),
        0x0C => Ok(Instruction::Br(decode_u32_leb128(cursor)?)),
        0x0D => Ok(Instruction::BrIf(decode_u32_leb128(cursor)?)),
        0x0E => {
            let count = decode_u32_leb128(cursor)? as usize;
            let mut targets = Vec::with_capacity(count);
            for _ in 0..count {
                targets.push(decode_u32_leb128(cursor)?);
            }
            let default = decode_u32_leb128(cursor)?;
            Ok(Instruction::BrTable(targets, default))
        }
        0x0F => Ok(Instruction::Return),
        0x10 => Ok(Instruction::Call(decode_u32_leb128(cursor)?)),
        0x11 => {
            let type_idx = decode_u32_leb128(cursor)?;
            let _table_idx = read_u8(cursor)?; // table index (always 0x00 in WASM MVP)
            Ok(Instruction::CallIndirect(type_idx))
        }
        0x1A => Ok(Instruction::Drop),
        0x1B => Ok(Instruction::Select),

        // Sign-extension operators (WASM sign-extension proposal)
        0xC0 => Ok(Instruction::I32Extend8S),
        0xC1 => Ok(Instruction::I32Extend16S),
        0xC2 => Ok(Instruction::I64Extend8S),
        0xC3 => Ok(Instruction::I64Extend16S),
        0xC4 => Ok(Instruction::I64Extend32S),

        // Bulk-memory prefix byte (WASM bulk-memory extension)
        0xFC => {
            let op = decode_u32_leb128(cursor)?;
            match op {
                8 => {
                    // memory.init: seg_idx mem_idx(0x00)
                    let seg_idx = decode_u32_leb128(cursor)?;
                    let _mem_idx = read_u8(cursor)?;
                    Ok(Instruction::MemoryInit(seg_idx))
                }
                9 => {
                    // data.drop: seg_idx
                    let seg_idx = decode_u32_leb128(cursor)?;
                    Ok(Instruction::DataDrop(seg_idx))
                }
                10 => {
                    // memory.copy: dst_mem(0x00) src_mem(0x00)
                    let _dst = read_u8(cursor)?;
                    let _src = read_u8(cursor)?;
                    Ok(Instruction::MemoryCopy)
                }
                11 => {
                    // memory.fill: mem_idx(0x00)
                    let _mem_idx = read_u8(cursor)?;
                    Ok(Instruction::MemoryFill)
                }
                _ => Err(format!("Unknown 0xFC sub-opcode: {op}")),
            }
        }

        _ => Err(format!("Unknown instruction: 0x{byte:02X}")),
    }
}

/// Represents a single function call frame on the call stack
/// Control flow block state for branching
#[derive(Debug, Clone)]
pub struct BlockFrame {
    /// Block type (None for Block/Loop, Some for If)
    pub block_type: Option<ValueType>,
    /// Stack depth at block entry
    pub stack_depth: usize,
    /// Whether this is a loop (affects branching)
    pub is_loop: bool,
    /// Bytecode position of the block start
    pub start_pos: usize,
    /// Bytecode position after 'end' instruction (branch target)
    pub end_pos: usize,
    /// For if blocks: whether we're in the then-branch (true) or else-branch (false)
    pub is_then_branch: bool,
}

#[derive(Debug, Clone)]
pub struct Frame {
    /// Function index being executed
    pub func_idx: u32,
    /// Local variables in this frame
    pub locals: Vec<Value>,
    /// Return address (instruction pointer in calling function)
    pub return_addr: usize,
    /// Number of return values expected
    pub num_returns: usize,
    /// Operand stack depth at function entry (after popping args).
    /// Used by `return` to restore the stack to the correct depth.
    pub base_stack_depth: usize,
}

impl Frame {
    pub fn new(func_idx: u32, locals: Vec<Value>, num_returns: usize) -> Self {
        Frame {
            func_idx,
            locals,
            return_addr: 0,
            num_returns,
            base_stack_depth: 0,
        }
    }

    pub fn get_local(&self, idx: usize) -> Result<Value, String> {
        self.locals.get(idx).copied().ok_or_else(|| {
            format!(
                "Local variable index {} out of bounds ({})",
                idx,
                self.locals.len()
            )
        })
    }

    pub fn set_local(&mut self, idx: usize, value: Value) -> Result<(), String> {
        if idx >= self.locals.len() {
            return Err(format!(
                "Local variable index {} out of bounds ({})",
                idx,
                self.locals.len()
            ));
        }
        self.locals[idx] = value;
        Ok(())
    }
}

/// Execution context for WASM module execution
#[derive(Debug)]
pub struct ExecutionContext {
    /// Call stack (stack of frames)
    pub call_stack: Vec<Frame>,
    /// Operand stack (values pushed/popped during execution)
    pub operand_stack: Vec<Value>,
    /// Linear memory
    pub memory: LinearMemory,
    /// Control flow block stack (for block, loop, if)
    pub block_stack: Vec<BlockFrame>,
    /// Global variable values (mutable)
    pub globals: Vec<Value>,
}

impl ExecutionContext {
    /// Create new execution context with given memory config
    pub fn new(memory_initial: u32, memory_max: Option<u32>) -> Result<Self, String> {
        let memory = LinearMemory::new(memory_initial, memory_max)?;
        Ok(ExecutionContext {
            call_stack: Vec::new(),
            operand_stack: Vec::new(),
            memory,
            block_stack: Vec::new(),
            globals: Vec::new(),
        })
    }

    /// Push a value onto operand stack
    pub fn push(&mut self, value: Value) {
        self.operand_stack.push(value);
    }

    /// Pop a value from operand stack
    pub fn pop(&mut self) -> Result<Value, String> {
        self.operand_stack.pop().ok_or_else(|| {
            let call_stack: Vec<u32> = self.call_stack.iter().map(|f| f.func_idx).collect();
            format!("Operand stack underflow (call_stack={call_stack:?})")
        })
    }

    /// Peek top value without removing it
    pub fn peek(&self) -> Result<Value, String> {
        self.operand_stack
            .last()
            .copied()
            .ok_or_else(|| "Operand stack is empty".to_string())
    }

    /// Pop n values from operand stack
    pub fn pop_n(&mut self, n: usize) -> Result<Vec<Value>, String> {
        if self.operand_stack.len() < n {
            return Err(format!(
                "Operand stack underflow: need {}, have {}",
                n,
                self.operand_stack.len()
            ));
        }
        let idx = self.operand_stack.len() - n;
        Ok(self.operand_stack.drain(idx..).collect())
    }

    /// Push call frame
    pub fn push_frame(&mut self, frame: Frame) {
        self.call_stack.push(frame);
    }

    /// Pop call frame
    pub fn pop_frame(&mut self) -> Result<Frame, String> {
        self.call_stack
            .pop()
            .ok_or_else(|| "Call stack underflow".to_string())
    }

    /// Get current frame (mutable)
    pub fn current_frame_mut(&mut self) -> Result<&mut Frame, String> {
        self.call_stack
            .last_mut()
            .ok_or_else(|| "No active frame".to_string())
    }

    /// Get current frame
    pub fn current_frame(&self) -> Result<&Frame, String> {
        self.call_stack
            .last()
            .ok_or_else(|| "No active frame".to_string())
    }

    /// Push a control flow block
    pub fn push_block(
        &mut self,
        block_type: Option<ValueType>,
        is_loop: bool,
        start_pos: usize,
        end_pos: usize,
        is_then_branch: bool,
    ) {
        let stack_depth = self.operand_stack.len();
        self.block_stack.push(BlockFrame {
            block_type,
            stack_depth,
            is_loop,
            start_pos,
            end_pos,
            is_then_branch,
        });
    }

    /// Pop a control flow block
    pub fn pop_block(&mut self) -> Result<BlockFrame, String> {
        self.block_stack
            .pop()
            .ok_or_else(|| "Block stack underflow".to_string())
    }

    /// Get current block
    pub fn current_block(&self) -> Result<&BlockFrame, String> {
        self.block_stack
            .last()
            .ok_or_else(|| "No active block".to_string())
    }
}

/// Evaluate a constant expression as a Value (used for global initialization).
/// Handles i32.const, i64.const, f32.const, f64.const, and global.get.
fn evaluate_const_expr_value(expr: &[u8], already_init: &[Value]) -> Result<Value, String> {
    if expr.is_empty() {
        return Ok(Value::I32(0));
    }
    let mut cursor = Cursor::new(expr);
    let instr = decode_instruction(&mut cursor)?;
    match instr {
        Instruction::I32Const(v) => Ok(Value::I32(v)),
        Instruction::I64Const(v) => Ok(Value::I64(v)),
        Instruction::F32Const(v) => Ok(Value::F32(v)),
        Instruction::F64Const(v) => Ok(Value::F64(v)),
        Instruction::GlobalGet(idx) => {
            // global.get in an init_expr refers to an already-initialized global
            already_init
                .get(idx as usize)
                .copied()
                .ok_or_else(|| format!("global.get {idx} out of bounds in const expr"))
        }
        _ => Err(format!(
            "Unsupported constant expression instruction: {instr:?}"
        )),
    }
}

/// Evaluate a constant expression as an address offset (used for data/element segment offsets).
/// Supports i32.const and i64.const followed by end.
fn evaluate_const_expr(expr: &[u8]) -> Result<usize, String> {
    match evaluate_const_expr_value(expr, &[])? {
        Value::I32(v) => Ok(v as u32 as usize),
        Value::I64(v) => Ok(v as u64 as usize),
        other => Err(format!("Expected i32/i64 in const expr, got {other:?}")),
    }
}

/// WASM instruction executor
pub struct Executor {
    context: ExecutionContext,
    module: Module,
    linker: Option<Linker>,
    import_func_count: usize,
    /// Flat function table initialized from element segments.
    /// Index = table slot, value = absolute function index (or None if unset).
    table: Vec<Option<u32>>,
}

impl Executor {
    /// Create new executor for module (no host function support).
    pub fn new(module: Module) -> Result<Self, String> {
        Self::build(module, None)
    }

    /// Create executor with a linker that provides host functions for imports.
    pub fn new_with_linker(module: Module, linker: Linker) -> Result<Self, String> {
        Self::build(module, Some(linker))
    }

    fn build(module: Module, linker: Option<Linker>) -> Result<Self, String> {
        let import_func_count = module
            .imports
            .iter()
            .filter(|i| matches!(i.kind, ImportKind::Function(_)))
            .count();

        // Memory config: check module section first, then imported memory
        let (initial, max) = if let Some(mem) = &module.memory {
            (mem.initial, mem.max)
        } else {
            let imported_mem = module.imports.iter().find_map(|i| match &i.kind {
                ImportKind::Memory(mem) => Some((mem.initial, mem.max)),
                _ => None,
            });
            imported_mem.unwrap_or((1, None))
        };

        let mut context = ExecutionContext::new(initial, max)?;

        for global in &module.globals {
            let init_val = if global.init_expr.is_empty() {
                match global.value_type {
                    ValueType::I32 => Value::I32(0),
                    ValueType::I64 => Value::I64(0),
                    ValueType::F32 => Value::F32(0.0),
                    ValueType::F64 => Value::F64(0.0),
                    _ => return Err(format!("Unsupported global type: {:?}", global.value_type)),
                }
            } else {
                evaluate_const_expr_value(&global.init_expr, &context.globals)
                    .map_err(|e| format!("Global init expr error: {e}"))?
            };
            context.globals.push(init_val);
        }

        for segment in &module.data {
            if segment.offset_expr.is_empty() {
                continue;
            }
            let offset = evaluate_const_expr(&segment.offset_expr)?;
            let end = offset + segment.data.len();
            let mem_size = context.memory.size_bytes();
            if end > mem_size {
                return Err(format!(
                    "Data segment out of bounds: offset={offset}, len={}, memory size={mem_size}",
                    segment.data.len()
                ));
            }
            context.memory.write_bytes(offset, &segment.data)?;
        }

        // Build a flat function table from active element segments.
        // Each active segment has an offset (where in the table it starts) and a list of
        // function indices. We compute table[offset + i] = function_indices[i].
        let mut table: Vec<Option<u32>> = Vec::new();
        for seg in &module.elements {
            if seg.offset_expr.is_empty() {
                // Passive element segment — skip (filled lazily via table.init)
                continue;
            }
            let offset = evaluate_const_expr(&seg.offset_expr)?;
            let end = offset + seg.function_indices.len();
            if end > table.len() {
                table.resize(end, None);
            }
            for (i, &func_idx) in seg.function_indices.iter().enumerate() {
                table[offset + i] = Some(func_idx);
            }
        }

        Ok(Executor {
            context,
            module,
            linker,
            import_func_count,
            table,
        })
    }

    /// Execute a function by index and return its results
    pub fn execute(&mut self, func_idx: u32) -> Result<Vec<Value>, String> {
        self.execute_with_args(func_idx, Vec::new())
    }

    /// Execute a function with arguments and return its results
    pub fn execute_with_args(
        &mut self,
        func_idx: u32,
        args: Vec<Value>,
    ) -> Result<Vec<Value>, String> {
        // If func_idx refers to an import, dispatch through the linker
        if (func_idx as usize) < self.import_func_count {
            return self.call_host_function_with_args(func_idx, args);
        }

        let defined_idx = func_idx as usize - self.import_func_count;

        // Get function signature and code (clone to avoid borrow issues)
        let func = {
            let func = self.module.functions.get(defined_idx).ok_or_else(|| {
                format!("Function index {func_idx} out of bounds (defined index {defined_idx})")
            })?;

            let func_type = self
                .module
                .types
                .get(func.type_index as usize)
                .ok_or_else(|| format!("Function type index {} out of bounds", func.type_index))?;

            // Initialize locals: parameters + local variables
            let mut locals = Vec::new();

            // Add parameter slots (initialized with provided arguments or zero)
            for (i, _param_type) in func_type.params.iter().enumerate() {
                if i < args.len() {
                    locals.push(args[i]);
                } else {
                    locals.push(Value::I32(0)); // Placeholder for missing parameters
                }
            }

            // Add local variable slots
            for (count, value_type) in &func.locals {
                for _ in 0..*count {
                    let default_value = match value_type {
                        ValueType::I32 => Value::I32(0),
                        ValueType::I64 => Value::I64(0),
                        ValueType::F32 => Value::F32(0.0),
                        ValueType::F64 => Value::F64(0.0),
                        _ => {
                            return Err(format!("Unsupported value type in locals: {value_type:?}"))
                        }
                    };
                    locals.push(default_value);
                }
            }

            // Return tuple with locals, num_returns, and code
            (locals, func_type.results.len(), func.code.clone())
        };

        let (locals, num_returns, code) = func;

        // Create call frame
        let mut frame = Frame::new(func_idx, locals, num_returns);
        frame.base_stack_depth = self.context.operand_stack.len();
        self.context.push_frame(frame);

        let block_depth_before = self.context.block_stack.len();
        // WASM spec: every function body is implicitly wrapped in a block.
        // Push it so the function-terminating 0x0b End byte pops this frame
        // rather than accidentally popping the caller's block frames.
        self.context.push_block(None, false, 0, 0, false);

        // Execute bytecode
        let mut cursor = Cursor::new(code.as_slice());
        let result = self.execute_bytecode(&mut cursor);
        self.context.block_stack.truncate(block_depth_before);
        result?;

        // Pop frame and collect return values
        let _frame = self.context.pop_frame()?;

        // Pop return values from stack (in reverse order)
        let mut results = Vec::new();
        for _ in 0..num_returns {
            results.push(self.context.pop()?);
        }
        results.reverse();

        Ok(results)
    }

    /// Execute bytecode starting from current position in cursor
    fn execute_bytecode(&mut self, cursor: &mut Cursor<&[u8]>) -> Result<(), String> {
        loop {
            if cursor.position() >= cursor.get_ref().len() as u64 {
                break;
            }

            let instr = decode_instruction(cursor)?;
            if self.dispatch_instruction(instr, cursor)? == ControlFlow::Return {
                break;
            }
        }
        Ok(())
    }

    /// Skip bytecode until we find the matching else or end instruction.
    /// Returns true if we stopped at an `else`, false if we stopped at an `end`.
    fn skip_to_else_or_end(&mut self, cursor: &mut Cursor<&[u8]>) -> Result<bool, String> {
        let mut depth = 0;

        loop {
            if cursor.position() >= cursor.get_ref().len() as u64 {
                return Err("Unexpected EOF while seeking else/end".to_string());
            }

            let instr = decode_instruction(cursor)?;
            match instr {
                Instruction::Block(_) | Instruction::Loop(_) | Instruction::If(_) => {
                    depth += 1;
                }
                Instruction::Else if depth == 0 => {
                    // Found matching else — cursor is now after `else`
                    return Ok(true);
                }
                Instruction::End => {
                    if depth == 0 {
                        // Found matching end (no else branch) — cursor is now after `end`
                        return Ok(false);
                    }
                    depth -= 1;
                }
                _ => {}
            }
        }
    }

    /// Skip bytecode until we find the matching end instruction
    fn skip_to_end(&mut self, cursor: &mut Cursor<&[u8]>) -> Result<(), String> {
        self.skip_n_ends(cursor, 1)
    }

    /// Skip past `n` unmatched end instructions in the bytecode
    fn skip_n_ends(&mut self, cursor: &mut Cursor<&[u8]>, n: usize) -> Result<(), String> {
        let mut depth: i32 = 0;
        let mut ends_found: usize = 0;

        loop {
            if cursor.position() >= cursor.get_ref().len() as u64 {
                return Err("Unexpected EOF while seeking end".to_string());
            }

            let instr = decode_instruction(cursor)?;
            match instr {
                Instruction::Block(_) | Instruction::Loop(_) | Instruction::If(_) => {
                    depth += 1;
                }
                Instruction::End => {
                    if depth == 0 {
                        ends_found += 1;
                        if ends_found >= n {
                            return Ok(());
                        }
                    } else {
                        depth -= 1;
                    }
                }
                _ => {}
            }
        }
    }

    /// Execute a branch to the given label depth
    fn do_branch(&mut self, label: u32, cursor: &mut Cursor<&[u8]>) -> Result<(), String> {
        let label_idx = label as usize;
        if label_idx >= self.context.block_stack.len() {
            let depth = self.context.block_stack.len();
            let call_stack: Vec<u32> = self.context.call_stack.iter().map(|f| f.func_idx).collect();
            return Err(format!(
                "br: invalid label {label} (block_stack depth={depth}, call_stack={call_stack:?})"
            ));
        }

        let block_idx = self.context.block_stack.len() - 1 - label_idx;
        let target_block = &self.context.block_stack[block_idx];

        // Arity: number of values to preserve on the stack.
        // For loops: 0 (we're restarting, no result passed through br)
        // For blocks/if: 0 if void, 1 if value type
        let arity: usize = if target_block.is_loop {
            0
        } else if target_block.block_type.is_some() {
            1
        } else {
            0
        };
        let is_loop = target_block.is_loop;

        // Restore operand stack: keep only the top `arity` values, truncate to target stack_depth
        let target_depth = target_block.stack_depth;
        let result_values: Vec<Value> =
            if arity > 0 && self.context.operand_stack.len() > target_depth {
                let cur_len = self.context.operand_stack.len();
                self.context
                    .operand_stack
                    .drain(cur_len - arity..)
                    .collect()
            } else {
                Vec::new()
            };
        if self.context.operand_stack.len() > target_depth {
            self.context.operand_stack.truncate(target_depth);
        }
        for v in result_values {
            self.context.operand_stack.push(v);
        }

        if is_loop {
            cursor.set_position(target_block.start_pos as u64);
            // Pop only the blocks above the loop (not the loop itself)
            for _ in 0..label_idx {
                self.context.pop_block()?;
            }
        } else {
            // Pop all blocks up to and including the target
            for _ in 0..=label_idx {
                self.context.pop_block()?;
            }
            // Skip past the remaining nested end instructions in bytecode
            self.skip_n_ends(cursor, label_idx + 1)?;
        }

        Ok(())
    }

    /// Call a function with arguments already on stack
    fn call_function(&mut self, func_idx: u32) -> Result<(), String> {
        if (func_idx as usize) < self.import_func_count {
            return self.call_host_function(func_idx);
        }

        let defined_idx = func_idx as usize - self.import_func_count;

        let (arg_count, num_results, code, local_types) = {
            let func = self.module.functions.get(defined_idx).ok_or_else(|| {
                format!("Function index {func_idx} out of bounds (defined index {defined_idx})")
            })?;

            let func_type = self
                .module
                .types
                .get(func.type_index as usize)
                .ok_or_else(|| format!("Function type index {} out of bounds", func.type_index))?;

            (
                func_type.params.len(),
                func_type.results.len(),
                func.code.clone(),
                func.locals.clone(),
            )
        };

        // Pop arguments from operand stack
        let args = self.context.pop_n(arg_count)?;
        // Record stack depth AFTER popping args — this is the frame's baseline.
        // `return` uses this to restore the operand stack before leaving.
        let base_stack_depth = self.context.operand_stack.len();

        // Initialize locals: parameters + local variables
        let mut locals = args;

        // Add local variable slots
        for (count, value_type) in local_types {
            for _ in 0..count {
                let default_value = match value_type {
                    ValueType::I32 => Value::I32(0),
                    ValueType::I64 => Value::I64(0),
                    ValueType::F32 => Value::F32(0.0),
                    ValueType::F64 => Value::F64(0.0),
                    _ => return Err(format!("Unsupported value type in locals: {value_type:?}")),
                };
                locals.push(default_value);
            }
        }

        // Create call frame and push it
        let mut frame = Frame::new(func_idx, locals, num_results);
        frame.base_stack_depth = base_stack_depth;
        self.context.push_frame(frame);

        // Snapshot block stack depth so we can restore it on return.
        // A `return` inside a block breaks out of execute_bytecode without
        // popping the intra-function blocks, which would corrupt the caller's
        // block stack.
        let block_depth_before = self.context.block_stack.len();
        // WASM spec: every function body is implicitly wrapped in a block.
        // Push it so the function-terminating 0x0b End byte pops this frame
        // rather than accidentally popping the caller's block frames.
        self.context.push_block(None, false, 0, 0, false);

        // Execute function bytecode
        let mut cursor = Cursor::new(code.as_slice());
        let result = self.execute_bytecode(&mut cursor);

        // Restore block stack to the depth it had before this call.
        self.context.block_stack.truncate(block_depth_before);

        result?;

        // Ensure the operand stack is exactly base_stack_depth + num_results.
        // Normally the function body leaves the right values, but after a `return`
        // or branch cleanup we enforce correctness here.
        let cur = self.context.operand_stack.len();
        let expected = base_stack_depth + num_results;
        if cur > expected {
            let results: Vec<Value> = if num_results > 0 {
                let start = cur.saturating_sub(num_results);
                self.context.operand_stack.drain(start..).collect()
            } else {
                Vec::new()
            };
            self.context.operand_stack.truncate(base_stack_depth);
            for v in results {
                self.context.operand_stack.push(v);
            }
        }

        // Pop frame
        self.context.pop_frame()?;

        Ok(())
    }

    /// Call a function indirectly via table lookup
    fn call_function_indirect(&mut self, table_idx: u32, type_idx: u32) -> Result<(), String> {
        let abs_func_idx = self
            .table
            .get(table_idx as usize)
            .and_then(|&v| v)
            .ok_or_else(|| format!("Table index {table_idx} is null or out of bounds"))?;

        // Resolve defined function index for type checking
        if (abs_func_idx as usize) < self.import_func_count {
            // Imported function via indirect call – look up type from import
            let import = &self.module.imports[abs_func_idx as usize];
            if let ImportKind::Function(import_type_idx) = &import.kind {
                let func_type = self
                    .module
                    .types
                    .get(*import_type_idx as usize)
                    .ok_or_else(|| format!("Import type index {import_type_idx} out of bounds"))?;
                let expected_type = self
                    .module
                    .types
                    .get(type_idx as usize)
                    .ok_or_else(|| format!("Expected type index {type_idx} out of bounds"))?;
                if func_type.params != expected_type.params
                    || func_type.results != expected_type.results
                {
                    return Err("Function signature mismatch in call_indirect".into());
                }
            }
        } else {
            let defined_idx = abs_func_idx as usize - self.import_func_count;
            let func = self
                .module
                .functions
                .get(defined_idx)
                .ok_or_else(|| format!("Function index {abs_func_idx} out of bounds"))?;
            let func_type = self
                .module
                .types
                .get(func.type_index as usize)
                .ok_or_else(|| format!("Function type index {} out of bounds", func.type_index))?;
            let expected_type = self
                .module
                .types
                .get(type_idx as usize)
                .ok_or_else(|| format!("Expected type index {type_idx} out of bounds"))?;
            if func_type.params != expected_type.params
                || func_type.results != expected_type.results
            {
                return Err("Function signature mismatch in call_indirect".into());
            }
        }

        self.call_function(abs_func_idx)?;
        Ok(())
    }

    /// Dispatch an imported function call through the linker.
    /// Arguments are already on the operand stack.
    fn call_host_function(&mut self, func_idx: u32) -> Result<(), String> {
        let idx = func_idx as usize;
        let import = self
            .module
            .imports
            .get(idx)
            .ok_or_else(|| format!("Import index {idx} out of bounds"))?;

        let type_idx = match &import.kind {
            ImportKind::Function(ti) => *ti,
            _ => return Err(format!("Import {idx} is not a function")),
        };

        let (param_count, result_count) = {
            let ft = self
                .module
                .types
                .get(type_idx as usize)
                .ok_or_else(|| format!("Type index {type_idx} out of bounds"))?;
            (ft.params.len(), ft.results.len())
        };

        let module_name = self.module.imports[idx].module.clone();
        let func_name = self.module.imports[idx].name.clone();

        let args = self.context.pop_n(param_count)?;

        let linker = self
            .linker
            .as_ref()
            .ok_or_else(|| format!("No linker: cannot call import {module_name}::{func_name}"))?;
        let host_fn = linker
            .get_import(&module_name, &func_name)
            .ok_or_else(|| format!("Unresolved import: {module_name}::{func_name}"))?;

        let results = host_fn.call(args, &mut self.context.memory)?;

        if results.len() != result_count {
            return Err(format!(
                "Host function {module_name}::{func_name} returned {} values, expected {result_count}",
                results.len()
            ));
        }
        for v in results {
            self.context.push(v);
        }
        Ok(())
    }

    /// Dispatch an imported function call with explicit arguments (for execute_with_args).
    fn call_host_function_with_args(
        &mut self,
        func_idx: u32,
        args: Vec<Value>,
    ) -> Result<Vec<Value>, String> {
        let idx = func_idx as usize;
        let import = self
            .module
            .imports
            .get(idx)
            .ok_or_else(|| format!("Import index {idx} out of bounds"))?;

        let module_name = import.module.clone();
        let func_name = import.name.clone();

        let linker = self
            .linker
            .as_ref()
            .ok_or_else(|| format!("No linker: cannot call import {module_name}::{func_name}"))?;
        let host_fn = linker
            .get_import(&module_name, &func_name)
            .ok_or_else(|| format!("Unresolved import: {module_name}::{func_name}"))?;

        host_fn.call(args, &mut self.context.memory)
    }

    /// Dispatch instruction to handler
    fn dispatch_instruction(
        &mut self,
        instr: Instruction,
        cursor: &mut Cursor<&[u8]>,
    ) -> Result<ControlFlow, String> {
        match instr {
            // Constants
            Instruction::I32Const(v) => self.context.push(Value::I32(v)),
            Instruction::I64Const(v) => self.context.push(Value::I64(v)),
            Instruction::F32Const(v) => self.context.push(Value::F32(v)),
            Instruction::F64Const(v) => self.context.push(Value::F64(v)),

            // i32 unary operations
            Instruction::I32Eqz => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I32(if x == 0 { 1 } else { 0 })),
                    _ => return Err("Type mismatch for i32.eqz".to_string()),
                }
            }
            Instruction::I32Clz => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I32(x.leading_zeros() as i32)),
                    _ => return Err("Type mismatch for i32.clz".to_string()),
                }
            }
            Instruction::I32Ctz => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I32(x.trailing_zeros() as i32)),
                    _ => return Err("Type mismatch for i32.ctz".to_string()),
                }
            }
            Instruction::I32Popcnt => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I32(x.count_ones() as i32)),
                    _ => return Err("Type mismatch for i32.popcnt".to_string()),
                }
            }

            // i64 unary operations
            Instruction::I64Eqz => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::I32(if x == 0 { 1 } else { 0 })),
                    _ => return Err("Type mismatch for i64.eqz".to_string()),
                }
            }
            Instruction::I64Clz => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::I64(x.leading_zeros() as i64)),
                    _ => return Err("Type mismatch for i64.clz".to_string()),
                }
            }
            Instruction::I64Ctz => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::I64(x.trailing_zeros() as i64)),
                    _ => return Err("Type mismatch for i64.ctz".to_string()),
                }
            }
            Instruction::I64Popcnt => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::I64(x.count_ones() as i64)),
                    _ => return Err("Type mismatch for i64.popcnt".to_string()),
                }
            }

            // i32 arithmetic
            Instruction::I32Add => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(x.wrapping_add(y)))
                    }
                    _ => return Err("Type mismatch for i32.add".to_string()),
                }
            }
            Instruction::I32Sub => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(x.wrapping_sub(y)))
                    }
                    _ => return Err("Type mismatch for i32.sub".to_string()),
                }
            }
            Instruction::I32Mul => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(x.wrapping_mul(y)))
                    }
                    _ => return Err("Type mismatch for i32.mul".to_string()),
                }
            }
            Instruction::I32DivS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        if x == i32::MIN && y == -1 {
                            return Err("Integer overflow in division".to_string());
                        }
                        self.context.push(Value::I32(x / y));
                    }
                    _ => return Err("Type mismatch for i32.div_s".to_string()),
                }
            }
            Instruction::I32DivU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context
                            .push(Value::I32(((x as u32) / (y as u32)) as i32));
                    }
                    _ => return Err("Type mismatch for i32.div_u".to_string()),
                }
            }
            Instruction::I32RemS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context.push(Value::I32(x % y));
                    }
                    _ => return Err("Type mismatch for i32.rem_s".to_string()),
                }
            }
            Instruction::I32RemU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context
                            .push(Value::I32(((x as u32) % (y as u32)) as i32));
                    }
                    _ => return Err("Type mismatch for i32.rem_u".to_string()),
                }
            }

            // i32 bitwise
            Instruction::I32And => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => self.context.push(Value::I32(x & y)),
                    _ => return Err("Type mismatch for i32.and".to_string()),
                }
            }
            Instruction::I32Or => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => self.context.push(Value::I32(x | y)),
                    _ => return Err("Type mismatch for i32.or".to_string()),
                }
            }
            Instruction::I32Xor => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => self.context.push(Value::I32(x ^ y)),
                    _ => return Err("Type mismatch for i32.xor".to_string()),
                }
            }
            Instruction::I32Shl => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(x.wrapping_shl(y as u32 & 31)));
                    }
                    _ => return Err("Type mismatch for i32.shl".to_string()),
                }
            }
            Instruction::I32ShrS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(x >> (y as u32 & 31)));
                    }
                    _ => return Err("Type mismatch for i32.shr_s".to_string()),
                }
            }
            Instruction::I32ShrU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32(((x as u32) >> (y as u32 & 31)) as i32));
                    }
                    _ => return Err("Type mismatch for i32.shr_u".to_string()),
                }
            }
            Instruction::I32Rotl => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32((x as u32).rotate_left(y as u32) as i32));
                    }
                    _ => return Err("Type mismatch for i32.rotl".to_string()),
                }
            }
            Instruction::I32Rotr => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32((x as u32).rotate_right(y as u32) as i32));
                    }
                    _ => return Err("Type mismatch for i32.rotr".to_string()),
                }
            }

            // i32 comparison
            Instruction::I32Eq => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x == y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.eq".to_string()),
                }
            }
            Instruction::I32Ne => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x != y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.ne".to_string()),
                }
            }
            Instruction::I32LtS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x < y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.lt_s".to_string()),
                }
            }
            Instruction::I32LtU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32(if (x as u32) < (y as u32) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.lt_u".to_string()),
                }
            }
            Instruction::I32GtS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x > y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.gt_s".to_string()),
                }
            }
            Instruction::I32GtU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32(if (x as u32) > (y as u32) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.gt_u".to_string()),
                }
            }
            Instruction::I32LeS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x <= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.le_s".to_string()),
                }
            }
            Instruction::I32LeU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32(if (x as u32) <= (y as u32) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.le_u".to_string()),
                }
            }
            Instruction::I32GeS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context.push(Value::I32(if x >= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.ge_s".to_string()),
                }
            }
            Instruction::I32GeU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I32(x), Value::I32(y)) => {
                        self.context
                            .push(Value::I32(if (x as u32) >= (y as u32) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i32.ge_u".to_string()),
                }
            }

            // Local operations
            Instruction::LocalGet(idx) => {
                let frame = self.context.current_frame()?;
                let value = frame.get_local(idx as usize)?;
                self.context.push(value);
            }
            Instruction::LocalSet(idx) => {
                let value = self.context.pop()?;
                let frame = self.context.current_frame_mut()?;
                frame.set_local(idx as usize, value)?;
            }
            Instruction::LocalTee(idx) => {
                let value = self.context.peek()?;
                let frame = self.context.current_frame_mut()?;
                frame.set_local(idx as usize, value)?;
            }

            // i64 arithmetic
            Instruction::I64Add => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I64(x.wrapping_add(y)))
                    }
                    _ => return Err("Type mismatch for i64.add".to_string()),
                }
            }
            Instruction::I64Sub => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I64(x.wrapping_sub(y)))
                    }
                    _ => return Err("Type mismatch for i64.sub".to_string()),
                }
            }
            Instruction::I64Mul => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I64(x.wrapping_mul(y)))
                    }
                    _ => return Err("Type mismatch for i64.mul".to_string()),
                }
            }
            Instruction::I64DivS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        if x == i64::MIN && y == -1 {
                            return Err("Integer overflow in division".to_string());
                        }
                        self.context.push(Value::I64(x / y));
                    }
                    _ => return Err("Type mismatch for i64.div_s".to_string()),
                }
            }
            Instruction::I64DivU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context
                            .push(Value::I64(((x as u64) / (y as u64)) as i64));
                    }
                    _ => return Err("Type mismatch for i64.div_u".to_string()),
                }
            }
            Instruction::I64RemS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context.push(Value::I64(x % y));
                    }
                    _ => return Err("Type mismatch for i64.rem_s".to_string()),
                }
            }
            Instruction::I64RemU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        if y == 0 {
                            return Err("Integer division by zero".to_string());
                        }
                        self.context
                            .push(Value::I64(((x as u64) % (y as u64)) as i64));
                    }
                    _ => return Err("Type mismatch for i64.rem_u".to_string()),
                }
            }

            // i64 bitwise
            Instruction::I64And => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => self.context.push(Value::I64(x & y)),
                    _ => return Err("Type mismatch for i64.and".to_string()),
                }
            }
            Instruction::I64Or => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => self.context.push(Value::I64(x | y)),
                    _ => return Err("Type mismatch for i64.or".to_string()),
                }
            }
            Instruction::I64Xor => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => self.context.push(Value::I64(x ^ y)),
                    _ => return Err("Type mismatch for i64.xor".to_string()),
                }
            }
            Instruction::I64Shl => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I64(x.wrapping_shl(y as u32 & 63)));
                    }
                    _ => return Err("Type mismatch for i64.shl".to_string()),
                }
            }
            Instruction::I64ShrS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I64(x >> (y as u32 & 63)));
                    }
                    _ => return Err("Type mismatch for i64.shr_s".to_string()),
                }
            }
            Instruction::I64ShrU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context
                            .push(Value::I64(((x as u64) >> (y as u32 & 63)) as i64));
                    }
                    _ => return Err("Type mismatch for i64.shr_u".to_string()),
                }
            }
            Instruction::I64Rotl => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        let shift = (y as u32) & 63;
                        self.context.push(Value::I64(x.rotate_left(shift)));
                    }
                    _ => return Err("Type mismatch for i64.rotl".to_string()),
                }
            }
            Instruction::I64Rotr => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        let shift = (y as u32) & 63;
                        self.context.push(Value::I64(x.rotate_right(shift)));
                    }
                    _ => return Err("Type mismatch for i64.rotr".to_string()),
                }
            }

            // i64 comparison
            Instruction::I64Eq => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x == y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.eq".to_string()),
                }
            }
            Instruction::I64Ne => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x != y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.ne".to_string()),
                }
            }
            Instruction::I64LtS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x < y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.lt_s".to_string()),
                }
            }
            Instruction::I64LtU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context
                            .push(Value::I32(if (x as u64) < (y as u64) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.lt_u".to_string()),
                }
            }
            Instruction::I64GtS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x > y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.gt_s".to_string()),
                }
            }
            Instruction::I64GtU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context
                            .push(Value::I32(if (x as u64) > (y as u64) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.gt_u".to_string()),
                }
            }
            Instruction::I64LeS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x <= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.le_s".to_string()),
                }
            }
            Instruction::I64LeU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context
                            .push(Value::I32(if (x as u64) <= (y as u64) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.le_u".to_string()),
                }
            }
            Instruction::I64GeS => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context.push(Value::I32(if x >= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.ge_s".to_string()),
                }
            }
            Instruction::I64GeU => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::I64(x), Value::I64(y)) => {
                        self.context
                            .push(Value::I32(if (x as u64) >= (y as u64) { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for i64.ge_u".to_string()),
                }
            }

            // f32 arithmetic
            Instruction::F32Add => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x + y)),
                    _ => return Err("Type mismatch for f32.add".to_string()),
                }
            }
            Instruction::F32Sub => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x - y)),
                    _ => return Err("Type mismatch for f32.sub".to_string()),
                }
            }
            Instruction::F32Mul => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x * y)),
                    _ => return Err("Type mismatch for f32.mul".to_string()),
                }
            }
            Instruction::F32Div => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x / y)),
                    _ => return Err("Type mismatch for f32.div".to_string()),
                }
            }
            Instruction::F32Sqrt => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.sqrt())),
                    _ => return Err("Type mismatch for f32.sqrt".to_string()),
                }
            }
            Instruction::F32Min => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x.min(y))),
                    _ => return Err("Type mismatch for f32.min".to_string()),
                }
            }
            Instruction::F32Max => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x.max(y))),
                    _ => return Err("Type mismatch for f32.max".to_string()),
                }
            }
            Instruction::F32Ceil => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.ceil())),
                    _ => return Err("Type mismatch for f32.ceil".to_string()),
                }
            }
            Instruction::F32Floor => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.floor())),
                    _ => return Err("Type mismatch for f32.floor".to_string()),
                }
            }
            Instruction::F32Trunc => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.trunc())),
                    _ => return Err("Type mismatch for f32.trunc".to_string()),
                }
            }
            Instruction::F32Nearest => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.round())),
                    _ => return Err("Type mismatch for f32.nearest".to_string()),
                }
            }
            Instruction::F32Abs => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(x.abs())),
                    _ => return Err("Type mismatch for f32.abs".to_string()),
                }
            }
            Instruction::F32Neg => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F32(-x)),
                    _ => return Err("Type mismatch for f32.neg".to_string()),
                }
            }
            Instruction::F32Copysign => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => self.context.push(Value::F32(x.copysign(y))),
                    _ => return Err("Type mismatch for f32.copysign".to_string()),
                }
            }

            // f32 comparison
            Instruction::F32Eq => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x == y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.eq".to_string()),
                }
            }
            Instruction::F32Ne => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x != y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.ne".to_string()),
                }
            }
            Instruction::F32Lt => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x < y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.lt".to_string()),
                }
            }
            Instruction::F32Gt => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x > y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.gt".to_string()),
                }
            }
            Instruction::F32Le => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x <= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.le".to_string()),
                }
            }
            Instruction::F32Ge => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F32(x), Value::F32(y)) => {
                        self.context.push(Value::I32(if x >= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f32.ge".to_string()),
                }
            }

            // f64 arithmetic
            Instruction::F64Add => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x + y)),
                    _ => return Err("Type mismatch for f64.add".to_string()),
                }
            }
            Instruction::F64Sub => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x - y)),
                    _ => return Err("Type mismatch for f64.sub".to_string()),
                }
            }
            Instruction::F64Mul => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x * y)),
                    _ => return Err("Type mismatch for f64.mul".to_string()),
                }
            }
            Instruction::F64Div => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x / y)),
                    _ => return Err("Type mismatch for f64.div".to_string()),
                }
            }
            Instruction::F64Sqrt => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.sqrt())),
                    _ => return Err("Type mismatch for f64.sqrt".to_string()),
                }
            }
            Instruction::F64Min => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x.min(y))),
                    _ => return Err("Type mismatch for f64.min".to_string()),
                }
            }
            Instruction::F64Max => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x.max(y))),
                    _ => return Err("Type mismatch for f64.max".to_string()),
                }
            }
            Instruction::F64Ceil => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.ceil())),
                    _ => return Err("Type mismatch for f64.ceil".to_string()),
                }
            }
            Instruction::F64Floor => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.floor())),
                    _ => return Err("Type mismatch for f64.floor".to_string()),
                }
            }
            Instruction::F64Trunc => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.trunc())),
                    _ => return Err("Type mismatch for f64.trunc".to_string()),
                }
            }
            Instruction::F64Nearest => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.round())),
                    _ => return Err("Type mismatch for f64.nearest".to_string()),
                }
            }
            Instruction::F64Abs => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(x.abs())),
                    _ => return Err("Type mismatch for f64.abs".to_string()),
                }
            }
            Instruction::F64Neg => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F64(-x)),
                    _ => return Err("Type mismatch for f64.neg".to_string()),
                }
            }
            Instruction::F64Copysign => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => self.context.push(Value::F64(x.copysign(y))),
                    _ => return Err("Type mismatch for f64.copysign".to_string()),
                }
            }

            // f64 comparison
            Instruction::F64Eq => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x == y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.eq".to_string()),
                }
            }
            Instruction::F64Ne => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x != y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.ne".to_string()),
                }
            }
            Instruction::F64Lt => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x < y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.lt".to_string()),
                }
            }
            Instruction::F64Gt => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x > y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.gt".to_string()),
                }
            }
            Instruction::F64Le => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x <= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.le".to_string()),
                }
            }
            Instruction::F64Ge => {
                let b = self.context.pop()?;
                let a = self.context.pop()?;
                match (a, b) {
                    (Value::F64(x), Value::F64(y)) => {
                        self.context.push(Value::I32(if x >= y { 1 } else { 0 }));
                    }
                    _ => return Err("Type mismatch for f64.ge".to_string()),
                }
            }

            // Control flow - basic ones first
            Instruction::Nop => {}
            Instruction::Unreachable => return Err("Unreachable instruction executed".to_string()),
            Instruction::Return => {
                // Clean up the operand stack to exactly base_stack_depth + num_returns.
                // In a valid WASM module the compiler guarantees this, but explicit cleanup
                // prevents accumulated garbage from corrupted branch handling.
                if let Ok(frame) = self.context.current_frame() {
                    let num_returns = frame.num_returns;
                    let base = frame.base_stack_depth;
                    let cur = self.context.operand_stack.len();
                    let expected = base + num_returns;
                    if cur > expected {
                        // Extra values: save the top num_returns, truncate, push back
                        let results: Vec<Value> = if num_returns > 0 {
                            let start = cur.saturating_sub(num_returns);
                            self.context.operand_stack.drain(start..).collect()
                        } else {
                            Vec::new()
                        };
                        self.context.operand_stack.truncate(base);
                        for v in results {
                            self.context.operand_stack.push(v);
                        }
                    }
                }
                return Ok(ControlFlow::Return);
            }
            Instruction::End => {
                self.context.pop_block().ok();
            }
            Instruction::Drop => {
                self.context.pop()?;
            }

            // Call instruction - implement function invocation
            Instruction::Call(func_idx) => {
                self.call_function(func_idx)?;
            }

            // CallIndirect - call function through table
            Instruction::CallIndirect(type_idx) => {
                let func_idx = self.context.pop()?;
                if let Value::I32(idx) = func_idx {
                    self.call_function_indirect(idx as u32, type_idx)?;
                } else {
                    return Err("CallIndirect requires i32 function index on stack".to_string());
                }
            }

            // Global operations
            Instruction::GlobalGet(idx) => {
                let val = self
                    .context
                    .globals
                    .get(idx as usize)
                    .copied()
                    .ok_or_else(|| format!("Global index {idx} out of bounds"))?;
                self.context.push(val);
            }
            Instruction::GlobalSet(idx) => {
                let val = self.context.pop()?;
                let global = self
                    .context
                    .globals
                    .get_mut(idx as usize)
                    .ok_or_else(|| format!("Global index {idx} out of bounds"))?;
                *global = val;
            }

            // Memory load operations — effective address = stack_val + offset
            Instruction::I32Load(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i32(addr)?;
                self.context.push(Value::I32(val));
            }
            Instruction::I64Load(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i64(addr)?;
                self.context.push(Value::I64(val));
            }
            Instruction::F32Load(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_f32(addr)?;
                self.context.push(Value::F32(val));
            }
            Instruction::F64Load(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_f64(addr)?;
                self.context.push(Value::F64(val));
            }
            Instruction::I32Load8S(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i8(addr)? as i32;
                self.context.push(Value::I32(val));
            }
            Instruction::I32Load8U(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = (self.context.memory.read_u8(addr)? as u32) as i32;
                self.context.push(Value::I32(val));
            }
            Instruction::I32Load16S(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i16(addr)? as i32;
                self.context.push(Value::I32(val));
            }
            Instruction::I32Load16U(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = (self.context.memory.read_u16(addr)? as u32) as i32;
                self.context.push(Value::I32(val));
            }
            Instruction::I64Load8S(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i8(addr)? as i64;
                self.context.push(Value::I64(val));
            }
            Instruction::I64Load8U(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_u8(addr)? as i64;
                self.context.push(Value::I64(val));
            }
            Instruction::I64Load16S(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i16(addr)? as i64;
                self.context.push(Value::I64(val));
            }
            Instruction::I64Load16U(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_u16(addr)? as i64;
                self.context.push(Value::I64(val));
            }
            Instruction::I64Load32S(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = self.context.memory.read_i32(addr)? as i64;
                self.context.push(Value::I64(val));
            }
            Instruction::I64Load32U(offset) => {
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                let val = (self.context.memory.read_i32(addr)? as u32) as i64;
                self.context.push(Value::I64(val));
            }

            // Memory store operations — effective address = stack_val + offset
            Instruction::I32Store(offset) => {
                let val = match self.context.pop()? {
                    Value::I32(v) => v,
                    _ => return Err("Value must be i32".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_i32(addr, val)?;
            }
            Instruction::I64Store(offset) => {
                let val = match self.context.pop()? {
                    Value::I64(v) => v,
                    _ => return Err("Value must be i64".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_i64(addr, val)?;
            }
            Instruction::F32Store(offset) => {
                let val = match self.context.pop()? {
                    Value::F32(v) => v,
                    _ => return Err("Value must be f32".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_f32(addr, val)?;
            }
            Instruction::F64Store(offset) => {
                let val = match self.context.pop()? {
                    Value::F64(v) => v,
                    _ => return Err("Value must be f64".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_f64(addr, val)?;
            }
            Instruction::I32Store8(offset) => {
                let val = match self.context.pop()? {
                    Value::I32(v) => v as u8,
                    _ => return Err("Value must be i32".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_u8(addr, val)?;
            }
            Instruction::I32Store16(offset) => {
                let val = match self.context.pop()? {
                    Value::I32(v) => v as u16,
                    _ => return Err("Value must be i32".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_u16(addr, val)?;
            }
            Instruction::I64Store8(offset) => {
                let val = match self.context.pop()? {
                    Value::I64(v) => v as u8,
                    _ => return Err("Value must be i64".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_u8(addr, val)?;
            }
            Instruction::I64Store16(offset) => {
                let val = match self.context.pop()? {
                    Value::I64(v) => v as u16,
                    _ => return Err("Value must be i64".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_u16(addr, val)?;
            }
            Instruction::I64Store32(offset) => {
                let val = match self.context.pop()? {
                    Value::I64(v) => v as u32 as i32,
                    _ => return Err("Value must be i64".to_string()),
                };
                let addr = match self.context.pop()? {
                    Value::I32(a) => (a as u32).wrapping_add(offset) as usize,
                    _ => return Err("Address must be i32".to_string()),
                };
                self.context.memory.write_i32(addr, val)?;
            }

            // Memory size
            Instruction::MemorySize => {
                let pages = self.context.memory.pages() as i32;
                self.context.push(Value::I32(pages));
            }

            // Memory grow
            Instruction::MemoryGrow => {
                let delta = match self.context.pop()? {
                    Value::I32(n) => n as u32,
                    _ => return Err("Memory grow delta must be i32".to_string()),
                };
                let old_pages = self.context.memory.pages();
                match self.context.memory.grow(delta) {
                    Ok(_) => {
                        self.context.push(Value::I32(old_pages as i32));
                    }
                    Err(_) => {
                        self.context.push(Value::I32(-1));
                    }
                }
            }

            // Bulk-memory: memory.fill — memset equivalent
            // Stack: [dest: i32, val: i32, len: i32]
            Instruction::MemoryFill => {
                let len = match self.context.pop()? {
                    Value::I32(n) => n as usize,
                    _ => return Err("memory.fill len must be i32".to_string()),
                };
                let val = match self.context.pop()? {
                    Value::I32(v) => (v & 0xFF) as u8,
                    _ => return Err("memory.fill val must be i32".to_string()),
                };
                let dest = match self.context.pop()? {
                    Value::I32(a) => a as u32 as usize,
                    _ => return Err("memory.fill dest must be i32".to_string()),
                };
                for i in 0..len {
                    self.context.memory.write_u8(dest + i, val)?;
                }
            }

            // Bulk-memory: memory.copy — memmove equivalent
            // Stack: [dst: i32, src: i32, len: i32]
            Instruction::MemoryCopy => {
                let len = match self.context.pop()? {
                    Value::I32(n) => n as usize,
                    _ => return Err("memory.copy len must be i32".to_string()),
                };
                let src = match self.context.pop()? {
                    Value::I32(a) => a as u32 as usize,
                    _ => return Err("memory.copy src must be i32".to_string()),
                };
                let dst = match self.context.pop()? {
                    Value::I32(a) => a as u32 as usize,
                    _ => return Err("memory.copy dst must be i32".to_string()),
                };
                let bytes = self.context.memory.read_bytes(src, len)?;
                self.context.memory.write_bytes(dst, &bytes)?;
            }

            // Bulk-memory: memory.init — copy data segment into memory
            // Stack: [dst: i32, src_offset: i32, len: i32]
            Instruction::MemoryInit(seg_idx) => {
                let len = match self.context.pop()? {
                    Value::I32(n) => n as usize,
                    _ => return Err("memory.init len must be i32".to_string()),
                };
                let src_off = match self.context.pop()? {
                    Value::I32(a) => a as usize,
                    _ => return Err("memory.init src_offset must be i32".to_string()),
                };
                let dst = match self.context.pop()? {
                    Value::I32(a) => a as u32 as usize,
                    _ => return Err("memory.init dst must be i32".to_string()),
                };
                let seg =
                    self.module.data.get(seg_idx as usize).ok_or_else(|| {
                        format!("memory.init: data segment {seg_idx} out of bounds")
                    })?;
                let src_end = src_off + len;
                if src_end > seg.data.len() {
                    return Err(format!(
                        "memory.init: src range {src_off}..{src_end} out of segment bounds ({})",
                        seg.data.len()
                    ));
                }
                let bytes = seg.data[src_off..src_end].to_vec();
                self.context.memory.write_bytes(dst, &bytes)?;
            }

            // Bulk-memory: data.drop — discard a data segment (no-op for us)
            Instruction::DataDrop(_seg_idx) => {}

            // Control flow - proper implementation
            Instruction::Block(block_type) => {
                let pos = cursor.position() as usize;
                self.context.push_block(block_type, false, pos, 0, false);
            }
            Instruction::Loop(block_type) => {
                let pos = cursor.position() as usize;
                self.context.push_block(block_type, true, pos, 0, false);
            }
            Instruction::If(block_type) => {
                // Pop condition from stack
                let cond = self.context.pop()?;
                let cond_value = match cond {
                    Value::I32(v) => v,
                    _ => return Err("if requires i32 condition".to_string()),
                };

                if cond_value != 0 {
                    // Condition is true — push frame, execute then-branch.
                    // If there's no else, the End instruction will pop this frame.
                    // If there IS an else, the Else handler will skip to end and pop this frame.
                    self.context.push_block(block_type, false, 0, 0, true);
                } else {
                    // Condition is false — scan forward to find else or end.
                    let found_else = self.skip_to_else_or_end(cursor)?;
                    if found_else {
                        // Cursor is now after `else`; push frame for the else-body.
                        // The End at the close of this if will pop this frame.
                        self.context.push_block(block_type, false, 0, 0, false);
                    }
                    // If found_else is false, `end` was already consumed — don't push a frame.
                }
            }
            Instruction::Else => {
                // We just finished the then-branch. Skip to the matching `end`
                // (which would otherwise be processed by the End handler, but we
                // consume it here so we must also pop the block frame ourselves).
                self.skip_to_end(cursor)?;
                self.context.pop_block()?;
            }
            Instruction::Br(label) => {
                self.do_branch(label, cursor)?;
            }
            Instruction::BrIf(label) => {
                let cond = self.context.pop()?;
                let cond_value = match cond {
                    Value::I32(v) => v,
                    _ => return Err("br_if requires i32 condition".to_string()),
                };

                if cond_value != 0 {
                    self.do_branch(label, cursor)?;
                }
            }
            Instruction::BrTable(targets, default) => {
                let index = match self.context.pop()? {
                    Value::I32(v) => v as u32,
                    _ => return Err("br_table index must be i32".to_string()),
                };

                let label = if (index as usize) < targets.len() {
                    targets[index as usize]
                } else {
                    default
                };

                self.do_branch(label, cursor)?;
            }

            // Type conversions
            Instruction::I32WrapI64 => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::I32(x as i32)),
                    _ => return Err("Type mismatch for i32.wrap_i64".to_string()),
                }
            }
            Instruction::I32TruncF32S => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (i32::MAX as f32 + 1.0) || x < (i32::MIN as f32) {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I32(x as i32));
                    }
                    _ => return Err("Type mismatch for i32.trunc_f32_s".to_string()),
                }
            }
            Instruction::I32TruncF32U => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (u32::MAX as f32 + 1.0) || x < 0.0 {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I32(x as u32 as i32));
                    }
                    _ => return Err("Type mismatch for i32.trunc_f32_u".to_string()),
                }
            }
            Instruction::I32TruncF64S => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (i32::MAX as f64 + 1.0) || x < (i32::MIN as f64) {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I32(x as i32));
                    }
                    _ => return Err("Type mismatch for i32.trunc_f64_s".to_string()),
                }
            }
            Instruction::I32TruncF64U => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (u32::MAX as f64 + 1.0) || x < 0.0 {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I32(x as u32 as i32));
                    }
                    _ => return Err("Type mismatch for i32.trunc_f64_u".to_string()),
                }
            }
            Instruction::I64ExtendI32S => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I64(x as i64)),
                    _ => return Err("Type mismatch for i64.extend_i32_s".to_string()),
                }
            }
            Instruction::I64ExtendI32U => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::I64(x as u32 as i64)),
                    _ => return Err("Type mismatch for i64.extend_i32_u".to_string()),
                }
            }
            Instruction::I64TruncF32S => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (i64::MAX as f32) || x < (i64::MIN as f32) {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I64(x as i64));
                    }
                    _ => return Err("Type mismatch for i64.trunc_f32_s".to_string()),
                }
            }
            Instruction::I64TruncF32U => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (u64::MAX as f32) || x < 0.0 {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I64(x as u64 as i64));
                    }
                    _ => return Err("Type mismatch for i64.trunc_f32_u".to_string()),
                }
            }
            Instruction::I64TruncF64S => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (i64::MAX as f64) || x < (i64::MIN as f64) {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I64(x as i64));
                    }
                    _ => return Err("Type mismatch for i64.trunc_f64_s".to_string()),
                }
            }
            Instruction::I64TruncF64U => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => {
                        if x.is_nan() {
                            return Err("Invalid conversion to integer: NaN".to_string());
                        }
                        if x >= (u64::MAX as f64) || x < 0.0 {
                            return Err("Integer overflow in truncation".to_string());
                        }
                        self.context.push(Value::I64(x as u64 as i64));
                    }
                    _ => return Err("Type mismatch for i64.trunc_f64_u".to_string()),
                }
            }
            Instruction::F32ConvertI32S => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::F32(x as f32)),
                    _ => return Err("Type mismatch for f32.convert_i32_s".to_string()),
                }
            }
            Instruction::F32ConvertI32U => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::F32(x as u32 as f32)),
                    _ => return Err("Type mismatch for f32.convert_i32_u".to_string()),
                }
            }
            Instruction::F32ConvertI64S => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::F32(x as f32)),
                    _ => return Err("Type mismatch for f32.convert_i64_s".to_string()),
                }
            }
            Instruction::F32ConvertI64U => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::F32(x as u64 as f32)),
                    _ => return Err("Type mismatch for f32.convert_i64_u".to_string()),
                }
            }
            Instruction::F32DemoteF64 => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::F32(x as f32)),
                    _ => return Err("Type mismatch for f32.demote_f64".to_string()),
                }
            }
            Instruction::F64ConvertI32S => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::F64(x as f64)),
                    _ => return Err("Type mismatch for f64.convert_i32_s".to_string()),
                }
            }
            Instruction::F64ConvertI32U => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => self.context.push(Value::F64(x as u32 as f64)),
                    _ => return Err("Type mismatch for f64.convert_i32_u".to_string()),
                }
            }
            Instruction::F64ConvertI64S => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::F64(x as f64)),
                    _ => return Err("Type mismatch for f64.convert_i64_s".to_string()),
                }
            }
            Instruction::F64ConvertI64U => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => self.context.push(Value::F64(x as u64 as f64)),
                    _ => return Err("Type mismatch for f64.convert_i64_u".to_string()),
                }
            }
            Instruction::F64PromoteF32 => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::F64(x as f64)),
                    _ => return Err("Type mismatch for f64.promote_f32".to_string()),
                }
            }
            Instruction::I32Reinterpret => {
                let a = self.context.pop()?;
                match a {
                    Value::F32(x) => self.context.push(Value::I32(x.to_bits() as i32)),
                    _ => return Err("Type mismatch for i32.reinterpret_f32".to_string()),
                }
            }
            Instruction::I64Reinterpret => {
                let a = self.context.pop()?;
                match a {
                    Value::F64(x) => self.context.push(Value::I64(x.to_bits() as i64)),
                    _ => return Err("Type mismatch for i64.reinterpret_f64".to_string()),
                }
            }
            Instruction::F32Reinterpret => {
                let a = self.context.pop()?;
                match a {
                    Value::I32(x) => {
                        self.context.push(Value::F32(f32::from_bits(x as u32)));
                    }
                    _ => return Err("Type mismatch for f32.reinterpret_i32".to_string()),
                }
            }
            Instruction::F64Reinterpret => {
                let a = self.context.pop()?;
                match a {
                    Value::I64(x) => {
                        self.context.push(Value::F64(f64::from_bits(x as u64)));
                    }
                    _ => return Err("Type mismatch for f64.reinterpret_i64".to_string()),
                }
            }

            // Sign-extension operators
            Instruction::I32Extend8S => {
                let a = match self.context.pop()? {
                    Value::I32(v) => v as i8 as i32,
                    _ => return Err("i32.extend8_s: expected i32".to_string()),
                };
                self.context.push(Value::I32(a));
            }
            Instruction::I32Extend16S => {
                let a = match self.context.pop()? {
                    Value::I32(v) => v as i16 as i32,
                    _ => return Err("i32.extend16_s: expected i32".to_string()),
                };
                self.context.push(Value::I32(a));
            }
            Instruction::I64Extend8S => {
                let a = match self.context.pop()? {
                    Value::I64(v) => v as i8 as i64,
                    _ => return Err("i64.extend8_s: expected i64".to_string()),
                };
                self.context.push(Value::I64(a));
            }
            Instruction::I64Extend16S => {
                let a = match self.context.pop()? {
                    Value::I64(v) => v as i16 as i64,
                    _ => return Err("i64.extend16_s: expected i64".to_string()),
                };
                self.context.push(Value::I64(a));
            }
            Instruction::I64Extend32S => {
                let a = match self.context.pop()? {
                    Value::I64(v) => v as i32 as i64,
                    _ => return Err("i64.extend32_s: expected i64".to_string()),
                };
                self.context.push(Value::I64(a));
            }

            Instruction::Select => {
                let cond = self.context.pop()?;
                let val2 = self.context.pop()?;
                let val1 = self.context.pop()?;
                match cond {
                    Value::I32(c) => {
                        self.context.push(if c != 0 { val1 } else { val2 });
                    }
                    _ => return Err("Select condition must be i32".to_string()),
                }
            }
        }

        Ok(ControlFlow::Continue)
    }

    pub fn context(&self) -> &ExecutionContext {
        &self.context
    }

    pub fn context_mut(&mut self) -> &mut ExecutionContext {
        &mut self.context
    }

    pub fn module(&self) -> &Module {
        &self.module
    }

    pub fn module_mut(&mut self) -> &mut Module {
        &mut self.module
    }

    pub fn import_func_count(&self) -> usize {
        self.import_func_count
    }

    /// Check whether an error string represents a WASI proc_exit.
    pub fn is_proc_exit(err: &str) -> Option<i32> {
        err.strip_prefix(WASI_PROC_EXIT_PREFIX)
            .and_then(|code| code.parse().ok())
    }
}

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

    #[test]
    fn test_frame_local_access() {
        let locals = vec![
            Value::I32(42),
            Value::I64(1000),
            Value::F32(std::f32::consts::PI),
        ];
        let mut frame = Frame::new(0, locals, 1);

        assert_eq!(frame.get_local(0).unwrap(), Value::I32(42));
        assert_eq!(frame.get_local(1).unwrap(), Value::I64(1000));

        frame.set_local(0, Value::I32(99)).unwrap();
        assert_eq!(frame.get_local(0).unwrap(), Value::I32(99));
    }

    #[test]
    fn test_execution_context_operand_stack() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();

        ctx.push(Value::I32(42));
        ctx.push(Value::I64(100));
        ctx.push(Value::I32(99));

        assert_eq!(ctx.pop().unwrap(), Value::I32(99));
        assert_eq!(ctx.pop().unwrap(), Value::I64(100));
        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_execution_context_stack_underflow() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        let result = ctx.pop();
        assert!(result.is_err());
    }

    #[test]
    fn test_execution_context_pop_n() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();

        ctx.push(Value::I32(1));
        ctx.push(Value::I32(2));
        ctx.push(Value::I32(3));
        ctx.push(Value::I32(4));

        let values = ctx.pop_n(2).unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values[0], Value::I32(3));
        assert_eq!(values[1], Value::I32(4));

        assert_eq!(ctx.pop().unwrap(), Value::I32(2));
    }

    #[test]
    fn test_execution_context_call_stack() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();

        let frame1 = Frame::new(0, vec![Value::I32(42)], 1);
        let frame2 = Frame::new(1, vec![Value::I64(100), Value::I32(99)], 2);

        ctx.push_frame(frame1);
        ctx.push_frame(frame2);

        assert_eq!(ctx.current_frame().unwrap().func_idx, 1);

        let popped = ctx.pop_frame().unwrap();
        assert_eq!(popped.func_idx, 1);
        assert_eq!(ctx.current_frame().unwrap().func_idx, 0);
    }

    #[test]
    fn test_executor_creation() {
        let module = super::super::module::Module::new();
        let executor = Executor::new(module).unwrap();
        assert_eq!(executor.context().memory.size(), 1);
    }

    #[test]
    fn test_executor_memory_access() {
        let module = super::super::module::Module::new();
        let mut executor = Executor::new(module).unwrap();

        executor
            .context_mut()
            .memory
            .write_i32(0, 0xDEADBEEFu32 as i32)
            .unwrap();
        assert_eq!(
            executor.context().memory.read_i32(0).unwrap(),
            0xDEADBEEFu32 as i32
        );
    }

    #[test]
    fn test_instruction_i32_const() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_i32_add() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(10));
        ctx.push(Value::I32(32));

        // i32.add pops two values and pushes result
        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x.wrapping_add(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_i32_sub() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(52));
        ctx.push(Value::I32(10));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x.wrapping_sub(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_i32_mul() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(6));
        ctx.push(Value::I32(7));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x.wrapping_mul(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_i32_div_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(84));
        ctx.push(Value::I32(2));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                if y != 0 {
                    ctx.push(Value::I32(x / y));
                }
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_i32_eq() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        ctx.push(Value::I32(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(if x == y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_instruction_i32_ne() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        ctx.push(Value::I32(10));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(if x != y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_instruction_i32_lt_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(10));
        ctx.push(Value::I32(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(if x < y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_instruction_i32_gt_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        ctx.push(Value::I32(10));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(if x > y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_instruction_i32_and() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(0xFF00));
        ctx.push(Value::I32(0x00FF));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x & y)),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(0x0000));
    }

    #[test]
    fn test_instruction_i32_or() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(0xFF00));
        ctx.push(Value::I32(0x00FF));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x | y)),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(0xFFFF));
    }

    #[test]
    fn test_instruction_i32_xor() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(0xFFFF));
        ctx.push(Value::I32(0x00FF));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => ctx.push(Value::I32(x ^ y)),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(0xFF00));
    }

    #[test]
    fn test_instruction_i32_shl() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(1));
        ctx.push(Value::I32(3));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(x.wrapping_shl(y as u32 & 31)));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(8));
    }

    #[test]
    fn test_instruction_i32_shr_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(16));
        ctx.push(Value::I32(2));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32(x >> (y as u32 & 31)));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(4));
    }

    #[test]
    fn test_instruction_local_get_set() {
        let locals = vec![Value::I32(10), Value::I32(20), Value::I32(30)];
        let mut frame = Frame::new(0, locals, 0);

        // local.get 1
        let val = frame.get_local(1).unwrap();
        assert_eq!(val, Value::I32(20));

        // local.set 1 (set to 99)
        frame.set_local(1, Value::I32(99)).unwrap();
        assert_eq!(frame.get_local(1).unwrap(), Value::I32(99));
    }

    #[test]
    fn test_instruction_local_tee() {
        let locals = vec![Value::I32(0)];
        let mut frame = Frame::new(0, locals, 0);
        let ctx_stack_val = Value::I32(42);

        // local.tee 0 (set local and keep value on stack)
        frame.set_local(0, ctx_stack_val).unwrap();
        assert_eq!(frame.get_local(0).unwrap(), Value::I32(42));
    }

    #[test]
    fn test_decode_instruction_i32_const() {
        let bytecode = vec![0x41, 0x2A]; // i32.const 42
        let mut cursor = Cursor::new(bytecode.as_slice());
        let instr = decode_instruction(&mut cursor).unwrap();
        match instr {
            Instruction::I32Const(v) => assert_eq!(v, 42),
            _ => panic!("Expected I32Const"),
        }
    }

    #[test]
    fn test_decode_instruction_i32_add() {
        let bytecode = vec![0x6A]; // i32.add
        let mut cursor = Cursor::new(bytecode.as_slice());
        let instr = decode_instruction(&mut cursor).unwrap();
        match instr {
            Instruction::I32Add => {}
            _ => panic!("Expected I32Add"),
        }
    }

    #[test]
    fn test_decode_instruction_local_get() {
        let bytecode = vec![0x20, 0x01]; // local.get 1
        let mut cursor = Cursor::new(bytecode.as_slice());
        let instr = decode_instruction(&mut cursor).unwrap();
        match instr {
            Instruction::LocalGet(idx) => assert_eq!(idx, 1),
            _ => panic!("Expected LocalGet"),
        }
    }

    #[test]
    fn test_decode_instruction_local_set() {
        let bytecode = vec![0x21, 0x02]; // local.set 2
        let mut cursor = Cursor::new(bytecode.as_slice());
        let instr = decode_instruction(&mut cursor).unwrap();
        match instr {
            Instruction::LocalSet(idx) => assert_eq!(idx, 2),
            _ => panic!("Expected LocalSet"),
        }
    }

    #[test]
    fn test_instruction_nop() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        // nop does nothing
        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_instruction_drop() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(42));
        ctx.push(Value::I32(99));
        // drop removes top value
        ctx.pop().unwrap();
        assert_eq!(ctx.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_i32_rem_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(47));
        ctx.push(Value::I32(5));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                if y != 0 {
                    ctx.push(Value::I32(x % y));
                }
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(2)); // 47 % 5 = 2
    }

    #[test]
    fn test_i32_rotl() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(0x00000001u32 as i32));
        ctx.push(Value::I32(1));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32((x as u32).rotate_left(y as u32) as i32));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(0x00000002u32 as i32));
    }

    #[test]
    fn test_i32_rotr() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I32(0x80000000u32 as i32));
        ctx.push(Value::I32(1));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I32(x), Value::I32(y)) => {
                ctx.push(Value::I32((x as u32).rotate_right(y as u32) as i32));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(0x40000000u32 as i32));
    }

    #[test]
    fn test_i64_add() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(100));
        ctx.push(Value::I64(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => ctx.push(Value::I64(x.wrapping_add(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I64(142));
    }

    #[test]
    fn test_i64_sub() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(100));
        ctx.push(Value::I64(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => ctx.push(Value::I64(x.wrapping_sub(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I64(58));
    }

    #[test]
    fn test_i64_mul() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(6));
        ctx.push(Value::I64(7));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => ctx.push(Value::I64(x.wrapping_mul(y))),
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I64(42));
    }

    #[test]
    fn test_i64_div_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(84));
        ctx.push(Value::I64(2));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => {
                if y != 0 {
                    ctx.push(Value::I64(x / y));
                }
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I64(42));
    }

    #[test]
    fn test_i64_eq() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(42));
        ctx.push(Value::I64(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => {
                ctx.push(Value::I32(if x == y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_i64_lt_s() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::I64(10));
        ctx.push(Value::I64(42));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::I64(x), Value::I64(y)) => {
                ctx.push(Value::I32(if x < y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_f32_add() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F32(1.5));
        ctx.push(Value::F32(2.5));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F32(x), Value::F32(y)) => ctx.push(Value::F32(x + y)),
            _ => panic!("Type mismatch"),
        }

        match ctx.pop().unwrap() {
            Value::F32(x) => assert!((x - 4.0).abs() < 0.001),
            _ => panic!("Expected f32"),
        }
    }

    #[test]
    fn test_f32_mul() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F32(2.0));
        ctx.push(Value::F32(3.0));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F32(x), Value::F32(y)) => ctx.push(Value::F32(x * y)),
            _ => panic!("Type mismatch"),
        }

        match ctx.pop().unwrap() {
            Value::F32(x) => assert!((x - 6.0).abs() < 0.001),
            _ => panic!("Expected f32"),
        }
    }

    #[test]
    fn test_f32_eq() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F32(std::f32::consts::PI));
        ctx.push(Value::F32(std::f32::consts::PI));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F32(x), Value::F32(y)) => {
                ctx.push(Value::I32(if x == y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_f64_add() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F64(1.5));
        ctx.push(Value::F64(2.5));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F64(x), Value::F64(y)) => ctx.push(Value::F64(x + y)),
            _ => panic!("Type mismatch"),
        }

        match ctx.pop().unwrap() {
            Value::F64(x) => assert!((x - 4.0).abs() < 0.001),
            _ => panic!("Expected f64"),
        }
    }

    #[test]
    fn test_f64_div() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F64(10.0));
        ctx.push(Value::F64(2.0));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F64(x), Value::F64(y)) => ctx.push(Value::F64(x / y)),
            _ => panic!("Type mismatch"),
        }

        match ctx.pop().unwrap() {
            Value::F64(x) => assert!((x - 5.0).abs() < 0.001),
            _ => panic!("Expected f64"),
        }
    }

    #[test]
    fn test_f64_lt() {
        let mut ctx = ExecutionContext::new(1, None).unwrap();
        ctx.push(Value::F64(1.5));
        ctx.push(Value::F64(2.5));

        let b = ctx.pop().unwrap();
        let a = ctx.pop().unwrap();
        match (a, b) {
            (Value::F64(x), Value::F64(y)) => {
                ctx.push(Value::I32(if x < y { 1 } else { 0 }));
            }
            _ => panic!("Type mismatch"),
        }

        assert_eq!(ctx.pop().unwrap(), Value::I32(1));
    }

    #[test]
    fn test_function_call_simple() {
        use crate::runtime::core::module::{Function, FunctionType};

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![ValueType::I32, ValueType::I32],
                results: vec![ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![],
                code: vec![0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b],
            }],
            tables: vec![],
            memory: None,
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(10));
        executor.context.push(Value::I32(5));

        executor.call_function(0).unwrap();

        let result = executor.context.pop().unwrap();
        assert_eq!(result, Value::I32(15));
    }

    #[test]
    fn test_function_call_with_locals() {
        use crate::runtime::core::module::{Function, FunctionType};

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![ValueType::I32],
                results: vec![ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![(1, ValueType::I32)],
                code: vec![0x41, 0x05, 0x21, 0x01, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b],
            }],
            tables: vec![],
            memory: None,
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(10));

        executor.call_function(0).unwrap();

        let result = executor.context.pop().unwrap();
        assert_eq!(result, Value::I32(15));
    }

    #[test]
    fn test_multiple_return_values() {
        use crate::runtime::core::module::{Function, FunctionType};

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![],
                results: vec![ValueType::I32, ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![],
                code: vec![0x41, 0x0a, 0x41, 0x05, 0x0b],
            }],
            tables: vec![],
            memory: None,
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();
        let results = executor.execute(0).unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0], Value::I32(10));
        assert_eq!(results[1], Value::I32(5));
    }

    // Global operations tests
    #[test]
    fn test_global_get_set() {
        use crate::runtime::core::module::{Function, FunctionType, GlobalValue};

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![],
                results: vec![ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![],
                code: vec![0x23, 0x00, 0x0b],
            }],
            tables: vec![],
            memory: None,
            globals: vec![GlobalValue {
                mutable: true,
                value_type: ValueType::I32,
                init_expr: vec![],
            }],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();
        executor.context.globals[0] = Value::I32(42);

        let results = executor.execute(0).unwrap();
        assert_eq!(results[0], Value::I32(42));
    }

    // Memory operations tests via context
    #[test]
    fn test_memory_direct_i32_store_load() {
        use crate::runtime::core::module::MemoryType;

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();

        executor.context.memory.write_i32(100, 12345).unwrap();
        let val = executor.context.memory.read_i32(100).unwrap();
        assert_eq!(val, 12345);
    }

    #[test]
    fn test_memory_size() {
        use crate::runtime::core::module::MemoryType;

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 3,
                max: Some(5),
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let executor = Executor::new(module).unwrap();
        assert_eq!(executor.context.memory.pages(), 3);
    }

    #[test]
    fn test_memory_i8_operations() {
        use crate::runtime::core::module::MemoryType;

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();

        executor.context.memory.write_i8(50, -42).unwrap();
        let val = executor.context.memory.read_i8(50).unwrap();
        assert_eq!(val, -42);

        executor.context.memory.write_u8(100, 255).unwrap();
        let val = executor.context.memory.read_u8(100).unwrap();
        assert_eq!(val, 255);
    }

    #[test]
    fn test_memory_i16_operations() {
        use crate::runtime::core::module::MemoryType;

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();

        executor.context.memory.write_i16(200, -1000).unwrap();
        let val = executor.context.memory.read_i16(200).unwrap();
        assert_eq!(val, -1000);

        executor.context.memory.write_u16(300, 65535).unwrap();
        let val = executor.context.memory.read_u16(300).unwrap();
        assert_eq!(val, 65535);
    }

    // ===== v0.16.0 Tests: Data Section Initialization =====

    #[test]
    fn test_data_segment_string_constant() {
        use crate::runtime::core::module::{DataSegment, MemoryType};

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![DataSegment {
                offset_expr: vec![0x41, 0x10, 0x0B], // i32.const 16, end
                data: b"Hello, WASM!".to_vec(),
            }],
        };

        let executor = Executor::new(module).unwrap();
        let bytes = executor.context.memory.read_bytes(16, 12).unwrap();
        assert_eq!(&bytes, b"Hello, WASM!");
    }

    #[test]
    fn test_data_segment_multiple() {
        use crate::runtime::core::module::{DataSegment, MemoryType};

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![
                DataSegment {
                    offset_expr: vec![0x41, 0x00, 0x0B], // i32.const 0
                    data: vec![0xDE, 0xAD],
                },
                DataSegment {
                    offset_expr: vec![0x41, 0x10, 0x0B], // i32.const 16
                    data: vec![0xBE, 0xEF],
                },
            ],
        };

        let executor = Executor::new(module).unwrap();
        assert_eq!(executor.context.memory.read_u8(0).unwrap(), 0xDE);
        assert_eq!(executor.context.memory.read_u8(1).unwrap(), 0xAD);
        assert_eq!(executor.context.memory.read_u8(16).unwrap(), 0xBE);
        assert_eq!(executor.context.memory.read_u8(17).unwrap(), 0xEF);
    }

    #[test]
    fn test_data_segment_out_of_bounds() {
        use crate::runtime::core::module::{DataSegment, MemoryType};

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: Some(1),
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![DataSegment {
                offset_expr: vec![0x41, 0xFF, 0xFF, 0x03, 0x0B], // i32.const 65535
                data: vec![0x00, 0x01], // 2 bytes at offset 65535 overflows 1 page
            }],
        };

        let result = Executor::new(module);
        assert!(result.is_err());
    }

    #[test]
    fn test_data_segment_passive_skipped() {
        use crate::runtime::core::module::{DataSegment, MemoryType};

        let module = Module {
            version: 1,
            types: vec![],
            imports: vec![],
            functions: vec![],
            tables: vec![],
            memory: Some(MemoryType {
                initial: 1,
                max: None,
            }),
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![DataSegment {
                offset_expr: vec![], // passive segment (empty offset)
                data: vec![0xFF; 100],
            }],
        };

        let executor = Executor::new(module).unwrap();
        assert_eq!(executor.context.memory.read_u8(0).unwrap(), 0x00);
    }

    // ===== v0.16.0 Tests: Type Conversion Instructions =====

    #[test]
    fn test_i32_wrap_i64() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I64(0x1_0000_002A)); // wraps to 42
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xA7, 0x0B]; // i32.wrap_i64, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::I32(42));
    }

    #[test]
    fn test_i64_extend_i32_s() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(-1));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xAC, 0x0B]; // i64.extend_i32_s, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::I64(-1));
    }

    #[test]
    fn test_i64_extend_i32_u() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(-1)); // 0xFFFFFFFF unsigned
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xAD, 0x0B]; // i64.extend_i32_u, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::I64(0xFFFF_FFFF_i64));
    }

    #[test]
    fn test_f32_convert_i32_s() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(-42));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xB2, 0x0B]; // f32.convert_i32_s, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::F32(-42.0));
    }

    #[test]
    fn test_f64_promote_f32() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::F32(1.5));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xBB, 0x0B]; // f64.promote_f32, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        match executor.context.pop().unwrap() {
            Value::F64(x) => assert!((x - 1.5).abs() < 0.001),
            other => panic!("Expected F64, got {other:?}"),
        }
    }

    #[test]
    fn test_f32_demote_f64() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::F64(2.5));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xB6, 0x0B]; // f32.demote_f64, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        match executor.context.pop().unwrap() {
            Value::F32(x) => assert!((x - 2.5).abs() < 0.001),
            other => panic!("Expected F32, got {other:?}"),
        }
    }

    #[test]
    fn test_i32_reinterpret_f32() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::F32(1.0));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xBC, 0x0B]; // i32.reinterpret_f32, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(
            executor.context.pop().unwrap(),
            Value::I32(0x3F80_0000_u32 as i32)
        ); // IEEE 754 for 1.0
    }

    #[test]
    fn test_f32_reinterpret_i32() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(0x3F80_0000_u32 as i32));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xBE, 0x0B]; // f32.reinterpret_i32, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::F32(1.0));
    }

    #[test]
    fn test_i32_trunc_f64_s_nan() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::F64(f64::NAN));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xAA, 0x0B]; // i32.trunc_f64_s, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        let result = executor.execute_bytecode(&mut cursor);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("NaN"));
    }

    #[test]
    fn test_i32_trunc_f32_u_overflow() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::F32(-1.0));
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0xA9, 0x0B]; // i32.trunc_f32_u, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        let result = executor.execute_bytecode(&mut cursor);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("overflow"));
    }

    #[test]
    fn test_select_true() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(10)); // val1
        executor.context.push(Value::I32(20)); // val2
        executor.context.push(Value::I32(1)); // cond (true)
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0x1B, 0x0B]; // select, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::I32(10));
    }

    #[test]
    fn test_select_false() {
        let module = Module::new();
        let mut executor = Executor::new(module).unwrap();
        executor.context.push(Value::I32(10)); // val1
        executor.context.push(Value::I32(20)); // val2
        executor.context.push(Value::I32(0)); // cond (false)
        let frame = Frame::new(0, vec![], 0);
        executor.context.push_frame(frame);

        let bytecode = vec![0x1B, 0x0B]; // select, end
        let mut cursor = Cursor::new(bytecode.as_slice());
        executor.execute_bytecode(&mut cursor).unwrap();
        executor.context.pop_frame().unwrap();
        assert_eq!(executor.context.pop().unwrap(), Value::I32(20));
    }

    // ===== v0.16.0 Tests: br_table =====

    #[test]
    fn test_br_table_case0() {
        use crate::runtime::core::module::{Function, FunctionType};

        // block $b0
        //   block $b1
        //     block $b2
        //       local.get 0
        //       br_table 0 1 2   ;; targets: [$b2, $b1, $b0], default=$b0
        //     end $b2
        //     i32.const 20
        //     return
        //   end $b1
        //   i32.const 10
        //   return
        // end $b0
        // i32.const 30
        let code = vec![
            0x02, 0x40, // block void
            0x02, 0x40, // block void
            0x02, 0x40, // block void
            0x20, 0x00, // local.get 0
            0x0E, 0x02, 0x00, 0x01, 0x02, // br_table [0, 1] default=2
            0x0B, // end (innermost)
            0x41, 0x14, // i32.const 20
            0x0F, // return
            0x0B, // end (middle)
            0x41, 0x0A, // i32.const 10
            0x0F, // return
            0x0B, // end (outer)
            0x41, 0x1E, // i32.const 30
            0x0B, // end (function)
        ];

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![ValueType::I32],
                results: vec![ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![],
                code,
            }],
            tables: vec![],
            memory: None,
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();

        // Case 0 → falls through innermost block → returns 20
        let results = executor.execute_with_args(0, vec![Value::I32(0)]).unwrap();
        assert_eq!(results[0], Value::I32(20));
    }

    #[test]
    fn test_br_table_default() {
        use crate::runtime::core::module::{Function, FunctionType};

        let code = vec![
            0x02, 0x40, // block void
            0x02, 0x40, // block void
            0x02, 0x40, // block void
            0x20, 0x00, // local.get 0
            0x0E, 0x02, 0x00, 0x01, 0x02, // br_table [0, 1] default=2
            0x0B, // end (innermost)
            0x41, 0x14, // i32.const 20
            0x0F, // return
            0x0B, // end (middle)
            0x41, 0x0A, // i32.const 10
            0x0F, // return
            0x0B, // end (outer)
            0x41, 0x1E, // i32.const 30
            0x0B, // end (function)
        ];

        let module = Module {
            version: 1,
            types: vec![FunctionType {
                params: vec![ValueType::I32],
                results: vec![ValueType::I32],
            }],
            imports: vec![],
            functions: vec![Function {
                type_index: 0,
                locals: vec![],
                code,
            }],
            tables: vec![],
            memory: None,
            globals: vec![],
            exports: std::collections::HashMap::new(),
            start: None,
            elements: vec![],
            data: vec![],
        };

        let mut executor = Executor::new(module).unwrap();

        // Out-of-range index (99) → uses default (label 2 → outer block) → returns 30
        let results = executor.execute_with_args(0, vec![Value::I32(99)]).unwrap();
        assert_eq!(results[0], Value::I32(30));
    }

    #[test]
    fn test_evaluate_const_expr_i32() {
        let expr = vec![0x41, 0x2A, 0x0B]; // i32.const 42, end
        assert_eq!(evaluate_const_expr(&expr).unwrap(), 42);
    }

    #[test]
    fn test_evaluate_const_expr_i64() {
        let expr = vec![0x42, 0x80, 0x01, 0x0B]; // i64.const 128, end
        assert_eq!(evaluate_const_expr(&expr).unwrap(), 128);
    }

    #[test]
    fn test_decode_type_conversion_opcodes() {
        let cases: Vec<(u8, &str)> = vec![
            (0xA7, "I32WrapI64"),
            (0xA8, "I32TruncF32S"),
            (0xAC, "I64ExtendI32S"),
            (0xAD, "I64ExtendI32U"),
            (0xB2, "F32ConvertI32S"),
            (0xB6, "F32DemoteF64"),
            (0xB7, "F64ConvertI32S"),
            (0xBB, "F64PromoteF32"),
            (0xBC, "I32Reinterpret"),
            (0xBD, "I64Reinterpret"),
            (0xBE, "F32Reinterpret"),
            (0xBF, "F64Reinterpret"),
        ];
        for (opcode, name) in cases {
            let bytecode = vec![opcode];
            let mut cursor = Cursor::new(bytecode.as_slice());
            let instr = decode_instruction(&mut cursor);
            assert!(
                instr.is_ok(),
                "Failed to decode opcode 0x{opcode:02X} ({name})"
            );
        }
    }

    #[test]
    fn test_decode_f32_unary_opcodes() {
        assert!(matches!(
            decode_instruction(&mut Cursor::new([0x8B].as_slice())).unwrap(),
            Instruction::F32Abs
        ));
        assert!(matches!(
            decode_instruction(&mut Cursor::new([0x8C].as_slice())).unwrap(),
            Instruction::F32Neg
        ));
        assert!(matches!(
            decode_instruction(&mut Cursor::new([0x91].as_slice())).unwrap(),
            Instruction::F32Sqrt
        ));
    }

    #[test]
    fn test_decode_f64_unary_opcodes() {
        assert!(matches!(
            decode_instruction(&mut Cursor::new([0x99].as_slice())).unwrap(),
            Instruction::F64Abs
        ));
        assert!(matches!(
            decode_instruction(&mut Cursor::new([0x9F].as_slice())).unwrap(),
            Instruction::F64Sqrt
        ));
    }
}