just-engine 0.1.0

A ground-up ES6 JavaScript engine with tree-walking interpreter, bytecode VMs, and Cranelift JIT compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
//! Expression evaluation.
//!
//! This module provides the core expression evaluation logic for the JavaScript interpreter.
//! It handles all expression types defined in the AST.

use crate::parser::ast::{
    AssignmentOperator, BinaryOperator, ClassData, ExpressionOrSpreadElement, ExpressionOrSuper,
    ExpressionType, ExpressionPatternType, FunctionData, LiteralData, LiteralType, MemberExpressionType,
    MethodDefinitionKind, PatternOrExpression, PatternType, PropertyData, PropertyKind, UnaryOperator,
    UpdateOperator, LogicalOperator,
};
use crate::runner::ds::error::JErrorType;
use crate::runner::ds::object::{JsObject, JsObjectType, ObjectBase, ObjectType};
use crate::runner::ds::object_property::{PropertyDescriptor, PropertyDescriptorAccessor, PropertyDescriptorData, PropertyKey};
use crate::runner::ds::value::{JsValue, JsNumberType};
use crate::runner::plugin::types::{EvalContext, SimpleObject};

use std::cell::RefCell;
use std::rc::Rc;

use super::types::ValueResult;

/// Evaluate an expression and return its value.
pub fn evaluate_expression(
    expr: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    match expr {
        ExpressionType::Literal(lit) => evaluate_literal(lit),

        ExpressionType::ExpressionWhichCanBePattern(pattern) => {
            evaluate_expression_pattern(pattern, ctx)
        }

        ExpressionType::ThisExpression { .. } => {
            Ok(ctx.global_this.clone().unwrap_or(JsValue::Undefined))
        }

        ExpressionType::ArrayExpression { elements, .. } => {
            evaluate_array_expression(elements, ctx)
        }

        ExpressionType::ObjectExpression { properties, .. } => {
            evaluate_object_expression(properties, ctx)
        }

        ExpressionType::FunctionOrGeneratorExpression(func_data) => {
            create_function_object(func_data, ctx)
        }

        ExpressionType::UnaryExpression { operator, argument, .. } => {
            evaluate_unary_expression(operator, argument, ctx)
        }

        ExpressionType::BinaryExpression { operator, left, right, .. } => {
            evaluate_binary_expression(operator, left, right, ctx)
        }

        ExpressionType::LogicalExpression { operator, left, right, .. } => {
            evaluate_logical_expression(operator, left, right, ctx)
        }

        ExpressionType::UpdateExpression { operator, argument, prefix, .. } => {
            evaluate_update_expression(operator, argument, *prefix, ctx)
        }

        ExpressionType::AssignmentExpression { operator, left, right, .. } => {
            evaluate_assignment_expression(operator, left, right, ctx)
        }

        ExpressionType::ConditionalExpression { test, consequent, alternate, .. } => {
            evaluate_conditional_expression(test, consequent, alternate, ctx)
        }

        ExpressionType::CallExpression { callee, arguments, .. } => {
            evaluate_call_expression(callee, arguments, ctx)
        }

        ExpressionType::NewExpression { callee, arguments, .. } => {
            evaluate_new_expression(callee, arguments, ctx)
        }

        ExpressionType::SequenceExpression { expressions, .. } => {
            evaluate_sequence_expression(expressions, ctx)
        }

        ExpressionType::TemplateLiteral(_) => {
            Err(JErrorType::TypeError("Template literal not yet implemented".to_string()))
        }

        ExpressionType::TaggedTemplateExpression { .. } => {
            Err(JErrorType::TypeError("Tagged template expression not yet implemented".to_string()))
        }

        ExpressionType::ClassExpression(class_data) => {
            evaluate_class_expression(class_data, ctx)
        }

        ExpressionType::YieldExpression { argument, delegate, .. } => {
            if *delegate {
                // yield* not yet supported
                return Err(JErrorType::TypeError("yield* not yet implemented".to_string()));
            }
            // Evaluate the argument
            let value = if let Some(arg) = argument {
                evaluate_expression(arg, ctx)?
            } else {
                JsValue::Undefined
            };
            // Return a special error that signals a yield
            Err(JErrorType::YieldValue(value))
        }

        ExpressionType::MetaProperty { .. } => {
            Err(JErrorType::TypeError("Meta property not yet implemented".to_string()))
        }

        ExpressionType::ArrowFunctionExpression { .. } => {
            Err(JErrorType::TypeError("Arrow function expression not yet implemented".to_string()))
        }

        ExpressionType::MemberExpression(member_expr) => {
            evaluate_member_expression(member_expr, ctx)
        }
    }
}

/// Evaluate a literal and return its value.
fn evaluate_literal(lit: &LiteralData) -> ValueResult {
    Ok(match &lit.value {
        LiteralType::NullLiteral => JsValue::Null,
        LiteralType::BooleanLiteral(b) => JsValue::Boolean(*b),
        LiteralType::StringLiteral(s) => JsValue::String(s.clone()),
        LiteralType::NumberLiteral(n) => {
            use crate::parser::ast::NumberLiteralType;
            match n {
                NumberLiteralType::IntegerLiteral(i) => JsValue::Number(JsNumberType::Integer(*i)),
                NumberLiteralType::FloatLiteral(f) => JsValue::Number(JsNumberType::Float(*f)),
            }
        }
        LiteralType::RegExpLiteral { .. } => {
            return Err(JErrorType::TypeError("RegExp literal not yet implemented".to_string()));
        }
    })
}

/// Evaluate an array expression and return an array object.
fn evaluate_array_expression(
    elements: &[Option<ExpressionOrSpreadElement>],
    ctx: &mut EvalContext,
) -> ValueResult {
    use crate::runner::ds::object::JsObject;

    // Create a new array object (tracked for heap accounting)
    let mut array_obj = ctx.new_tracked_object()?;

    let mut index = 0;
    for element in elements {
        if let Some(elem) = element {
            match elem {
                ExpressionOrSpreadElement::Expression(expr) => {
                    let value = evaluate_expression(expr, ctx)?;
                    // Define the element as a property
                    let key = PropertyKey::Str(index.to_string());
                    array_obj.get_object_base_mut().properties.insert(
                        key,
                        PropertyDescriptor::Data(PropertyDescriptorData {
                            value,
                            writable: true,
                            enumerable: true,
                            configurable: true,
                        }),
                    );
                    index += 1;
                }
                ExpressionOrSpreadElement::SpreadElement(spread_expr) => {
                    // Evaluate the spread expression
                    let spread_value = evaluate_expression(spread_expr, ctx)?;

                    // If it's an array, spread its elements
                    if let JsValue::Object(spread_obj) = spread_value {
                        let borrowed = spread_obj.borrow();
                        let base = borrowed.as_js_object().get_object_base();

                        // Get length property if it exists
                        let length = if let Some(PropertyDescriptor::Data(prop)) =
                            base.properties.get(&PropertyKey::Str("length".to_string()))
                        {
                            match &prop.value {
                                JsValue::Number(JsNumberType::Integer(n)) => *n as usize,
                                JsValue::Number(JsNumberType::Float(n)) => *n as usize,
                                _ => 0,
                            }
                        } else {
                            0
                        };

                        // Iterate over array indices
                        for i in 0..length {
                            let elem_key = PropertyKey::Str(i.to_string());
                            let elem_value = if let Some(PropertyDescriptor::Data(prop)) =
                                base.properties.get(&elem_key)
                            {
                                prop.value.clone()
                            } else {
                                JsValue::Undefined
                            };

                            // Add to result array
                            let key = PropertyKey::Str(index.to_string());
                            array_obj.get_object_base_mut().properties.insert(
                                key,
                                PropertyDescriptor::Data(PropertyDescriptorData {
                                    value: elem_value,
                                    writable: true,
                                    enumerable: true,
                                    configurable: true,
                                }),
                            );
                            index += 1;
                        }
                    } else if let JsValue::String(s) = spread_value {
                        // Spread string characters
                        for ch in s.chars() {
                            let key = PropertyKey::Str(index.to_string());
                            array_obj.get_object_base_mut().properties.insert(
                                key,
                                PropertyDescriptor::Data(PropertyDescriptorData {
                                    value: JsValue::String(ch.to_string()),
                                    writable: true,
                                    enumerable: true,
                                    configurable: true,
                                }),
                            );
                            index += 1;
                        }
                    } else {
                        return Err(JErrorType::TypeError(
                            "Spread requires an iterable".to_string(),
                        ));
                    }
                }
            }
        } else {
            // Holes (None elements) are left as undefined/missing
            index += 1;
        }
    }

    // Set the length property
    array_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("length".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Number(JsNumberType::Integer(index as i64)),
            writable: true,
            enumerable: false,
            configurable: false,
        }),
    );

    // Wrap in JsObjectType
    let obj: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(array_obj))));
    Ok(JsValue::Object(obj))
}

/// Evaluate an object expression and return an object.
fn evaluate_object_expression(
    properties: &[PropertyData<Box<ExpressionType>>],
    ctx: &mut EvalContext,
) -> ValueResult {
    use std::collections::HashMap;

    // Create a new object (tracked for heap accounting)
    let mut obj = ctx.new_tracked_object()?;

    // Track accessor properties to merge getter/setter pairs
    let mut accessors: HashMap<String, (Option<JsObjectType>, Option<JsObjectType>)> = HashMap::new();

    for prop in properties {
        // Get the property key
        let key = get_object_property_key(&prop.key, prop.computed, ctx)?;

        match prop.kind {
            PropertyKind::Init => {
                // Evaluate the value
                let value = evaluate_expression(&prop.value, ctx)?;

                // Define the property
                obj.get_object_base_mut().properties.insert(
                    PropertyKey::Str(key),
                    PropertyDescriptor::Data(PropertyDescriptorData {
                        value,
                        writable: true,
                        enumerable: true,
                        configurable: true,
                    }),
                );
            }
            PropertyKind::Get => {
                // The value should be a function expression
                if let ExpressionType::FunctionOrGeneratorExpression(func_data) = prop.value.as_ref() {
                    let getter_fn = create_function_object(func_data, ctx)?;
                    if let JsValue::Object(getter_obj) = getter_fn {
                        let entry = accessors.entry(key).or_insert((None, None));
                        entry.0 = Some(getter_obj);
                    }
                } else {
                    return Err(JErrorType::TypeError("Getter must be a function".to_string()));
                }
            }
            PropertyKind::Set => {
                // The value should be a function expression
                if let ExpressionType::FunctionOrGeneratorExpression(func_data) = prop.value.as_ref() {
                    let setter_fn = create_function_object(func_data, ctx)?;
                    if let JsValue::Object(setter_obj) = setter_fn {
                        let entry = accessors.entry(key).or_insert((None, None));
                        entry.1 = Some(setter_obj);
                    }
                } else {
                    return Err(JErrorType::TypeError("Setter must be a function".to_string()));
                }
            }
        }
    }

    // Add accessor properties to the object
    for (key, (getter, setter)) in accessors {
        obj.get_object_base_mut().properties.insert(
            PropertyKey::Str(key),
            PropertyDescriptor::Accessor(PropertyDescriptorAccessor {
                get: getter,
                set: setter,
                enumerable: true,
                configurable: true,
            }),
        );
    }

    // Wrap in JsObjectType
    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(obj))));
    Ok(JsValue::Object(obj_ref))
}

/// Get the property key from an object literal property.
fn get_object_property_key(
    key_expr: &ExpressionType,
    computed: bool,
    ctx: &mut EvalContext,
) -> Result<String, JErrorType> {
    if computed {
        // Computed property: [expr]
        let key_value = evaluate_expression(key_expr, ctx)?;
        Ok(to_string(&key_value))
    } else {
        // Static property key
        match key_expr {
            ExpressionType::ExpressionWhichCanBePattern(ExpressionPatternType::Identifier(id)) => {
                Ok(id.name.clone())
            }
            ExpressionType::Literal(lit) => match &lit.value {
                LiteralType::StringLiteral(s) => Ok(s.clone()),
                LiteralType::NumberLiteral(n) => {
                    use crate::parser::ast::NumberLiteralType;
                    match n {
                        NumberLiteralType::IntegerLiteral(i) => Ok(i.to_string()),
                        NumberLiteralType::FloatLiteral(f) => Ok(f.to_string()),
                    }
                }
                _ => Err(JErrorType::TypeError("Invalid property key".to_string())),
            },
            _ => Err(JErrorType::TypeError("Invalid property key".to_string())),
        }
    }
}

/// Evaluate an expression pattern (identifier).
fn evaluate_expression_pattern(
    pattern: &ExpressionPatternType,
    ctx: &mut EvalContext,
) -> ValueResult {
    match pattern {
        ExpressionPatternType::Identifier(id) => {
            // Look up the identifier in the environment chain
            ctx.get_binding(&id.name)
        }
    }
}

/// Evaluate a member expression (property access).
fn evaluate_member_expression(
    member_expr: &MemberExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    match member_expr {
        MemberExpressionType::SimpleMemberExpression { object, property, .. } => {
            // Evaluate the object
            let obj_value = evaluate_expression_or_super(object, ctx)?;
            let prop_name = &property.name;

            // Get the property (with getter support)
            get_property_with_ctx(&obj_value, prop_name, ctx)
        }
        MemberExpressionType::ComputedMemberExpression { object, property, .. } => {
            // Evaluate the object
            let obj_value = evaluate_expression_or_super(object, ctx)?;

            // Evaluate the property expression to get the key
            let prop_value = evaluate_expression(property, ctx)?;
            let prop_name = to_property_key(&prop_value);

            // Get the property (with getter support)
            get_property_with_ctx(&obj_value, &prop_name, ctx)
        }
    }
}

/// Evaluate an ExpressionOrSuper.
fn evaluate_expression_or_super(
    expr_or_super: &ExpressionOrSuper,
    ctx: &mut EvalContext,
) -> ValueResult {
    match expr_or_super {
        ExpressionOrSuper::Expression(expr) => evaluate_expression(expr, ctx),
        ExpressionOrSuper::Super => {
            Err(JErrorType::TypeError("super not yet supported".to_string()))
        }
    }
}

/// Evaluate a call expression (function call).
fn evaluate_call_expression(
    callee: &ExpressionOrSuper,
    arguments: &[ExpressionOrSpreadElement],
    ctx: &mut EvalContext,
) -> ValueResult {
    // Check if this is a member expression call (e.g., Math.abs, console.log)
    // If so, try super-global method dispatch first
    if let ExpressionOrSuper::Expression(expr) = callee {
        if let ExpressionType::MemberExpression(member) = expr.as_ref() {
            if let MemberExpressionType::SimpleMemberExpression { object, property, .. } = member {
                // Try to get the object name for super-global lookup
                if let ExpressionOrSuper::Expression(obj_expr) = object {
                    if let ExpressionType::ExpressionWhichCanBePattern(
                        ExpressionPatternType::Identifier(id)
                    ) = obj_expr.as_ref() {
                        let obj_name = &id.name;
                        let method_name = &property.name;
                        
                        // Evaluate arguments first
                        let args = evaluate_arguments(arguments, ctx)?;
                        
                        // Try super-global method dispatch
                        let sg = ctx.super_global.clone();
                        let this_value = ctx.resolve_binding(obj_name).unwrap_or(JsValue::Undefined);
                        
                        let sg_result = sg.borrow().call_method(
                            obj_name,
                            method_name,
                            ctx,
                            this_value.clone(),
                            args.clone(),
                        );
                        
                        if let Some(result) = sg_result {
                            return result;
                        }
                        
                        // Fall through to normal property lookup if super-global doesn't handle it
                    }
                }
            }
        }
    }
    
    // Normal call path: evaluate the callee to get the function
    let callee_value = evaluate_expression_or_super(callee, ctx)?;

    // Get the 'this' value for the call
    let this_value = get_call_this_value(callee, ctx);

    // Evaluate the arguments
    let args = evaluate_arguments(arguments, ctx)?;

    // Call the function
    call_value(&callee_value, this_value, args, ctx)
}

/// Evaluate a new expression (constructor call).
fn evaluate_new_expression(
    callee: &ExpressionType,
    arguments: &[ExpressionOrSpreadElement],
    ctx: &mut EvalContext,
) -> ValueResult {
    // Check if this is a simple identifier constructor (e.g., new String(), new Number())
    // If so, try super-global constructor dispatch first
    if let ExpressionType::ExpressionWhichCanBePattern(
        ExpressionPatternType::Identifier(id)
    ) = callee {
        let ctor_name = &id.name;
        
        // Evaluate arguments first
        let args = evaluate_arguments(arguments, ctx)?;
        
        // Try super-global constructor dispatch
        let sg = ctx.super_global.clone();
        let sg_result = sg.borrow().call_constructor(ctor_name, ctx, args.clone());
        
        if let Some(result) = sg_result {
            return result;
        }
        
        // Fall through to normal evaluation if super-global doesn't handle it
    }
    
    // Normal constructor path: evaluate the callee to get the constructor function
    let constructor = evaluate_expression(callee, ctx)?;

    // Verify it's callable
    let ctor_obj = match &constructor {
        JsValue::Object(obj) => {
            if !obj.borrow().is_callable() {
                return Err(JErrorType::TypeError(format!(
                    "{} is not a constructor",
                    constructor
                )));
            }
            obj.clone()
        }
        _ => {
            return Err(JErrorType::TypeError(format!(
                "{} is not a constructor",
                constructor
            )));
        }
    };

    // Create a new object for 'this'
    let new_obj = create_new_object_for_constructor(&ctor_obj)?;

    // Evaluate the arguments
    let args = evaluate_arguments(arguments, ctx)?;

    // Call the constructor with the new object as 'this'
    let result = call_value(&constructor, JsValue::Object(new_obj.clone()), args, ctx)?;

    // If constructor returns an object, use that; otherwise use the new object
    match result {
        JsValue::Object(_) => Ok(result),
        _ => Ok(JsValue::Object(new_obj)),
    }
}

/// Create a new object for use in a constructor call.
/// Sets up the prototype chain from the constructor's prototype property.
fn create_new_object_for_constructor(
    constructor: &JsObjectType,
) -> Result<JsObjectType, JErrorType> {
    use crate::runner::ds::object::{JsObject, ObjectType};
    use crate::runner::ds::object_property::{PropertyDescriptor, PropertyKey};

    // Create a new empty object
    let mut new_obj = SimpleObject::new();

    // Get the prototype from the constructor's 'prototype' property
    let ctor_borrowed = constructor.borrow();
    let prototype_key = PropertyKey::Str("prototype".to_string());

    if let Some(PropertyDescriptor::Data(data)) =
        ctor_borrowed.as_js_object().get_object_base().properties.get(&prototype_key)
    {
        if let JsValue::Object(proto_obj) = &data.value {
            // Set the prototype field on ObjectBase (used by get_prototype_of)
            new_obj.get_object_base_mut().prototype = Some(proto_obj.clone());
        }
    }

    drop(ctor_borrowed);

    let obj: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(new_obj))));
    Ok(obj)
}

/// Get the 'this' value for a call expression.
fn get_call_this_value(callee: &ExpressionOrSuper, ctx: &mut EvalContext) -> JsValue {
    match callee {
        ExpressionOrSuper::Expression(expr) => {
            match expr.as_ref() {
                // For member expressions, 'this' is the object
                ExpressionType::MemberExpression(member) => {
                    match member {
                        MemberExpressionType::SimpleMemberExpression { object, .. } |
                        MemberExpressionType::ComputedMemberExpression { object, .. } => {
                            match object {
                                ExpressionOrSuper::Expression(obj_expr) => {
                                    evaluate_expression(obj_expr, ctx).unwrap_or(JsValue::Undefined)
                                }
                                ExpressionOrSuper::Super => JsValue::Undefined,
                            }
                        }
                    }
                }
                // For other expressions, 'this' is undefined (or global in non-strict)
                _ => ctx.global_this.clone().unwrap_or(JsValue::Undefined),
            }
        }
        ExpressionOrSuper::Super => JsValue::Undefined,
    }
}

/// Evaluate call arguments.
fn evaluate_arguments(
    arguments: &[ExpressionOrSpreadElement],
    ctx: &mut EvalContext,
) -> Result<Vec<JsValue>, JErrorType> {
    let mut args = Vec::with_capacity(arguments.len());
    for arg in arguments {
        match arg {
            ExpressionOrSpreadElement::Expression(expr) => {
                args.push(evaluate_expression(expr, ctx)?);
            }
            ExpressionOrSpreadElement::SpreadElement(spread_expr) => {
                // Evaluate the spread expression
                let spread_value = evaluate_expression(spread_expr, ctx)?;

                // If it's an array, spread its elements into args
                if let JsValue::Object(spread_obj) = spread_value {
                    let borrowed = spread_obj.borrow();
                    let base = borrowed.as_js_object().get_object_base();

                    // Get length property if it exists
                    let length = if let Some(PropertyDescriptor::Data(prop)) =
                        base.properties.get(&PropertyKey::Str("length".to_string()))
                    {
                        match &prop.value {
                            JsValue::Number(JsNumberType::Integer(n)) => *n as usize,
                            JsValue::Number(JsNumberType::Float(n)) => *n as usize,
                            _ => 0,
                        }
                    } else {
                        0
                    };

                    // Iterate over array indices and add each element to args
                    for i in 0..length {
                        let elem_key = PropertyKey::Str(i.to_string());
                        let elem_value = if let Some(PropertyDescriptor::Data(prop)) =
                            base.properties.get(&elem_key)
                        {
                            prop.value.clone()
                        } else {
                            JsValue::Undefined
                        };
                        args.push(elem_value);
                    }
                } else if let JsValue::String(s) = spread_value {
                    // Spread string characters as separate args
                    for ch in s.chars() {
                        args.push(JsValue::String(ch.to_string()));
                    }
                } else {
                    return Err(JErrorType::TypeError(
                        "Spread requires an iterable".to_string(),
                    ));
                }
            }
        }
    }
    Ok(args)
}

/// Call a value as a function.
fn call_value(
    callee: &JsValue,
    this_value: JsValue,
    args: Vec<JsValue>,
    ctx: &mut EvalContext,
) -> ValueResult {
    match callee {
        JsValue::Object(obj) => {
            let obj_ref = obj.borrow();
            if obj_ref.is_callable() {
                drop(obj_ref);
                // For now, we'll call through our execution context stack
                // This is a simplified implementation that doesn't fully support
                // user-defined functions yet, but will work for native functions
                // stored in NativeFunctionObject
                call_function_object(obj, this_value, args, ctx)
            } else {
                Err(JErrorType::TypeError(format!(
                    "{} is not a function",
                    callee
                )))
            }
        }
        _ => Err(JErrorType::TypeError(format!(
            "{} is not a function",
            callee
        ))),
    }
}

/// Call a function object.
pub fn call_function_object(
    func: &crate::runner::ds::object::JsObjectType,
    this_value: JsValue,
    args: Vec<JsValue>,
    ctx: &mut EvalContext,
) -> ValueResult {
    let func_ref = func.borrow();

    match &*func_ref {
        ObjectType::Function(func_obj) => {
            // Get function metadata (these are Rc so cloning is cheap)
            let body = func_obj.get_function_object_base().body_code.clone();
            let params = func_obj.get_function_object_base().formal_parameters.clone();
            let func_env = func_obj.get_function_object_base().environment.clone();

            drop(func_ref);

            // Create a new function scope
            let saved_lex_env = ctx.lex_env.clone();
            let saved_var_env = ctx.var_env.clone();

            // Create new environment for the function, with the function's closure as outer
            use crate::runner::ds::env_record::new_declarative_environment;
            let func_scope = new_declarative_environment(Some(func_env));
            ctx.lex_env = func_scope.clone();
            ctx.var_env = func_scope;

            // Bind parameters to arguments
            for (i, param) in params.iter().enumerate() {
                if let crate::parser::ast::PatternType::PatternWhichCanBeExpression(
                    ExpressionPatternType::Identifier(id)
                ) = param {
                    let arg_value = args.get(i).cloned().unwrap_or(JsValue::Undefined);
                    ctx.create_binding(&id.name, false)?;
                    ctx.initialize_binding(&id.name, arg_value)?;
                }
            }

            // Execute each statement in the function body
            use super::statement::execute_statement;
            use super::types::CompletionType;

            let mut result_completion = super::types::Completion::normal();

            for stmt in body.body.iter() {
                let completion = execute_statement(stmt, ctx)?;

                match completion.completion_type {
                    CompletionType::Return => {
                        result_completion = completion;
                        break;
                    }
                    CompletionType::Throw => {
                        // Restore environment before returning error
                        ctx.lex_env = saved_lex_env;
                        ctx.var_env = saved_var_env;
                        return Err(JErrorType::TypeError(format!(
                            "Uncaught exception: {:?}",
                            completion.value
                        )));
                    }
                    CompletionType::Break | CompletionType::Continue | CompletionType::Yield => {
                        // These shouldn't escape function body
                        result_completion = completion;
                        break;
                    }
                    CompletionType::Normal => {
                        result_completion = completion;
                    }
                }
            }

            // Restore the previous environment
            ctx.lex_env = saved_lex_env;
            ctx.var_env = saved_var_env;

            // Return the result
            match result_completion.completion_type {
                CompletionType::Return => Ok(result_completion.get_value()),
                _ => Ok(JsValue::Undefined),
            }
        }
        ObjectType::Ordinary(obj) => {
            // Check if it's a SimpleFunctionObject (has marker property)
            let marker = PropertyKey::Str("__simple_function__".to_string());
            let default_ctor_marker = PropertyKey::Str("__default_constructor__".to_string());

            let generator_marker = PropertyKey::Str("__generator__".to_string());
            let generator_next_marker = PropertyKey::Str("__generator_next__".to_string());

            if obj.get_object_base().properties.contains_key(&default_ctor_marker) {
                // It's a default constructor (no-op) - just return undefined
                drop(func_ref);
                Ok(JsValue::Undefined)
            } else if let Some(PropertyDescriptor::Data(data)) = obj.get_object_base().properties.get(&generator_next_marker) {
                // It's a generator next method - call the generator's .next()
                let gen_obj = match &data.value {
                    JsValue::Object(o) => o.clone(),
                    _ => return Err(JErrorType::TypeError("Invalid generator reference".to_string())),
                };
                drop(func_ref);

                // Call the generator's next method
                let mut gen_borrowed = gen_obj.borrow_mut();

                // We need to cast to GeneratorObject
                match &mut *gen_borrowed {
                    ObjectType::Ordinary(inner_obj) => {
                        let gen_marker = PropertyKey::Str("__generator_object__".to_string());
                        if inner_obj.get_object_base().properties.contains_key(&gen_marker) {
                            // Cast to GeneratorObject
                            let gen_ptr = inner_obj.as_mut() as *mut dyn JsObject as *mut GeneratorObject;
                            drop(gen_borrowed);
                            // SAFETY: We know this is a GeneratorObject
                            unsafe {
                                let gen = &mut *gen_ptr;
                                gen.next(ctx)
                            }
                        } else {
                            Err(JErrorType::TypeError("Not a generator object".to_string()))
                        }
                    }
                    _ => Err(JErrorType::TypeError("Not a generator object".to_string())),
                }
            } else if obj.get_object_base().properties.contains_key(&generator_marker) {
                // It's a generator function - create a GeneratorObject instead of executing
                let obj_ptr = obj.as_ref() as *const dyn JsObject;
                drop(func_ref);

                // SAFETY: We know this is a SimpleFunctionObject and we've dropped func_ref
                unsafe {
                    let simple_func = &*(obj_ptr as *const SimpleFunctionObject);
                    // Create generator object from function data
                    create_generator_object(
                        simple_func.body_ptr,
                        simple_func.params_ptr,
                        simple_func.environment.clone(),
                        args,
                        ctx,
                    )
                }
            } else if obj.get_object_base().properties.contains_key(&marker) {
                // It's a SimpleFunctionObject - use the call_with_this method
                // Get a raw pointer to call call_with_this
                let obj_ptr = obj.as_ref() as *const dyn JsObject;
                drop(func_ref);

                // SAFETY: We know this is a SimpleFunctionObject and we've dropped func_ref
                unsafe {
                    // Cast to SimpleFunctionObject
                    let simple_func = &*(obj_ptr as *const SimpleFunctionObject);
                    simple_func.call_with_this(this_value, args, ctx)
                }
            } else {
                Err(JErrorType::TypeError("Object is not callable".to_string()))
            }
        }
    }
}


/// Get a property from a value, calling getters if necessary.
fn get_property_with_ctx(value: &JsValue, prop_name: &str, ctx: &mut EvalContext) -> ValueResult {
    // Use the receiver version with value as both receiver and lookup target
    get_property_with_receiver(value, value, prop_name, ctx)
}

/// Get a property, with separate receiver (for 'this') and lookup target.
/// This handles prototype chain lookups where 'this' should be the original receiver.
fn get_property_with_receiver(
    receiver: &JsValue,
    lookup_target: &JsValue,
    prop_name: &str,
    ctx: &mut EvalContext,
) -> ValueResult {
    match lookup_target {
        JsValue::Object(obj) => {
            // Check if this is a generator object and we're accessing 'next'
            let is_gen_obj = {
                let obj_ref = obj.borrow();
                let marker = PropertyKey::Str("__generator_object__".to_string());
                obj_ref.as_js_object().get_object_base().properties.contains_key(&marker)
            };

            if is_gen_obj && prop_name == "next" {
                // Return a special "next" method that calls the generator's next
                // We create a wrapper function that holds a reference to the generator
                return create_generator_next_method(obj.clone());
            }

            let prop_key = PropertyKey::Str(prop_name.to_string());

            // Check own property
            let desc = {
                let obj_ref = obj.borrow();
                obj_ref.as_js_object().get_own_property(&prop_key)?.cloned()
            };

            if let Some(desc) = desc {
                match desc {
                    PropertyDescriptor::Data(data) => Ok(data.value.clone()),
                    PropertyDescriptor::Accessor(accessor) => {
                        // Call the getter if it exists, with RECEIVER as 'this'
                        if let Some(getter) = accessor.get {
                            call_accessor_function(&getter, receiver.clone(), vec![], ctx)
                        } else {
                            Ok(JsValue::Undefined)
                        }
                    }
                }
            } else {
                // Check prototype chain - receiver stays the same
                let proto = obj.borrow().as_js_object().get_prototype_of();
                if let Some(proto) = proto {
                    get_property_with_receiver(receiver, &JsValue::Object(proto), prop_name, ctx)
                } else {
                    Ok(JsValue::Undefined)
                }
            }
        }
        JsValue::String(s) => {
            // String primitive property access
            if prop_name == "length" {
                Ok(JsValue::Number(JsNumberType::Integer(s.len() as i64)))
            } else if let Ok(index) = prop_name.parse::<usize>() {
                // Access character at index
                if index < s.len() {
                    Ok(JsValue::String(s.chars().nth(index).unwrap().to_string()))
                } else {
                    Ok(JsValue::Undefined)
                }
            } else {
                // Other string methods not yet supported
                Ok(JsValue::Undefined)
            }
        }
        JsValue::Undefined => {
            Err(JErrorType::TypeError("Cannot read property of undefined".to_string()))
        }
        JsValue::Null => {
            Err(JErrorType::TypeError("Cannot read property of null".to_string()))
        }
        _ => {
            // Primitive types - return undefined for now
            Ok(JsValue::Undefined)
        }
    }
}

/// Call an accessor function (getter or setter).
fn call_accessor_function(
    func: &JsObjectType,
    this_value: JsValue,
    args: Vec<JsValue>,
    ctx: &mut EvalContext,
) -> ValueResult {
    let func_ref = func.borrow();

    // Check if it's our SimpleFunctionObject (stored as Ordinary with marker)
    if let ObjectType::Ordinary(obj) = &*func_ref {
        if is_simple_function_object(obj.as_ref()) {
            // This is a SimpleFunctionObject - we need to call its method
            // Since we can't downcast easily, we use unsafe to access it
            // The object was created by create_function_object so we know it's a SimpleFunctionObject
            let simple_func = unsafe {
                // Get the raw pointer to the inner object and cast it
                let ptr = obj.as_ref() as *const dyn JsObject as *const SimpleFunctionObject;
                &*ptr
            };
            drop(func_ref);
            return simple_func.call_with_this(this_value, args, ctx);
        }

        // Regular object - try to call as function (likely will fail)
        drop(func_ref);
        call_function_object(func, this_value, args, ctx)
    } else if let ObjectType::Function(func_obj) = &*func_ref {
        // It's a full function object
        let body = func_obj.get_function_object_base().body_code.clone();
        let params = func_obj.get_function_object_base().formal_parameters.clone();
        let func_env = func_obj.get_function_object_base().environment.clone();

        drop(func_ref);

        call_function_with_body(body, params, func_env, this_value, args, ctx)
    } else {
        Err(JErrorType::TypeError("Not a function".to_string()))
    }
}

/// Call a function given its body, parameters, and environment.
fn call_function_with_body(
    body: Rc<crate::parser::ast::FunctionBodyData>,
    params: Rc<Vec<PatternType>>,
    func_env: crate::runner::ds::lex_env::JsLexEnvironmentType,
    this_value: JsValue,
    args: Vec<JsValue>,
    ctx: &mut EvalContext,
) -> ValueResult {
    use crate::runner::ds::env_record::new_declarative_environment;
    use super::statement::execute_statement;
    use super::types::CompletionType;

    // Save current environment
    let saved_lex_env = ctx.lex_env.clone();
    let saved_var_env = ctx.var_env.clone();
    let saved_this = ctx.global_this.clone();

    // Create new environment for the function, with the function's closure as outer
    let func_scope = new_declarative_environment(Some(func_env));
    ctx.lex_env = func_scope.clone();
    ctx.var_env = func_scope;
    ctx.global_this = Some(this_value);

    // Bind parameters to arguments
    for (i, param) in params.iter().enumerate() {
        if let PatternType::PatternWhichCanBeExpression(
            ExpressionPatternType::Identifier(id)
        ) = param {
            let arg_value = args.get(i).cloned().unwrap_or(JsValue::Undefined);
            ctx.create_binding(&id.name, false)?;
            ctx.initialize_binding(&id.name, arg_value)?;
        }
    }

    // Execute each statement in the function body
    let mut result_completion = super::types::Completion::normal();

    for stmt in body.body.iter() {
        let completion = execute_statement(stmt, ctx)?;

        match completion.completion_type {
            CompletionType::Return => {
                result_completion = completion;
                break;
            }
            CompletionType::Throw => {
                // Restore environment before returning error
                ctx.lex_env = saved_lex_env;
                ctx.var_env = saved_var_env;
                ctx.global_this = saved_this;
                return Err(JErrorType::TypeError(format!(
                    "Uncaught exception: {:?}",
                    completion.value
                )));
            }
            CompletionType::Break | CompletionType::Continue | CompletionType::Yield => {
                result_completion = completion;
                break;
            }
            CompletionType::Normal => {
                result_completion = completion;
            }
        }
    }

    // Restore the previous environment
    ctx.lex_env = saved_lex_env;
    ctx.var_env = saved_var_env;
    ctx.global_this = saved_this;

    // Return the result
    match result_completion.completion_type {
        CompletionType::Return => Ok(result_completion.get_value()),
        _ => Ok(JsValue::Undefined),
    }
}

/// Convert a value to a property key string.
fn to_property_key(value: &JsValue) -> String {
    to_string(value)
}

/// Evaluate an assignment expression.
fn evaluate_assignment_expression(
    operator: &AssignmentOperator,
    left: &PatternOrExpression,
    right: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    // Check if this is a member expression assignment
    if let PatternOrExpression::Expression(expr) = left {
        if let ExpressionType::MemberExpression(member) = expr.as_ref() {
            return evaluate_member_assignment(operator, member, right, ctx);
        }
    }

    // Handle destructuring assignment patterns
    if let PatternOrExpression::Pattern(pattern) = left {
        if !matches!(
            &**pattern,
            PatternType::PatternWhichCanBeExpression(ExpressionPatternType::Identifier(_))
        ) {
            if !matches!(operator, AssignmentOperator::Equals) {
                return Err(JErrorType::TypeError(
                    "Compound assignment not supported for destructuring patterns".to_string(),
                ));
            }
            let rhs_value = evaluate_expression(right, ctx)?;
            assign_pattern(pattern, rhs_value.clone(), ctx)?;
            return Ok(rhs_value);
        }
    }

    // Get the name to assign to (simple variable assignment)
    let name = match left {
        PatternOrExpression::Pattern(pattern) => get_pattern_name(pattern)?,
        PatternOrExpression::Expression(expr) => get_expression_name(expr)?,
    };

    // Evaluate the right-hand side
    let rhs_value = evaluate_expression(right, ctx)?;

    // Compute the final value based on the operator
    let final_value = match operator {
        AssignmentOperator::Equals => rhs_value,
        AssignmentOperator::AddEquals => {
            let current = ctx.get_binding(&name)?;
            add_values(&current, &rhs_value)?
        }
        AssignmentOperator::SubtractEquals => {
            let current = ctx.get_binding(&name)?;
            subtract_values(&current, &rhs_value)?
        }
        AssignmentOperator::MultiplyEquals => {
            let current = ctx.get_binding(&name)?;
            multiply_values(&current, &rhs_value)?
        }
        AssignmentOperator::DivideEquals => {
            let current = ctx.get_binding(&name)?;
            divide_values(&current, &rhs_value)?
        }
        AssignmentOperator::ModuloEquals => {
            let current = ctx.get_binding(&name)?;
            modulo_values(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseLeftShiftEquals => {
            let current = ctx.get_binding(&name)?;
            left_shift(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseRightShiftEquals => {
            let current = ctx.get_binding(&name)?;
            right_shift(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseUnsignedRightShiftEquals => {
            let current = ctx.get_binding(&name)?;
            unsigned_right_shift(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseOrEquals => {
            let current = ctx.get_binding(&name)?;
            bitwise_or(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseAndEquals => {
            let current = ctx.get_binding(&name)?;
            bitwise_and(&current, &rhs_value)?
        }
        AssignmentOperator::BitwiseXorEquals => {
            let current = ctx.get_binding(&name)?;
            bitwise_xor(&current, &rhs_value)?
        }
    };

    // Set the binding and return the value
    ctx.set_binding(&name, final_value.clone())?;
    Ok(final_value)
}

/// Assign a value to a binding pattern (destructuring assignment).
fn assign_pattern(
    pattern: &PatternType,
    value: JsValue,
    ctx: &mut EvalContext,
) -> Result<(), JErrorType> {
    match pattern {
        PatternType::PatternWhichCanBeExpression(ExpressionPatternType::Identifier(id)) => {
            ctx.set_binding(&id.name, value)?;
            Ok(())
        }
        PatternType::ObjectPattern { properties, .. } => {
            for prop in properties {
                let prop_data = &prop.0;
                let key_name = get_assignment_property_key(prop_data, ctx)?;
                let prop_value = get_object_property_value(&value, &key_name, ctx)?;
                assign_pattern(&prop_data.value, prop_value, ctx)?;
            }
            Ok(())
        }
        PatternType::ArrayPattern { elements, .. } => {
            for (index, element) in elements.iter().enumerate() {
                if let Some(elem_pattern) = element {
                    if let PatternType::RestElement { argument, .. } = elem_pattern.as_ref() {
                        let rest_value = get_rest_elements_for_assignment(&value, index, ctx)?;
                        assign_pattern(argument, rest_value, ctx)?;
                    } else {
                        let elem_value = get_array_element_for_assignment(&value, index, ctx)?;
                        assign_pattern(elem_pattern, elem_value, ctx)?;
                    }
                }
            }
            Ok(())
        }
        PatternType::AssignmentPattern { left, right, .. } => {
            let actual_value = if matches!(value, JsValue::Undefined) {
                evaluate_expression(right, ctx)?
            } else {
                value
            };
            assign_pattern(left, actual_value, ctx)
        }
        PatternType::RestElement { argument, .. } => assign_pattern(argument, value, ctx),
    }
}

fn get_assignment_property_key(
    prop: &PropertyData<Box<PatternType>>,
    ctx: &mut EvalContext,
) -> Result<String, JErrorType> {
    if prop.computed {
        let key_value = evaluate_expression(prop.key.as_ref(), ctx)?;
        Ok(to_string(&key_value))
    } else {
        match prop.key.as_ref() {
            ExpressionType::ExpressionWhichCanBePattern(ExpressionPatternType::Identifier(id)) => {
                Ok(id.name.clone())
            }
            ExpressionType::Literal(lit_data) => match &lit_data.value {
                LiteralType::StringLiteral(s) => Ok(s.clone()),
                LiteralType::NumberLiteral(num) => {
                    use crate::parser::ast::NumberLiteralType;
                    match num {
                        NumberLiteralType::IntegerLiteral(n) => Ok(n.to_string()),
                        NumberLiteralType::FloatLiteral(n) => Ok(n.to_string()),
                    }
                }
                _ => Err(JErrorType::TypeError(
                    "Invalid property key in destructuring assignment".to_string(),
                )),
            },
            _ => Err(JErrorType::TypeError(
                "Invalid property key in destructuring assignment".to_string(),
            )),
        }
    }
}

fn get_object_property_value(
    obj: &JsValue,
    key: &str,
    ctx: &mut EvalContext,
) -> Result<JsValue, JErrorType> {
    match obj {
        JsValue::Object(_) => get_property_with_ctx(obj, key, ctx),
        _ => Err(JErrorType::TypeError(
            "Cannot destructure non-object".to_string(),
        )),
    }
}

fn get_array_element_for_assignment(
    arr: &JsValue,
    index: usize,
    ctx: &mut EvalContext,
) -> Result<JsValue, JErrorType> {
    match arr {
        JsValue::Object(_) => {
            let key = index.to_string();
            get_property_with_ctx(arr, &key, ctx)
        }
        _ => Err(JErrorType::TypeError(
            "Cannot destructure non-array".to_string(),
        )),
    }
}

fn get_rest_elements_for_assignment(
    arr: &JsValue,
    start_index: usize,
    ctx: &mut EvalContext,
) -> Result<JsValue, JErrorType> {
    use crate::runner::ds::object::{JsObject, JsObjectType, ObjectType};
    use crate::runner::ds::object_property::{PropertyDescriptor, PropertyDescriptorData, PropertyKey};
    use std::cell::RefCell;
    use std::rc::Rc;

    let length = match arr {
        JsValue::Object(_) => {
            let length_value = get_property_with_ctx(arr, "length", ctx)?;
            match length_value {
                JsValue::Number(JsNumberType::Integer(n)) => n.max(0) as usize,
                JsValue::Number(JsNumberType::Float(n)) => {
                    if n.is_nan() || n < 0.0 {
                        0
                    } else {
                        n as usize
                    }
                }
                _ => 0,
            }
        }
        _ => {
            return Err(JErrorType::TypeError(
                "Cannot use rest with non-array".to_string(),
            ))
        }
    };

    let mut rest_obj = ctx.new_tracked_object()?;
    let mut rest_index = 0;

    for i in start_index..length {
        let key = i.to_string();
        let value = get_property_with_ctx(arr, &key, ctx)?;
        rest_obj.get_object_base_mut().properties.insert(
            PropertyKey::Str(rest_index.to_string()),
            PropertyDescriptor::Data(PropertyDescriptorData {
                value,
                writable: true,
                enumerable: true,
                configurable: true,
            }),
        );
        rest_index += 1;
    }

    rest_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("length".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Number(JsNumberType::Integer(rest_index as i64)),
            writable: true,
            enumerable: false,
            configurable: false,
        }),
    );

    let obj: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(rest_obj))));
    Ok(JsValue::Object(obj))
}

/// Evaluate assignment to a member expression (obj.prop = value or obj[prop] = value).
fn evaluate_member_assignment(
    operator: &AssignmentOperator,
    member: &MemberExpressionType,
    right: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    // Get the object and property key
    let (obj_value, prop_name) = match member {
        MemberExpressionType::SimpleMemberExpression { object, property, .. } => {
            let obj = evaluate_expression_or_super(object, ctx)?;
            (obj, property.name.clone())
        }
        MemberExpressionType::ComputedMemberExpression { object, property, .. } => {
            let obj = evaluate_expression_or_super(object, ctx)?;
            let prop_val = evaluate_expression(property.as_ref(), ctx)?;
            (obj, to_property_key(&prop_val))
        }
    };

    // Evaluate the right-hand side
    let rhs_value = evaluate_expression(right, ctx)?;

    // Compute the final value based on the operator
    let final_value = if matches!(operator, AssignmentOperator::Equals) {
        rhs_value
    } else {
        let current = get_property_with_ctx(&obj_value, &prop_name, ctx)?;
        match operator {
            AssignmentOperator::Equals => unreachable!(),
            AssignmentOperator::AddEquals => add_values(&current, &rhs_value)?,
            AssignmentOperator::SubtractEquals => subtract_values(&current, &rhs_value)?,
            AssignmentOperator::MultiplyEquals => multiply_values(&current, &rhs_value)?,
            AssignmentOperator::DivideEquals => divide_values(&current, &rhs_value)?,
            AssignmentOperator::ModuloEquals => modulo_values(&current, &rhs_value)?,
            AssignmentOperator::BitwiseLeftShiftEquals => left_shift(&current, &rhs_value)?,
            AssignmentOperator::BitwiseRightShiftEquals => right_shift(&current, &rhs_value)?,
            AssignmentOperator::BitwiseUnsignedRightShiftEquals => unsigned_right_shift(&current, &rhs_value)?,
            AssignmentOperator::BitwiseOrEquals => bitwise_or(&current, &rhs_value)?,
            AssignmentOperator::BitwiseAndEquals => bitwise_and(&current, &rhs_value)?,
            AssignmentOperator::BitwiseXorEquals => bitwise_xor(&current, &rhs_value)?,
        }
    };

    // Set the property (with setter support)
    set_property_with_ctx(&obj_value, &prop_name, final_value.clone(), ctx)?;
    Ok(final_value)
}

/// Set a property on an object, calling setters if necessary.
fn set_property_with_ctx(
    value: &JsValue,
    prop_name: &str,
    new_value: JsValue,
    ctx: &mut EvalContext,
) -> Result<(), JErrorType> {
    match value {
        JsValue::Object(obj) => {
            let prop_key = PropertyKey::Str(prop_name.to_string());

            // Check for accessor property (setter)
            let desc = {
                let obj_ref = obj.borrow();
                obj_ref.as_js_object().get_own_property(&prop_key)?.cloned()
            };

            if let Some(PropertyDescriptor::Accessor(accessor)) = desc {
                // Call the setter if it exists
                if let Some(setter) = accessor.set {
                    call_accessor_function(&setter, value.clone(), vec![new_value], ctx)?;
                    return Ok(());
                }
                // No setter - fall through to data property behavior
            }

            // Set as data property
            let mut obj_mut = obj.borrow_mut();
            obj_mut.as_js_object_mut().get_object_base_mut().properties.insert(
                prop_key,
                PropertyDescriptor::Data(PropertyDescriptorData {
                    value: new_value,
                    writable: true,
                    enumerable: true,
                    configurable: true,
                }),
            );
            Ok(())
        }
        _ => Err(JErrorType::TypeError("Cannot set property on non-object".to_string())),
    }
}

/// Get the name from a pattern (for simple identifier patterns).
fn get_pattern_name(pattern: &PatternType) -> Result<String, JErrorType> {
    match pattern {
        PatternType::PatternWhichCanBeExpression(ExpressionPatternType::Identifier(id)) => {
            Ok(id.name.clone())
        }
        _ => Err(JErrorType::TypeError(
            "Complex patterns in assignment not yet supported".to_string(),
        )),
    }
}

/// Get the name from an expression (for simple identifier expressions).
fn get_expression_name(expr: &ExpressionType) -> Result<String, JErrorType> {
    match expr {
        ExpressionType::ExpressionWhichCanBePattern(ExpressionPatternType::Identifier(id)) => {
            Ok(id.name.clone())
        }
        _ => Err(JErrorType::TypeError(
            "Assignment to non-identifier expressions not yet supported".to_string(),
        )),
    }
}

/// Evaluate a unary expression.
fn evaluate_unary_expression(
    operator: &UnaryOperator,
    argument: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    match operator {
        UnaryOperator::TypeOf => {
            let value = evaluate_expression(argument, ctx).unwrap_or(JsValue::Undefined);
            Ok(JsValue::String(get_typeof_string(&value)))
        }
        UnaryOperator::Void => {
            let _ = evaluate_expression(argument, ctx)?;
            Ok(JsValue::Undefined)
        }
        UnaryOperator::LogicalNot => {
            let value = evaluate_expression(argument, ctx)?;
            Ok(JsValue::Boolean(!to_boolean(&value)))
        }
        UnaryOperator::Minus => {
            let value = evaluate_expression(argument, ctx)?;
            negate_number(&value)
        }
        UnaryOperator::Plus => {
            let value = evaluate_expression(argument, ctx)?;
            to_number(&value)
        }
        UnaryOperator::BitwiseNot => {
            let value = evaluate_expression(argument, ctx)?;
            bitwise_not(&value)
        }
        UnaryOperator::Delete => {
            match argument {
                ExpressionType::MemberExpression(member) => {
                    match member {
                        MemberExpressionType::SimpleMemberExpression { object, property, .. } => {
                            let obj_value = evaluate_expression_or_super(object, ctx)?;
                            match obj_value {
                                JsValue::Object(obj) => {
                                    let prop_key = PropertyKey::Str(property.name.clone());
                                    let result = obj.borrow_mut().as_js_object_mut().delete(&prop_key)?;
                                    Ok(JsValue::Boolean(result))
                                }
                                _ => Ok(JsValue::Boolean(true))
                            }
                        }
                        MemberExpressionType::ComputedMemberExpression { object, property, .. } => {
                            let obj_value = evaluate_expression_or_super(object, ctx)?;
                            let prop_value = evaluate_expression(property.as_ref(), ctx)?;
                            let prop_name = to_property_key(&prop_value);
                            match obj_value {
                                JsValue::Object(obj) => {
                                    let prop_key = PropertyKey::Str(prop_name);
                                    let result = obj.borrow_mut().as_js_object_mut().delete(&prop_key)?;
                                    Ok(JsValue::Boolean(result))
                                }
                                _ => Ok(JsValue::Boolean(true))
                            }
                        }
                    }
                }
                _ => {
                    // Non-member: evaluate for side effects, return true
                    let _ = evaluate_expression(argument, ctx)?;
                    Ok(JsValue::Boolean(true))
                }
            }
        }
    }
}

/// Evaluate a binary expression.
fn evaluate_binary_expression(
    operator: &BinaryOperator,
    left: &ExpressionType,
    right: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    let left_val = evaluate_expression(left, ctx)?;
    let right_val = evaluate_expression(right, ctx)?;

    match operator {
        // Arithmetic
        BinaryOperator::Add => add_values(&left_val, &right_val),
        BinaryOperator::Subtract => subtract_values(&left_val, &right_val),
        BinaryOperator::Multiply => multiply_values(&left_val, &right_val),
        BinaryOperator::Divide => divide_values(&left_val, &right_val),
        BinaryOperator::Modulo => modulo_values(&left_val, &right_val),

        // Comparison
        BinaryOperator::LessThan => compare_values(&left_val, &right_val, |a, b| a < b),
        BinaryOperator::GreaterThan => compare_values(&left_val, &right_val, |a, b| a > b),
        BinaryOperator::LessThanEqual => compare_values(&left_val, &right_val, |a, b| a <= b),
        BinaryOperator::GreaterThanEqual => compare_values(&left_val, &right_val, |a, b| a >= b),

        // Equality
        BinaryOperator::StrictlyEqual => Ok(JsValue::Boolean(strict_equality(&left_val, &right_val))),
        BinaryOperator::StrictlyUnequal => Ok(JsValue::Boolean(!strict_equality(&left_val, &right_val))),
        BinaryOperator::LooselyEqual => Ok(JsValue::Boolean(loose_equality(&left_val, &right_val))),
        BinaryOperator::LooselyUnequal => Ok(JsValue::Boolean(!loose_equality(&left_val, &right_val))),

        // Bitwise
        BinaryOperator::BitwiseAnd => bitwise_and(&left_val, &right_val),
        BinaryOperator::BitwiseOr => bitwise_or(&left_val, &right_val),
        BinaryOperator::BitwiseXor => bitwise_xor(&left_val, &right_val),
        BinaryOperator::BitwiseLeftShift => left_shift(&left_val, &right_val),
        BinaryOperator::BitwiseRightShift => right_shift(&left_val, &right_val),
        BinaryOperator::BitwiseUnsignedRightShift => unsigned_right_shift(&left_val, &right_val),

        // Other
        BinaryOperator::InstanceOf => {
            // Left must be an object for instanceof to potentially return true
            let left_obj = match &left_val {
                JsValue::Object(obj) => obj.clone(),
                _ => return Ok(JsValue::Boolean(false)),
            };

            // Right must be an object (constructor function) with a prototype property
            let right_obj = match &right_val {
                JsValue::Object(obj) => obj.clone(),
                _ => return Err(JErrorType::TypeError("Right-hand side of 'instanceof' is not an object".to_string())),
            };

            // Get the prototype property from the right-hand side (constructor.prototype)
            let proto_key = PropertyKey::Str("prototype".to_string());
            let right_prototype = {
                let right_borrowed = right_obj.borrow();
                if let Some(desc) = right_borrowed.as_js_object().get_own_property(&proto_key)? {
                    match desc {
                        PropertyDescriptor::Data(data) => {
                            match &data.value {
                                JsValue::Object(p) => Some(p.clone()),
                                _ => None,
                            }
                        }
                        _ => None,
                    }
                } else {
                    None
                }
            };

            // If right.prototype is not an object, return false
            let target_proto = match right_prototype {
                Some(p) => p,
                None => return Ok(JsValue::Boolean(false)),
            };

            // Walk the prototype chain of left
            let mut current_proto = left_obj.borrow().as_js_object().get_prototype_of();

            while let Some(proto) = current_proto {
                // Compare by reference
                if Rc::ptr_eq(&proto, &target_proto) {
                    return Ok(JsValue::Boolean(true));
                }
                current_proto = proto.borrow().as_js_object().get_prototype_of();
            }

            Ok(JsValue::Boolean(false))
        }
        BinaryOperator::In => {
            let prop_key = PropertyKey::Str(to_property_key(&left_val));
            match &right_val {
                JsValue::Object(obj) => {
                    let has = obj.borrow().as_js_object().has_property(&prop_key);
                    Ok(JsValue::Boolean(has))
                }
                _ => Err(JErrorType::TypeError("Cannot use 'in' operator with non-object".to_string()))
            }
        }
    }
}

/// Evaluate a logical expression with short-circuit evaluation.
fn evaluate_logical_expression(
    operator: &LogicalOperator,
    left: &ExpressionType,
    right: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    let left_val = evaluate_expression(left, ctx)?;

    match operator {
        LogicalOperator::And => {
            if !to_boolean(&left_val) {
                Ok(left_val)
            } else {
                evaluate_expression(right, ctx)
            }
        }
        LogicalOperator::Or => {
            if to_boolean(&left_val) {
                Ok(left_val)
            } else {
                evaluate_expression(right, ctx)
            }
        }
    }
}

/// Evaluate a conditional (ternary) expression.
fn evaluate_conditional_expression(
    test: &ExpressionType,
    consequent: &ExpressionType,
    alternate: &ExpressionType,
    ctx: &mut EvalContext,
) -> ValueResult {
    let test_val = evaluate_expression(test, ctx)?;

    if to_boolean(&test_val) {
        evaluate_expression(consequent, ctx)
    } else {
        evaluate_expression(alternate, ctx)
    }
}

/// Evaluate a sequence expression.
fn evaluate_sequence_expression(
    expressions: &[Box<ExpressionType>],
    ctx: &mut EvalContext,
) -> ValueResult {
    let mut result = JsValue::Undefined;
    for expr in expressions {
        result = evaluate_expression(expr.as_ref(), ctx)?;
    }
    Ok(result)
}

/// Evaluate an update expression (++x, x++, --x, x--).
fn evaluate_update_expression(
    operator: &UpdateOperator,
    argument: &ExpressionType,
    prefix: bool,
    ctx: &mut EvalContext,
) -> ValueResult {
    // Get the variable name from the argument
    let name = get_expression_name(argument)?;

    // Get the current value
    let current_value = ctx.get_binding(&name)?;

    // Convert to number
    let old_number = to_number(&current_value)?;
    let old_f64 = match &old_number {
        JsValue::Number(n) => number_to_f64(n),
        _ => f64::NAN,
    };

    // Compute the new value based on operator
    let new_f64 = match operator {
        UpdateOperator::PlusPlus => old_f64 + 1.0,
        UpdateOperator::MinusMinus => old_f64 - 1.0,
    };

    // Create the new JsValue
    let new_value = if new_f64.fract() == 0.0 && new_f64.abs() < i64::MAX as f64 {
        JsValue::Number(JsNumberType::Integer(new_f64 as i64))
    } else {
        JsValue::Number(JsNumberType::Float(new_f64))
    };

    // Store the new value
    ctx.set_binding(&name, new_value.clone())?;

    // Return old value for postfix, new value for prefix
    if prefix {
        Ok(new_value)
    } else {
        Ok(old_number)
    }
}

// ============================================================================
// Type conversion helpers
// ============================================================================

/// Convert a value to boolean.
pub fn to_boolean(value: &JsValue) -> bool {
    match value {
        JsValue::Undefined => false,
        JsValue::Null => false,
        JsValue::Boolean(b) => *b,
        JsValue::Number(n) => match n {
            JsNumberType::Integer(0) => false,
            JsNumberType::Float(f) if *f == 0.0 || f.is_nan() => false,
            JsNumberType::NaN => false,
            _ => true,
        },
        JsValue::String(s) => !s.is_empty(),
        JsValue::Symbol(_) => true,
        JsValue::Object(_) => true,
    }
}

/// Get the typeof string for a value.
fn get_typeof_string(value: &JsValue) -> String {
    match value {
        JsValue::Undefined => "undefined".to_string(),
        JsValue::Null => "object".to_string(),
        JsValue::Boolean(_) => "boolean".to_string(),
        JsValue::Number(_) => "number".to_string(),
        JsValue::String(_) => "string".to_string(),
        JsValue::Symbol(_) => "symbol".to_string(),
        JsValue::Object(_) => "object".to_string(),
    }
}

/// Convert a value to a number.
fn to_number(value: &JsValue) -> ValueResult {
    Ok(match value {
        JsValue::Undefined => JsValue::Number(JsNumberType::NaN),
        JsValue::Null => JsValue::Number(JsNumberType::Integer(0)),
        JsValue::Boolean(true) => JsValue::Number(JsNumberType::Integer(1)),
        JsValue::Boolean(false) => JsValue::Number(JsNumberType::Integer(0)),
        JsValue::Number(n) => JsValue::Number(n.clone()),
        JsValue::String(s) => {
            if s.is_empty() {
                JsValue::Number(JsNumberType::Integer(0))
            } else if let Ok(i) = s.trim().parse::<i64>() {
                JsValue::Number(JsNumberType::Integer(i))
            } else if let Ok(f) = s.trim().parse::<f64>() {
                JsValue::Number(JsNumberType::Float(f))
            } else {
                JsValue::Number(JsNumberType::NaN)
            }
        }
        JsValue::Symbol(_) => {
            return Err(JErrorType::TypeError("Cannot convert Symbol to number".to_string()));
        }
        JsValue::Object(_) => JsValue::Number(JsNumberType::NaN),
    })
}

/// Negate a number value.
fn negate_number(value: &JsValue) -> ValueResult {
    let num_value = to_number(value)?;
    Ok(match num_value {
        JsValue::Number(JsNumberType::Integer(i)) => JsValue::Number(JsNumberType::Integer(-i)),
        JsValue::Number(JsNumberType::Float(f)) => JsValue::Number(JsNumberType::Float(-f)),
        JsValue::Number(JsNumberType::PositiveInfinity) => JsValue::Number(JsNumberType::NegativeInfinity),
        JsValue::Number(JsNumberType::NegativeInfinity) => JsValue::Number(JsNumberType::PositiveInfinity),
        JsValue::Number(JsNumberType::NaN) => JsValue::Number(JsNumberType::NaN),
        _ => JsValue::Number(JsNumberType::NaN),
    })
}

/// Bitwise NOT operation.
fn bitwise_not(value: &JsValue) -> ValueResult {
    let num = to_i32(value)?;
    Ok(JsValue::Number(JsNumberType::Integer(!num as i64)))
}

/// Convert to i32 for bitwise operations.
fn to_i32(value: &JsValue) -> Result<i32, JErrorType> {
    match to_number(value)? {
        JsValue::Number(JsNumberType::Integer(i)) => Ok(i as i32),
        JsValue::Number(JsNumberType::Float(f)) => Ok(f as i32),
        JsValue::Number(JsNumberType::NaN) => Ok(0),
        JsValue::Number(JsNumberType::PositiveInfinity) => Ok(0),
        JsValue::Number(JsNumberType::NegativeInfinity) => Ok(0),
        _ => Ok(0),
    }
}

/// Convert to u32 for unsigned bitwise operations.
fn to_u32(value: &JsValue) -> Result<u32, JErrorType> {
    Ok(to_i32(value)? as u32)
}

// ============================================================================
// Arithmetic operations
// ============================================================================

fn add_values(left: &JsValue, right: &JsValue) -> ValueResult {
    if matches!(left, JsValue::String(_)) || matches!(right, JsValue::String(_)) {
        let left_str = to_string(left);
        let right_str = to_string(right);
        return Ok(JsValue::String(format!("{}{}", left_str, right_str)));
    }

    let left_num = to_number(left)?;
    let right_num = to_number(right)?;
    apply_numeric_op(&left_num, &right_num, |a, b| a + b, |a, b| a + b)
}

fn subtract_values(left: &JsValue, right: &JsValue) -> ValueResult {
    let left_num = to_number(left)?;
    let right_num = to_number(right)?;
    apply_numeric_op(&left_num, &right_num, |a, b| a - b, |a, b| a - b)
}

fn multiply_values(left: &JsValue, right: &JsValue) -> ValueResult {
    let left_num = to_number(left)?;
    let right_num = to_number(right)?;
    apply_numeric_op(&left_num, &right_num, |a, b| a * b, |a, b| a * b)
}

fn divide_values(left: &JsValue, right: &JsValue) -> ValueResult {
    let left_num = to_number(left)?;
    let right_num = to_number(right)?;

    if matches!(right_num, JsValue::Number(JsNumberType::Integer(0)))
        || matches!(right_num, JsValue::Number(JsNumberType::Float(f)) if f == 0.0)
    {
        let left_f = match &left_num {
            JsValue::Number(n) => number_to_f64(n),
            _ => f64::NAN,
        };
        return Ok(if left_f.is_nan() || left_f == 0.0 {
            JsValue::Number(JsNumberType::NaN)
        } else if left_f > 0.0 {
            JsValue::Number(JsNumberType::PositiveInfinity)
        } else {
            JsValue::Number(JsNumberType::NegativeInfinity)
        });
    }

    apply_numeric_op(&left_num, &right_num, |a, b| a / b, |a, b| a / b)
}

fn modulo_values(left: &JsValue, right: &JsValue) -> ValueResult {
    let left_num = to_number(left)?;
    let right_num = to_number(right)?;
    apply_numeric_op(&left_num, &right_num, |a, b| a % b, |a, b| a % b)
}

fn apply_numeric_op<F, G>(left: &JsValue, right: &JsValue, int_op: F, float_op: G) -> ValueResult
where
    F: Fn(i64, i64) -> i64,
    G: Fn(f64, f64) -> f64,
{
    match (left, right) {
        (JsValue::Number(JsNumberType::NaN), _) | (_, JsValue::Number(JsNumberType::NaN)) => {
            Ok(JsValue::Number(JsNumberType::NaN))
        }
        (JsValue::Number(JsNumberType::Integer(a)), JsValue::Number(JsNumberType::Integer(b))) => {
            Ok(JsValue::Number(JsNumberType::Integer(int_op(*a, *b))))
        }
        (JsValue::Number(a), JsValue::Number(b)) => {
            let a_f64 = number_to_f64(a);
            let b_f64 = number_to_f64(b);
            Ok(JsValue::Number(JsNumberType::Float(float_op(a_f64, b_f64))))
        }
        _ => Ok(JsValue::Number(JsNumberType::NaN)),
    }
}

fn number_to_f64(n: &JsNumberType) -> f64 {
    match n {
        JsNumberType::Integer(i) => *i as f64,
        JsNumberType::Float(f) => *f,
        JsNumberType::NaN => f64::NAN,
        JsNumberType::PositiveInfinity => f64::INFINITY,
        JsNumberType::NegativeInfinity => f64::NEG_INFINITY,
    }
}

// ============================================================================
// Comparison operations
// ============================================================================

fn compare_values<F>(left: &JsValue, right: &JsValue, cmp: F) -> ValueResult
where
    F: Fn(f64, f64) -> bool,
{
    let left_num = to_number(left)?;
    let right_num = to_number(right)?;

    let result = match (&left_num, &right_num) {
        (JsValue::Number(JsNumberType::NaN), _) | (_, JsValue::Number(JsNumberType::NaN)) => false,
        (JsValue::Number(a), JsValue::Number(b)) => {
            cmp(number_to_f64(a), number_to_f64(b))
        }
        _ => false,
    };

    Ok(JsValue::Boolean(result))
}

pub fn strict_equality(left: &JsValue, right: &JsValue) -> bool {
    match (left, right) {
        (JsValue::Undefined, JsValue::Undefined) => true,
        (JsValue::Null, JsValue::Null) => true,
        (JsValue::Boolean(a), JsValue::Boolean(b)) => a == b,
        (JsValue::String(a), JsValue::String(b)) => a == b,
        (JsValue::Number(JsNumberType::NaN), _) | (_, JsValue::Number(JsNumberType::NaN)) => false,
        (JsValue::Number(a), JsValue::Number(b)) => {
            number_to_f64(a) == number_to_f64(b)
        }
        (JsValue::Object(a), JsValue::Object(b)) => std::rc::Rc::ptr_eq(a, b),
        _ => false,
    }
}

fn loose_equality(left: &JsValue, right: &JsValue) -> bool {
    if std::mem::discriminant(left) == std::mem::discriminant(right) {
        return strict_equality(left, right);
    }

    match (left, right) {
        (JsValue::Null, JsValue::Undefined) | (JsValue::Undefined, JsValue::Null) => true,
        (JsValue::Number(_), JsValue::String(_)) => {
            if let Ok(r) = to_number(right) {
                strict_equality(left, &r)
            } else {
                false
            }
        }
        (JsValue::String(_), JsValue::Number(_)) => {
            if let Ok(l) = to_number(left) {
                strict_equality(&l, right)
            } else {
                false
            }
        }
        (JsValue::Boolean(_), _) => {
            if let Ok(l) = to_number(left) {
                loose_equality(&l, right)
            } else {
                false
            }
        }
        (_, JsValue::Boolean(_)) => {
            if let Ok(r) = to_number(right) {
                loose_equality(left, &r)
            } else {
                false
            }
        }
        _ => false,
    }
}

// ============================================================================
// Bitwise operations
// ============================================================================

fn bitwise_and(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_i32(left)?;
    let r = to_i32(right)?;
    Ok(JsValue::Number(JsNumberType::Integer((l & r) as i64)))
}

fn bitwise_or(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_i32(left)?;
    let r = to_i32(right)?;
    Ok(JsValue::Number(JsNumberType::Integer((l | r) as i64)))
}

fn bitwise_xor(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_i32(left)?;
    let r = to_i32(right)?;
    Ok(JsValue::Number(JsNumberType::Integer((l ^ r) as i64)))
}

fn left_shift(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_i32(left)?;
    let r = to_u32(right)? & 0x1f;
    Ok(JsValue::Number(JsNumberType::Integer((l << r) as i64)))
}

fn right_shift(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_i32(left)?;
    let r = to_u32(right)? & 0x1f;
    Ok(JsValue::Number(JsNumberType::Integer((l >> r) as i64)))
}

fn unsigned_right_shift(left: &JsValue, right: &JsValue) -> ValueResult {
    let l = to_u32(left)?;
    let r = to_u32(right)? & 0x1f;
    Ok(JsValue::Number(JsNumberType::Integer((l >> r) as i64)))
}

// ============================================================================
// String conversion
// ============================================================================

fn to_string(value: &JsValue) -> String {
    match value {
        JsValue::Undefined => "undefined".to_string(),
        JsValue::Null => "null".to_string(),
        JsValue::Boolean(true) => "true".to_string(),
        JsValue::Boolean(false) => "false".to_string(),
        JsValue::Number(n) => n.to_string(),
        JsValue::String(s) => s.clone(),
        JsValue::Symbol(_) => "[Symbol]".to_string(),
        JsValue::Object(_) => "[object Object]".to_string(),
    }
}

// ============================================================================
// Function object creation
// ============================================================================

/// Simple function object that stores function metadata for evaluation.
/// Instead of storing AST data directly, we store references to the source AST.
pub struct SimpleFunctionObject {
    base: ObjectBase,
    /// Pointer to the function body (using raw pointer for simplicity)
    body_ptr: *const crate::parser::ast::FunctionBodyData,
    /// Pointer to the formal parameters
    params_ptr: *const Vec<PatternType>,
    /// The lexical environment at the time the function was created
    environment: crate::runner::ds::lex_env::JsLexEnvironmentType,
}

// Safety: SimpleFunctionObject is only used within a single thread
unsafe impl Send for SimpleFunctionObject {}
unsafe impl Sync for SimpleFunctionObject {}

impl SimpleFunctionObject {
    pub fn new(
        body_ptr: *const crate::parser::ast::FunctionBodyData,
        params_ptr: *const Vec<PatternType>,
        environment: crate::runner::ds::lex_env::JsLexEnvironmentType,
    ) -> Self {
        SimpleFunctionObject {
            base: ObjectBase::new(),
            body_ptr,
            params_ptr,
            environment,
        }
    }

    /// Call this function with the given this value and arguments.
    /// Safety: The AST pointers must still be valid.
    pub fn call_with_this(
        &self,
        this_value: JsValue,
        args: Vec<JsValue>,
        ctx: &mut EvalContext,
    ) -> ValueResult {
        use crate::runner::ds::env_record::new_declarative_environment;
        use super::statement::execute_statement;
        use super::types::CompletionType;

        // Get the body and params (unsafe dereference)
        let (body, params) = unsafe {
            (&*self.body_ptr, &*self.params_ptr)
        };

        // Save current environment
        let saved_lex_env = ctx.lex_env.clone();
        let saved_var_env = ctx.var_env.clone();
        let saved_this = ctx.global_this.clone();

        // Create new environment for the function, with the function's closure as outer
        let func_scope = new_declarative_environment(Some(self.environment.clone()));
        ctx.lex_env = func_scope.clone();
        ctx.var_env = func_scope;
        ctx.global_this = Some(this_value);

        // Bind parameters to arguments
        for (i, param) in params.iter().enumerate() {
            if let PatternType::PatternWhichCanBeExpression(
                ExpressionPatternType::Identifier(id)
            ) = param {
                let arg_value = args.get(i).cloned().unwrap_or(JsValue::Undefined);
                ctx.create_binding(&id.name, false)?;
                ctx.initialize_binding(&id.name, arg_value)?;
            }
        }

        // Execute each statement in the function body
        let mut result_completion = super::types::Completion::normal();

        for stmt in body.body.iter() {
            let completion = execute_statement(stmt, ctx)?;

            match completion.completion_type {
                CompletionType::Return => {
                    result_completion = completion;
                    break;
                }
                CompletionType::Throw => {
                    // Restore environment before returning error
                    ctx.lex_env = saved_lex_env;
                    ctx.var_env = saved_var_env;
                    ctx.global_this = saved_this;
                    return Err(JErrorType::TypeError(format!(
                        "Uncaught exception: {:?}",
                        completion.value
                    )));
                }
                CompletionType::Break | CompletionType::Continue | CompletionType::Yield => {
                    result_completion = completion;
                    break;
                }
                CompletionType::Normal => {
                    result_completion = completion;
                }
            }
        }

        // Restore the previous environment
        ctx.lex_env = saved_lex_env;
        ctx.var_env = saved_var_env;
        ctx.global_this = saved_this;

        // Return the result
        match result_completion.completion_type {
            CompletionType::Return => Ok(result_completion.get_value()),
            _ => Ok(JsValue::Undefined),
        }
    }
}

impl JsObject for SimpleFunctionObject {
    fn get_object_base_mut(&mut self) -> &mut ObjectBase {
        &mut self.base
    }

    fn get_object_base(&self) -> &ObjectBase {
        &self.base
    }

    fn as_js_object(&self) -> &dyn JsObject {
        self
    }

    fn as_js_object_mut(&mut self) -> &mut dyn JsObject {
        self
    }
}

/// Type ID for SimpleFunctionObject - used for downcasting
pub fn is_simple_function_object(obj: &dyn JsObject) -> bool {
    // Check if the object has a special marker property
    let marker = PropertyKey::Str("__simple_function__".to_string());
    obj.get_object_base().properties.contains_key(&marker)
}

/// Create a function object from FunctionData.
/// Note: This creates a closure that references the AST. The AST must remain valid
/// for the lifetime of the function object.
pub fn create_function_object(func_data: &FunctionData, ctx: &EvalContext) -> ValueResult {
    let body_ptr = func_data.body.as_ref() as *const _;
    let params_ptr = &func_data.params.list as *const _;
    let environment = ctx.lex_env.clone();

    let mut func_obj = SimpleFunctionObject::new(body_ptr, params_ptr, environment);

    // Create a prototype object for this function
    let prototype = SimpleObject::new();
    let prototype_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(prototype))));

    // Store prototype on the function object
    func_obj.base.properties.insert(
        PropertyKey::Str("prototype".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Object(prototype_ref),
            writable: true,
            enumerable: false,
            configurable: false,
        }),
    );

    // Add marker property to identify this as a SimpleFunctionObject
    func_obj.base.properties.insert(
        PropertyKey::Str("__simple_function__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Mark as generator if applicable
    if func_data.generator {
        func_obj.base.properties.insert(
            PropertyKey::Str("__generator__".to_string()),
            PropertyDescriptor::Data(PropertyDescriptorData {
                value: JsValue::Boolean(true),
                writable: false,
                enumerable: false,
                configurable: false,
            }),
        );
    }

    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(func_obj))));
    Ok(JsValue::Object(obj_ref))
}

// ============================================================================
// Generator object
// ============================================================================

/// Generator state.
#[derive(Debug, Clone, PartialEq)]
pub enum GeneratorState {
    SuspendedStart,
    SuspendedYield,
    Executing,
    Completed,
}

/// Generator object that stores the suspended state of a generator function.
pub struct GeneratorObject {
    base: ObjectBase,
    /// Pointer to the function body
    body_ptr: *const crate::parser::ast::FunctionBodyData,
    /// Pointer to the formal parameters
    _params_ptr: *const Vec<PatternType>,
    /// The lexical environment at the time the generator was created
    environment: crate::runner::ds::lex_env::JsLexEnvironmentType,
    /// Current state
    state: GeneratorState,
    /// Current statement index (for resuming)
    current_index: usize,
    /// Stored local bindings (for resuming)
    local_bindings: std::collections::HashMap<String, JsValue>,
}

// Safety: GeneratorObject is only used within a single thread
unsafe impl Send for GeneratorObject {}
unsafe impl Sync for GeneratorObject {}

impl GeneratorObject {
    pub fn new(
        body_ptr: *const crate::parser::ast::FunctionBodyData,
        params_ptr: *const Vec<PatternType>,
        environment: crate::runner::ds::lex_env::JsLexEnvironmentType,
    ) -> Self {
        GeneratorObject {
            base: ObjectBase::new(),
            body_ptr,
            _params_ptr: params_ptr,
            environment,
            state: GeneratorState::SuspendedStart,
            current_index: 0,
            local_bindings: std::collections::HashMap::new(),
        }
    }

    /// Call .next() on this generator, executing until yield or completion.
    pub fn next(&mut self, ctx: &mut EvalContext) -> ValueResult {
        use crate::runner::ds::env_record::new_declarative_environment;
        use super::statement::execute_statement;
        use super::types::CompletionType;

        match self.state {
            GeneratorState::Completed => {
                // Return { value: undefined, done: true }
                return create_iterator_result(JsValue::Undefined, true);
            }
            GeneratorState::Executing => {
                return Err(JErrorType::TypeError("Generator is already executing".to_string()));
            }
            GeneratorState::SuspendedStart | GeneratorState::SuspendedYield => {
                // Continue or start execution
            }
        }

        self.state = GeneratorState::Executing;

        // Get the body and params (unsafe dereference)
        let body = unsafe { &*self.body_ptr };

        // Save current environment
        let saved_lex_env = ctx.lex_env.clone();
        let saved_var_env = ctx.var_env.clone();

        // Create new environment for the generator (or restore previous)
        let func_scope = new_declarative_environment(Some(self.environment.clone()));
        ctx.lex_env = func_scope.clone();
        ctx.var_env = func_scope;

        // Restore local bindings if resuming
        for (name, value) in &self.local_bindings {
            let _ = ctx.create_binding(name, false);
            let _ = ctx.initialize_binding(name, value.clone());
        }

        // Execute statements starting from current_index
        let mut result_value = JsValue::Undefined;
        let mut yielded = false;

        for (idx, stmt) in body.body.iter().enumerate() {
            if idx < self.current_index {
                continue; // Skip already executed statements
            }

            match execute_statement(stmt, ctx) {
                Ok(completion) => {
                    match completion.completion_type {
                        CompletionType::Return => {
                            result_value = completion.get_value();
                            self.state = GeneratorState::Completed;
                            break;
                        }
                        CompletionType::Yield => {
                            // Yield the value and suspend
                            result_value = completion.get_value();
                            self.current_index = idx + 1;
                            self.state = GeneratorState::SuspendedYield;

                            // Save current bindings
                            self.save_bindings(ctx);

                            yielded = true;
                            break;
                        }
                        CompletionType::Throw => {
                            ctx.lex_env = saved_lex_env;
                            ctx.var_env = saved_var_env;
                            self.state = GeneratorState::Completed;
                            return Err(JErrorType::TypeError(format!(
                                "Uncaught exception: {:?}",
                                completion.value
                            )));
                        }
                        _ => {
                            result_value = completion.get_value();
                        }
                    }
                }
                Err(JErrorType::YieldValue(value)) => {
                    // Yield expression hit
                    result_value = value;
                    self.current_index = idx + 1;
                    self.state = GeneratorState::SuspendedYield;

                    // Save current bindings
                    self.save_bindings(ctx);

                    yielded = true;
                    break;
                }
                Err(e) => {
                    ctx.lex_env = saved_lex_env;
                    ctx.var_env = saved_var_env;
                    self.state = GeneratorState::Completed;
                    return Err(e);
                }
            }
        }

        // If we didn't yield, we're done
        if !yielded && self.state == GeneratorState::Executing {
            self.state = GeneratorState::Completed;
        }

        // Restore the previous environment
        ctx.lex_env = saved_lex_env;
        ctx.var_env = saved_var_env;

        // Return { value, done }
        let done = self.state == GeneratorState::Completed;
        create_iterator_result(result_value, done)
    }

    fn save_bindings(&mut self, ctx: &EvalContext) {
        // This is a simplified version - in a full implementation we'd need
        // to properly capture all bindings from the current scope
        self.local_bindings.clear();

        // Get bindings from current environment
        let env = ctx.lex_env.borrow();
        if let Some(bindings) = env.inner.as_env_record().get_all_bindings() {
            for (name, value) in bindings {
                self.local_bindings.insert(name, value);
            }
        }
    }
}

impl JsObject for GeneratorObject {
    fn get_object_base_mut(&mut self) -> &mut ObjectBase {
        &mut self.base
    }

    fn get_object_base(&self) -> &ObjectBase {
        &self.base
    }

    fn as_js_object(&self) -> &dyn JsObject {
        self
    }

    fn as_js_object_mut(&mut self) -> &mut dyn JsObject {
        self
    }
}

/// Create an iterator result object { value, done }.
fn create_iterator_result(value: JsValue, done: bool) -> ValueResult {
    let mut obj = SimpleObject::new();

    obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("value".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value,
            writable: true,
            enumerable: true,
            configurable: true,
        }),
    );

    obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("done".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(done),
            writable: true,
            enumerable: true,
            configurable: true,
        }),
    );

    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(obj))));
    Ok(JsValue::Object(obj_ref))
}

/// Create a generator object from a generator function.
fn create_generator_object(
    body_ptr: *const crate::parser::ast::FunctionBodyData,
    params_ptr: *const Vec<PatternType>,
    environment: crate::runner::ds::lex_env::JsLexEnvironmentType,
    _args: Vec<JsValue>,
    _ctx: &mut EvalContext,
) -> ValueResult {
    let mut gen_obj = GeneratorObject::new(body_ptr, params_ptr, environment);

    // Add marker property
    gen_obj.base.properties.insert(
        PropertyKey::Str("__generator_object__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Store parameter values in local_bindings for when .next() is first called
    let params = unsafe { &*params_ptr };
    for (i, param) in params.iter().enumerate() {
        if let PatternType::PatternWhichCanBeExpression(
            ExpressionPatternType::Identifier(id)
        ) = param {
            let arg_value = _args.get(i).cloned().unwrap_or(JsValue::Undefined);
            gen_obj.local_bindings.insert(id.name.clone(), arg_value);
        }
    }

    // Create a 'next' method
    // We store a reference to the generator in a closure
    let gen_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(gen_obj))));

    // Add next method - this is a bit hacky, we'll store the generator ref
    // Actually, we can't easily create a closure here. Let's use a different approach:
    // We'll mark the generator and handle .next() specially in property access.

    // For simplicity, we mark it and handle next() calls specially
    Ok(JsValue::Object(gen_ref))
}

/// Create a callable "next" method for a generator object.
fn create_generator_next_method(gen_obj: JsObjectType) -> ValueResult {
    // Create a simple object that holds the generator reference
    // and is marked as a generator-next-method
    let mut next_obj = SimpleObject::new();

    next_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("__generator_next__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Object(gen_obj),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Mark it as callable
    next_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("__simple_function__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(next_obj))));
    Ok(JsValue::Object(obj_ref))
}

// ============================================================================
// Class evaluation
// ============================================================================

/// Evaluate a class expression and return the constructor function.
pub fn evaluate_class_expression(class_data: &ClassData, ctx: &mut EvalContext) -> ValueResult {
    evaluate_class(class_data, ctx)
}

/// Evaluate a class definition (used by both ClassExpression and ClassDeclaration).
/// Returns a constructor function object with methods on its prototype.
pub fn evaluate_class(class_data: &ClassData, ctx: &mut EvalContext) -> ValueResult {
    // 1. Evaluate the super class if present
    let parent_proto = if let Some(super_class) = &class_data.super_class {
        let parent = evaluate_expression(super_class, ctx)?;
        match &parent {
            JsValue::Object(parent_obj) => {
                // Get parent.prototype
                let borrowed = parent_obj.borrow();
                let proto_key = PropertyKey::Str("prototype".to_string());
                if let Some(PropertyDescriptor::Data(data)) = borrowed.as_js_object().get_object_base().properties.get(&proto_key) {
                    if let JsValue::Object(proto) = &data.value {
                        Some((parent_obj.clone(), proto.clone()))
                    } else {
                        return Err(JErrorType::TypeError("Parent class prototype is not an object".to_string()));
                    }
                } else {
                    return Err(JErrorType::TypeError("Parent class has no prototype".to_string()));
                }
            }
            _ => return Err(JErrorType::TypeError("Class extends value is not a constructor".to_string())),
        }
    } else {
        None
    };

    // 2. Find the constructor method
    let constructor_method = class_data.body.body.iter()
        .find(|m| matches!(m.kind, MethodDefinitionKind::Constructor));

    // 3. Create the constructor function
    let constructor_obj = if let Some(ctor_method) = constructor_method {
        // Use the defined constructor
        create_class_constructor(&ctor_method.value, parent_proto.as_ref().map(|(p, _)| p.clone()), ctx)?
    } else {
        // Create a default constructor
        create_default_constructor(parent_proto.as_ref().map(|(p, _)| p.clone()), ctx)?
    };

    // 4. Create the prototype object
    let prototype = if let Some((_, parent_proto)) = &parent_proto {
        // Derived class: prototype inherits from parent prototype
        let mut proto_obj = SimpleObject::new();
        proto_obj.get_object_base_mut().prototype = Some(parent_proto.clone());
        Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(proto_obj))))
    } else {
        // Base class: regular prototype object
        Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(SimpleObject::new()))))
    };

    // 5. Add methods to prototype (and static methods to constructor)
    for method in &class_data.body.body {
        if matches!(method.kind, MethodDefinitionKind::Constructor) {
            continue; // Skip constructor, already handled
        }

        // Get the method key
        let key = get_object_property_key(&method.key, method.computed, ctx)?;

        // Create the method function
        let method_fn = create_function_object(&method.value, ctx)?;

        // Determine target: prototype for instance methods, constructor for static
        let target = if method.static_flag {
            &constructor_obj
        } else {
            &JsValue::Object(prototype.clone())
        };

        match method.kind {
            MethodDefinitionKind::Method => {
                // Regular method
                if let JsValue::Object(target_obj) = target {
                    target_obj.borrow_mut().as_js_object_mut().get_object_base_mut().properties.insert(
                        PropertyKey::Str(key),
                        PropertyDescriptor::Data(PropertyDescriptorData {
                            value: method_fn,
                            writable: true,
                            enumerable: false,
                            configurable: true,
                        }),
                    );
                }
            }
            MethodDefinitionKind::Get => {
                // Getter
                if let JsValue::Object(getter_fn) = method_fn {
                    if let JsValue::Object(target_obj) = target {
                        let mut borrowed = target_obj.borrow_mut();
                        let prop_key = PropertyKey::Str(key.clone());
                        let existing = borrowed.as_js_object().get_object_base().properties.get(&prop_key).cloned();

                        let setter = if let Some(PropertyDescriptor::Accessor(acc)) = existing {
                            acc.set
                        } else {
                            None
                        };

                        borrowed.as_js_object_mut().get_object_base_mut().properties.insert(
                            prop_key,
                            PropertyDescriptor::Accessor(PropertyDescriptorAccessor {
                                get: Some(getter_fn),
                                set: setter,
                                enumerable: false,
                                configurable: true,
                            }),
                        );
                    }
                }
            }
            MethodDefinitionKind::Set => {
                // Setter
                if let JsValue::Object(setter_fn) = method_fn {
                    if let JsValue::Object(target_obj) = target {
                        let mut borrowed = target_obj.borrow_mut();
                        let prop_key = PropertyKey::Str(key.clone());
                        let existing = borrowed.as_js_object().get_object_base().properties.get(&prop_key).cloned();

                        let getter = if let Some(PropertyDescriptor::Accessor(acc)) = existing {
                            acc.get
                        } else {
                            None
                        };

                        borrowed.as_js_object_mut().get_object_base_mut().properties.insert(
                            prop_key,
                            PropertyDescriptor::Accessor(PropertyDescriptorAccessor {
                                get: getter,
                                set: Some(setter_fn),
                                enumerable: false,
                                configurable: true,
                            }),
                        );
                    }
                }
            }
            MethodDefinitionKind::Constructor => unreachable!(),
        }
    }

    // 6. Wire up constructor.prototype
    if let JsValue::Object(ctor_obj) = &constructor_obj {
        ctor_obj.borrow_mut().as_js_object_mut().get_object_base_mut().properties.insert(
            PropertyKey::Str("prototype".to_string()),
            PropertyDescriptor::Data(PropertyDescriptorData {
                value: JsValue::Object(prototype.clone()),
                writable: false,
                enumerable: false,
                configurable: false,
            }),
        );

        // Set prototype.constructor to point back to constructor
        prototype.borrow_mut().as_js_object_mut().get_object_base_mut().properties.insert(
            PropertyKey::Str("constructor".to_string()),
            PropertyDescriptor::Data(PropertyDescriptorData {
                value: constructor_obj.clone(),
                writable: true,
                enumerable: false,
                configurable: true,
            }),
        );
    }

    Ok(constructor_obj)
}

/// Create a constructor function from a method definition.
fn create_class_constructor(
    func_data: &FunctionData,
    _parent_ctor: Option<JsObjectType>,
    ctx: &EvalContext,
) -> ValueResult {
    let body_ptr = func_data.body.as_ref() as *const _;
    let params_ptr = &func_data.params.list as *const _;
    let environment = ctx.lex_env.clone();

    let mut func_obj = SimpleFunctionObject::new(body_ptr, params_ptr, environment);

    // Add marker property to identify this as a SimpleFunctionObject (callable)
    func_obj.base.properties.insert(
        PropertyKey::Str("__simple_function__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Mark as class constructor
    func_obj.base.properties.insert(
        PropertyKey::Str("__class_constructor__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(func_obj))));
    Ok(JsValue::Object(obj_ref))
}

/// Create a default constructor for a class.
fn create_default_constructor(
    _parent_ctor: Option<JsObjectType>,
    _ctx: &EvalContext,
) -> ValueResult {
    // Create a simple empty function that does nothing
    // For derived classes, it should call super(), but we'll simplify for now
    let mut func_obj = SimpleObject::new();

    // Add marker property to identify this as callable
    func_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("__simple_function__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Mark as class constructor
    func_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("__class_constructor__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    // Mark as default constructor (no-op)
    func_obj.get_object_base_mut().properties.insert(
        PropertyKey::Str("__default_constructor__".to_string()),
        PropertyDescriptor::Data(PropertyDescriptorData {
            value: JsValue::Boolean(true),
            writable: false,
            enumerable: false,
            configurable: false,
        }),
    );

    let obj_ref: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(func_obj))));
    Ok(JsValue::Object(obj_ref))
}