javascript 0.1.13

A JavaScript engine implementation in Rust
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
#![allow(clippy::collapsible_if, clippy::collapsible_match)]

use crate::core::{
    ClosureData, DestructuringElement, Expr, JSObjectDataPtr, Statement, Value, evaluate_expr, evaluate_statements, get_own_property,
    new_js_object_data, prepare_function_call_env,
};
use crate::core::{obj_get_key_value, obj_set_key_value, value_to_string};
use crate::js_array::is_array;
use crate::{error::JSError, unicode::utf8_to_utf16};
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug, Clone)]
pub enum ClassMember {
    Constructor(Vec<DestructuringElement>, Vec<Statement>),           // parameters, body
    Method(String, Vec<DestructuringElement>, Vec<Statement>),        // name, parameters, body
    StaticMethod(String, Vec<DestructuringElement>, Vec<Statement>),  // name, parameters, body
    Property(String, Expr),                                           // name, value
    StaticProperty(String, Expr),                                     // name, value
    PrivateProperty(String, Expr),                                    // name, value
    PrivateStaticProperty(String, Expr),                              // name, value
    PrivateMethod(String, Vec<DestructuringElement>, Vec<Statement>), // name, parameters, body
    PrivateStaticMethod(String, Vec<DestructuringElement>, Vec<Statement>), // name, parameters, body
    PrivateGetter(String, Vec<Statement>),                            // name, body
    PrivateSetter(String, Vec<DestructuringElement>, Vec<Statement>), // name, parameter, body
    PrivateStaticGetter(String, Vec<Statement>),                      // name, body
    PrivateStaticSetter(String, Vec<DestructuringElement>, Vec<Statement>), // name, parameter, body
    StaticBlock(Vec<Statement>),                                      // body
    Getter(String, Vec<Statement>),                                   // name, body
    Setter(String, Vec<DestructuringElement>, Vec<Statement>),        // name, parameter, body
    StaticGetter(String, Vec<Statement>),                             // name, body
    StaticSetter(String, Vec<DestructuringElement>, Vec<Statement>),  // name, parameter, body
}

#[derive(Debug, Clone)]
pub struct ClassDefinition {
    pub name: String,
    pub extends: Option<Expr>,
    pub members: Vec<ClassMember>,
}

pub(crate) fn is_class_instance(obj: &JSObjectDataPtr) -> Result<bool, JSError> {
    // Check if the object's prototype has a __class_def__ property
    // This means the object was created with 'new ClassName()'
    if let Some(proto_val) = obj_get_key_value(obj, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        // Check if the prototype object has __class_def__
        if let Some(class_def_val) = obj_get_key_value(proto_obj, &"__class_def__".into())?
            && let Value::ClassDefinition(_) = *class_def_val.borrow()
        {
            return Ok(true);
        }
    }
    Ok(false)
}

pub(crate) fn get_class_proto_obj(class_obj: &JSObjectDataPtr) -> Result<JSObjectDataPtr, JSError> {
    if let Some(proto_val) = obj_get_key_value(class_obj, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        return Ok(proto_obj.clone());
    }
    Err(raise_type_error!("Prototype object not found"))
}

pub(crate) fn is_private_member_declared(class_def: &ClassDefinition, name: &str) -> bool {
    // Accept either '#name' or 'name' as input; normalize to the raw identifier
    let key = if let Some(stripped) = name.strip_prefix('#') {
        stripped
    } else {
        name
    };
    for member in &class_def.members {
        match member {
            ClassMember::PrivateProperty(n, _)
            | ClassMember::PrivateMethod(n, _, _)
            | ClassMember::PrivateStaticProperty(n, _)
            | ClassMember::PrivateStaticMethod(n, _, _) => {
                if n == key {
                    return true;
                }
            }
            ClassMember::PrivateGetter(n, _)
            | ClassMember::PrivateSetter(n, _, _)
            | ClassMember::PrivateStaticGetter(n, _)
            | ClassMember::PrivateStaticSetter(n, _, _) => {
                if n == key {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

pub(crate) fn evaluate_this(env: &JSObjectDataPtr) -> Result<Value, JSError> {
    // Walk the environment/prototype (scope) chain looking for a bound
    // `this` value. Some nested/temporarily created environments (e.g.
    // catch-block envs) do not bind `this` themselves but inherit the
    // effective global `this` from an outer environment. Return the
    // first `this` value found; if none is present, return the topmost
    // environment object as the default global object.
    let mut env_opt: Option<JSObjectDataPtr> = Some(env.clone());
    let mut last_seen: JSObjectDataPtr = env.clone();
    while let Some(env_ptr) = env_opt {
        last_seen = env_ptr.clone();
        if let Some(this_val_rc) = obj_get_key_value(&env_ptr, &"this".into())? {
            return Ok(this_val_rc.borrow().clone());
        }
        env_opt = env_ptr.borrow().prototype.clone();
    }
    Ok(Value::Object(last_seen))
}

pub(crate) fn evaluate_new(env: &JSObjectDataPtr, constructor: &Expr, args: &[Expr]) -> Result<Value, JSError> {
    // Evaluate the constructor
    let constructor_val = evaluate_expr(env, constructor)?;
    // Log pointer/type of the evaluated constructor value for diagnostics
    match &constructor_val {
        Value::Object(o) => {
            log::debug!("DBG evaluate_new - constructor evaluated -> Object ptr={:p}", Rc::as_ptr(o));
        }
        Value::Function(name) => {
            log::debug!("DBG evaluate_new - constructor evaluated -> Builtin Function {}", name);
        }
        Value::Closure(..) | Value::AsyncClosure(..) => {
            log::debug!("DBG evaluate_new - constructor evaluated -> Closure")
        }
        other => {
            log::debug!("DBG evaluate_new - constructor evaluated -> {:?}", other);
        }
    }
    log::trace!("evaluate_new - invoking constructor (evaluated)");

    match constructor_val {
        Value::Object(class_obj) => {
            // If this object wraps a closure (created from a function
            // expression/declaration), treat it as a constructor by
            // extracting the internal closure and invoking it as a
            // constructor. This allows script-defined functions stored
            // as objects to be used with `new` while still exposing
            // assignable `prototype` properties.
            if let Some(cl_val_rc) = obj_get_key_value(&class_obj, &"__closure__".into())? {
                let closure_data = match &*cl_val_rc.borrow() {
                    Value::Closure(data) | Value::AsyncClosure(data) => Some(data.clone()),
                    _ => None,
                };

                if let Some(data) = closure_data {
                    let params = &data.params;
                    let body = &data.body;
                    let captured_env = &data.env;
                    // Create the instance object
                    let instance = new_js_object_data();

                    // Attach a debug identifier to help correlate runtime instances
                    // with logs (printed as a pointer string).
                    let dbg_ptr_str = format!("{:p}", Rc::as_ptr(&instance));
                    obj_set_key_value(&instance, &"__dbg_ptr__".into(), Value::String(utf8_to_utf16(&dbg_ptr_str)))?;
                    log::debug!(
                        "DBG evaluate_new - created instance ptr={:p} __dbg_ptr__={}",
                        Rc::as_ptr(&instance),
                        dbg_ptr_str
                    );

                    // Set prototype from the constructor object's `.prototype` if available
                    if let Some(prototype_val) = obj_get_key_value(&class_obj, &"prototype".into())? {
                        if let Value::Object(proto_obj) = &*prototype_val.borrow() {
                            instance.borrow_mut().prototype = Some(proto_obj.clone());
                            obj_set_key_value(&instance, &"__proto__".into(), Value::Object(proto_obj.clone()))?;
                        } else {
                            obj_set_key_value(&instance, &"__proto__".into(), prototype_val.borrow().clone())?;
                        }
                    }

                    // Prepare function environment with 'this' bound to the instance
                    let mut evaluated_args = Vec::new();
                    crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;
                    let func_env = prepare_function_call_env(
                        Some(captured_env),
                        Some(Value::Object(instance.clone())),
                        Some(params),
                        &evaluated_args,
                        None,
                        None,
                    )?;

                    // Execute constructor body
                    evaluate_statements(&func_env, body)?;

                    // Ensure instance.constructor points back to the constructor object
                    obj_set_key_value(&instance, &"constructor".into(), Value::Object(class_obj.clone()))?;

                    return Ok(Value::Object(instance));
                }
            }

            // Check if this is Array constructor
            if get_own_property(&class_obj, &"__is_array_constructor".into()).is_some() {
                return crate::js_array::handle_array_constructor(args, env);
            }

            // Check if this is a TypedArray constructor
            if get_own_property(&class_obj, &"__kind".into()).is_some() {
                return crate::js_typedarray::handle_typedarray_constructor(&class_obj, args, env);
            }

            // Check if this is ArrayBuffer constructor
            if get_own_property(&class_obj, &"__arraybuffer".into()).is_some() {
                return crate::js_typedarray::handle_arraybuffer_constructor(args, env);
            }

            // Check if this is DataView constructor
            if get_own_property(&class_obj, &"__dataview".into()).is_some() {
                return crate::js_typedarray::handle_dataview_constructor(args, env);
            }

            // Check if this is a class object
            if let Some(class_def_val) = obj_get_key_value(&class_obj, &"__class_def__".into())?
                && let Value::ClassDefinition(ref class_def) = *class_def_val.borrow()
            {
                // Create instance
                let instance = new_js_object_data();

                // Set prototype (both internal pointer and __proto__ property)
                if let Some(prototype_val) = obj_get_key_value(&class_obj, &"prototype".into())? {
                    if let Value::Object(proto_obj) = &*prototype_val.borrow() {
                        instance.borrow_mut().prototype = Some(proto_obj.clone());
                        obj_set_key_value(&instance, &"__proto__".into(), Value::Object(proto_obj.clone()))?;
                    } else {
                        // Fallback: store whatever prototype value was provided
                        obj_set_key_value(&instance, &"__proto__".into(), prototype_val.borrow().clone())?;
                    }
                }

                // Set instance properties
                for member in &class_def.members {
                    if let ClassMember::Property(prop_name, value_expr) = member {
                        let value = evaluate_expr(env, value_expr)?;
                        obj_set_key_value(&instance, &prop_name.into(), value)?;
                    } else if let ClassMember::PrivateProperty(prop_name, value_expr) = member {
                        // Store instance private fields under a key prefixed with '#'
                        let value = evaluate_expr(env, value_expr)?;
                        obj_set_key_value(&instance, &format!("#{}", prop_name).into(), value)?;
                    }
                }

                // Call constructor if it exists
                for member in &class_def.members {
                    if let ClassMember::Constructor(params, body) = member {
                        // Collect all arguments, expanding spreads
                        let mut evaluated_args = Vec::new();
                        crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                        let func_env = prepare_function_call_env(
                            None,
                            Some(Value::Object(instance.clone())),
                            Some(params),
                            &evaluated_args,
                            None,
                            None,
                        )?;

                        // Execute constructor body
                        let result = crate::core::evaluate_statements_with_context(&func_env, body)?;

                        // Check for explicit return
                        if let crate::core::ControlFlow::Return(ret_val) = result {
                            if let Value::Object(_) = ret_val {
                                return Ok(ret_val);
                            }
                        }

                        // Retrieve 'this' from env, as it might have been changed by super()
                        if let Some(final_this) = obj_get_key_value(&func_env, &"this".into())? {
                            if let Value::Object(final_instance) = &*final_this.borrow() {
                                // Ensure instance.constructor points back to the constructor object
                                obj_set_key_value(final_instance, &"constructor".into(), Value::Object(class_obj.clone()))?;
                                return Ok(Value::Object(final_instance.clone()));
                            }
                        }
                        break;
                    }
                }

                // Also set an own `constructor` property on the instance so `err.constructor`
                // resolves directly to the canonical constructor object.
                obj_set_key_value(&instance, &"constructor".into(), Value::Object(class_obj.clone()))?;

                return Ok(Value::Object(instance));
            }
            // Check if this is the Number constructor object
            if obj_get_key_value(&class_obj, &"MAX_VALUE".into())?.is_some() {
                return handle_number_constructor(args, env);
            }
            // Check for constructor-like singleton objects created by the evaluator
            if get_own_property(&class_obj, &"__is_string_constructor".into()).is_some() {
                return handle_string_constructor(args, env);
            }
            if get_own_property(&class_obj, &"__is_boolean_constructor".into()).is_some() {
                return handle_boolean_constructor(args, env);
            }
            if get_own_property(&class_obj, &"__is_date_constructor".into()).is_some() {
                return crate::js_date::handle_date_constructor(args, env);
            }
            if get_own_property(&class_obj, &"__is_function_constructor".into()).is_some() {
                return crate::js_function::handle_global_function("Function", args, env);
            }
            // Error-like constructors (Error) created via ensure_constructor_object
            if get_own_property(&class_obj, &"__is_error_constructor".into()).is_some() {
                log::debug!(
                    "DBG evaluate_new - entered error-like constructor branch, args.len={} class_obj ptr={:p}",
                    args.len(),
                    Rc::as_ptr(&class_obj)
                );
                if !args.is_empty() {
                    log::debug!("DBG evaluate_new - args[0] expr = {:?}", args[0]);
                }
                // Use the class_obj as the canonical constructor
                let canonical_ctor = class_obj.clone();

                // Create instance object
                let instance = new_js_object_data();

                // Attach a debug identifier (pointer string) so we can correlate
                // runtime-created instances with later logs (e.g. thrown object ptrs).
                let dbg_ptr_str = format!("{:p}", Rc::as_ptr(&instance));
                obj_set_key_value(&instance, &"__dbg_ptr__".into(), Value::String(utf8_to_utf16(&dbg_ptr_str)))?;
                log::debug!(
                    "DBG evaluate_new - created instance ptr={:p} __dbg_ptr__={}",
                    Rc::as_ptr(&instance),
                    dbg_ptr_str
                );

                // Set prototype from the canonical constructor's `.prototype` if available
                if let Some(prototype_val) = obj_get_key_value(&canonical_ctor, &"prototype".into())? {
                    if let Value::Object(proto_obj) = &*prototype_val.borrow() {
                        instance.borrow_mut().prototype = Some(proto_obj.clone());
                        obj_set_key_value(&instance, &"__proto__".into(), Value::Object(proto_obj.clone()))?;
                    } else {
                        obj_set_key_value(&instance, &"__proto__".into(), prototype_val.borrow().clone())?;
                    }
                }

                // If a message argument was supplied, set the message property
                if !args.is_empty() {
                    log::debug!("DBG evaluate_new - about to evaluate args[0]");
                    match evaluate_expr(env, &args[0]) {
                        Ok(val) => {
                            log::debug!("DBG evaluate_new - eval args[0] result = {:?}", val);
                            match val {
                                Value::String(s) => {
                                    log::debug!("DBG evaluate_new - setting message (string) = {:?}", String::from_utf16_lossy(&s));
                                    obj_set_key_value(&instance, &"message".into(), Value::String(s))?;
                                }
                                Value::Number(n) => {
                                    log::debug!("DBG evaluate_new - setting message (number) = {}", n);
                                    obj_set_key_value(&instance, &"message".into(), Value::String(utf8_to_utf16(&n.to_string())))?;
                                }
                                _ => {
                                    // convert other types to string via value_to_string
                                    let s = utf8_to_utf16(&value_to_string(&val));
                                    log::debug!("DBG evaluate_new - setting message (other) = {:?}", String::from_utf16_lossy(&s));
                                    obj_set_key_value(&instance, &"message".into(), Value::String(s))?;
                                }
                            }
                        }
                        Err(err) => {
                            log::debug!("DBG evaluate_new - failed to evaluate args[0]: {:?}", err);
                        }
                    }
                }

                // Ensure prototype.constructor points back to the canonical constructor
                if let Some(prototype_val) = obj_get_key_value(&canonical_ctor, &"prototype".into())? {
                    if let Value::Object(proto_obj) = &*prototype_val.borrow() {
                        match crate::core::get_own_property(proto_obj, &"constructor".into()) {
                            Some(existing_rc) => {
                                if let Value::Object(existing_ctor_obj) = &*existing_rc.borrow() {
                                    if !Rc::ptr_eq(existing_ctor_obj, &canonical_ctor) {
                                        obj_set_key_value(proto_obj, &"constructor".into(), Value::Object(canonical_ctor.clone()))?;
                                    }
                                } else {
                                    obj_set_key_value(proto_obj, &"constructor".into(), Value::Object(canonical_ctor.clone()))?;
                                }
                            }
                            None => {
                                obj_set_key_value(proto_obj, &"constructor".into(), Value::Object(canonical_ctor.clone()))?;
                            }
                        }
                    }
                }

                // Ensure constructor.name exists
                let ctor_name = "Error";
                match crate::core::get_own_property(&canonical_ctor, &"name".into()) {
                    Some(name_rc) => {
                        if let Value::Undefined = &*name_rc.borrow() {
                            obj_set_key_value(&canonical_ctor, &"name".into(), Value::String(utf8_to_utf16(ctor_name)))?;
                        }
                    }
                    None => {
                        obj_set_key_value(&canonical_ctor, &"name".into(), Value::String(utf8_to_utf16(ctor_name)))?;
                    }
                }

                // Also set an own `constructor` property on the instance so `err.constructor`
                // resolves directly to the canonical constructor object used by the bootstrap.
                obj_set_key_value(&instance, &"constructor".into(), Value::Object(canonical_ctor.clone()))?;

                // Build a minimal stack string from any linked __frame/__caller
                // frames available on the current environment. This provides a
                // reasonable default for Error instances created via `new Error()`.
                let mut stack_lines: Vec<String> = Vec::new();
                // First line: Error: <message>
                let message_text = match crate::core::get_own_property(&instance, &"message".into()) {
                    Some(mrc) => match &*mrc.borrow() {
                        Value::String(s) => String::from_utf16_lossy(s),
                        other => crate::core::value_to_string(other),
                    },
                    None => String::new(),
                };
                stack_lines.push(format!("Error: {}", message_text));

                // Walk caller chain starting from current env
                let mut env_opt: Option<crate::core::JSObjectDataPtr> = Some(env.clone());
                while let Some(env_ptr) = env_opt {
                    if let Ok(Some(frame_val_rc)) = obj_get_key_value(&env_ptr, &"__frame".into()) {
                        if let Value::String(s_utf16) = &*frame_val_rc.borrow() {
                            stack_lines.push(format!("    at {}", String::from_utf16_lossy(s_utf16)));
                        }
                    }
                    // follow caller link if present
                    if let Ok(Some(caller_rc)) = obj_get_key_value(&env_ptr, &"__caller".into()) {
                        if let Value::Object(caller_env) = &*caller_rc.borrow() {
                            env_opt = Some(caller_env.clone());
                            continue;
                        }
                    }
                    break;
                }

                let stack_combined = stack_lines.join("\n");
                obj_set_key_value(&instance, &"stack".into(), Value::String(utf8_to_utf16(&stack_combined)))?;

                return Ok(Value::Object(instance));
            }
        }
        Value::Closure(data) | Value::AsyncClosure(data) => {
            let params = &data.params;
            let body = &data.body;
            let captured_env = &data.env;
            // Handle function constructors
            let instance = new_js_object_data();
            // Collect all arguments, expanding spreads
            let mut evaluated_args = Vec::new();
            crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

            let func_env = prepare_function_call_env(
                Some(captured_env),
                Some(Value::Object(instance.clone())),
                Some(params),
                &evaluated_args,
                None,
                None,
            )?;

            // Execute function body
            evaluate_statements(&func_env, body)?;

            return Ok(Value::Object(instance));
        }
        Value::Function(func_name) => {
            // Handle built-in constructors
            match func_name.as_str() {
                "Date" => {
                    return crate::js_date::handle_date_constructor(args, env);
                }
                "Array" => {
                    return crate::js_array::handle_array_constructor(args, env);
                }
                "RegExp" => {
                    return crate::js_regexp::handle_regexp_constructor(args, env);
                }
                "Object" => {
                    return handle_object_constructor(args, env);
                }
                "Number" => {
                    return handle_number_constructor(args, env);
                }
                "Boolean" => {
                    return handle_boolean_constructor(args, env);
                }
                "String" => {
                    return handle_string_constructor(args, env);
                }
                "Promise" => {
                    return crate::js_promise::handle_promise_constructor(args, env);
                }
                "Map" => return crate::js_map::handle_map_constructor(args, env),
                "Set" => return crate::js_set::handle_set_constructor(args, env),
                "Proxy" => return crate::js_proxy::handle_proxy_constructor(args, env),
                "WeakMap" => return crate::js_weakmap::handle_weakmap_constructor(args, env),
                "WeakSet" => return crate::js_weakset::handle_weakset_constructor(args, env),
                "MockIntlConstructor" => {
                    // Handle mock Intl constructor for testing
                    let locale_arg = if !args.is_empty() {
                        match evaluate_expr(env, &args[0])? {
                            // Accept either a single string or an array containing a string
                            Value::String(s) => Some(crate::unicode::utf16_to_utf8(&s)),
                            Value::Object(arr_obj) if is_array(&arr_obj) => {
                                // Try to read index 0 from the array
                                if let Some(first_rc) = obj_get_key_value(&arr_obj, &"0".into())? {
                                    match &*first_rc.borrow() {
                                        Value::String(s) => Some(crate::unicode::utf16_to_utf8(s)),
                                        _ => None,
                                    }
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        }
                    } else {
                        None
                    };
                    return crate::js_testintl::create_mock_intl_instance(locale_arg, env);
                }
                _ => {
                    log::warn!("evaluate_new - constructor is not an object or closure: Function({func_name})",);
                }
            }
        }
        _ => {
            log::warn!("evaluate_new - constructor is not an object or closure: {constructor_val:?}");
        }
    }

    Err(raise_type_error!("Constructor is not callable"))
}

pub(crate) fn create_class_object(
    name: &str,
    extends: &Option<Expr>,
    members: &[ClassMember],
    env: &JSObjectDataPtr,
    bind_name_during_creation: bool,
) -> Result<Value, JSError> {
    // Create a class object (function) that can be instantiated with 'new'
    let class_obj = new_js_object_data();

    // If requested (class declaration), bind the class name into the surrounding environment
    // early so that static blocks can reference it during class evaluation.
    if bind_name_during_creation && !name.is_empty() {
        crate::core::env_set(env, name, Value::Object(class_obj.clone()))?;
    }

    // Set class name
    obj_set_key_value(&class_obj, &"name".into(), Value::String(utf8_to_utf16(name)))?;

    // Create the prototype object first
    let prototype_obj = new_js_object_data();

    // Handle inheritance if extends is specified
    if let Some(parent_expr) = extends {
        // Evaluate the extends expression to get the parent class object
        let parent_val = evaluate_expr(env, parent_expr)?;
        if let Value::Object(parent_class_obj) = parent_val {
            // Get the parent class's prototype
            if let Some(parent_proto_val) = obj_get_key_value(&parent_class_obj, &"prototype".into())?
                && let Value::Object(parent_proto_obj) = &*parent_proto_val.borrow()
            {
                // Set the child class prototype's internal prototype pointer and __proto__ property
                prototype_obj.borrow_mut().prototype = Some(parent_proto_obj.clone());
                obj_set_key_value(&prototype_obj, &"__proto__".into(), Value::Object(parent_proto_obj.clone()))?;
            }
        } else {
            return Err(raise_eval_error!("Parent class expression did not evaluate to a class constructor"));
        }
    } else {
        // No `extends`: link prototype.__proto__ to `Object.prototype` if available so
        // instance property lookups fall back to the standard Object.prototype methods
        // (e.g., toString, valueOf, hasOwnProperty).
        let _ = crate::core::set_internal_prototype_from_constructor(&prototype_obj, env, "Object");
    }

    obj_set_key_value(&class_obj, &"prototype".into(), Value::Object(prototype_obj.clone()))?;
    obj_set_key_value(&prototype_obj, &"constructor".into(), Value::Object(class_obj.clone()))?;

    // Store class definition for later use
    let class_def = ClassDefinition {
        name: name.to_string(),
        extends: extends.clone(),
        members: members.to_vec(),
    };

    // Store class definition in a special property
    let class_def_val = Value::ClassDefinition(Rc::new(class_def));
    obj_set_key_value(&class_obj, &"__class_def__".into(), class_def_val.clone())?;

    // Store class definition in prototype as well for instanceof checks
    obj_set_key_value(&prototype_obj, &"__class_def__".into(), class_def_val)?;

    // Add methods to prototype
    for member in members {
        match member {
            ClassMember::Method(method_name, params, body) => {
                // Create a closure for the method
                let closure_data = ClosureData::new(params, body, env, Some(&prototype_obj));
                let method_closure = Value::Closure(Rc::new(closure_data));
                obj_set_key_value(&prototype_obj, &method_name.into(), method_closure)?;
            }
            ClassMember::Constructor(_, _) => {
                // Constructor is handled separately during instantiation
            }
            ClassMember::Property(_, _) => {
                // Instance properties not implemented yet
            }
            ClassMember::Getter(getter_name, body) => {
                // Merge getter into existing property descriptor if present
                if let Some(existing_rc) = crate::core::get_own_property(&prototype_obj, &getter_name.into()) {
                    match &*existing_rc.borrow() {
                        Value::Property {
                            value,
                            getter: _old_getter,
                            setter,
                        } => {
                            let new_prop = Value::Property {
                                value: value.clone(),
                                getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                                setter: setter.clone(),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &getter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                        Value::Setter(params, body_set, set_env, home) => {
                            // Convert to property descriptor with both getter and setter
                            let new_prop = Value::Property {
                                value: None,
                                getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                                setter: Some((params.clone(), body_set.clone(), set_env.clone(), home.clone())),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &getter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                        // If there's an existing raw value or getter, overwrite with a Property descriptor bearing the getter
                        _ => {
                            let new_prop = Value::Property {
                                value: None,
                                getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                                setter: None,
                            };
                            crate::core::obj_set_rc(&prototype_obj, &getter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                    }
                } else {
                    let new_prop = Value::Property {
                        value: None,
                        getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                        setter: None,
                    };
                    obj_set_key_value(&prototype_obj, &getter_name.into(), new_prop)?;
                }
            }
            ClassMember::Setter(setter_name, param, body) => {
                // Merge setter into existing property descriptor if present
                if let Some(existing_rc) = crate::core::get_own_property(&prototype_obj, &setter_name.into()) {
                    match &*existing_rc.borrow() {
                        Value::Property {
                            value,
                            getter,
                            setter: _old_setter,
                        } => {
                            let new_prop = Value::Property {
                                value: value.clone(),
                                getter: getter.clone(),
                                setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &setter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                        Value::Getter(get_body, get_env, home) => {
                            // Convert to property descriptor with both getter and setter
                            let new_prop = Value::Property {
                                value: None,
                                getter: Some((get_body.clone(), get_env.clone(), home.clone())),
                                setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &setter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                        _ => {
                            let new_prop = Value::Property {
                                value: None,
                                getter: None,
                                setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &setter_name.into(), Rc::new(RefCell::new(new_prop)));
                        }
                    }
                } else {
                    let new_prop = Value::Property {
                        value: None,
                        getter: None,
                        setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                    };
                    obj_set_key_value(&prototype_obj, &setter_name.into(), new_prop)?;
                }
            }
            ClassMember::StaticMethod(method_name, params, body) => {
                // Add static method to class object
                let closure_data = ClosureData::new(params, body, env, Some(&class_obj));
                let method_closure = Value::Closure(Rc::new(closure_data));
                obj_set_key_value(&class_obj, &method_name.into(), method_closure)?;
            }
            ClassMember::StaticProperty(prop_name, value_expr) => {
                // Add static property to class object
                let value = evaluate_expr(env, value_expr)?;
                obj_set_key_value(&class_obj, &prop_name.into(), value)?;
            }
            ClassMember::StaticGetter(getter_name, body) => {
                // Create a static getter for the class object
                let getter = Value::Getter(body.clone(), env.clone(), Some(class_obj.clone()));
                obj_set_key_value(&class_obj, &getter_name.into(), getter)?;
            }
            ClassMember::StaticSetter(setter_name, param, body) => {
                // Create a static setter for the class object
                let setter = Value::Setter(param.clone(), body.clone(), env.clone(), Some(class_obj.clone()));
                obj_set_key_value(&class_obj, &setter_name.into(), setter)?;
            }
            ClassMember::PrivateProperty(_, _) => {
                // Instance private properties handled during instantiation
            }
            ClassMember::PrivateMethod(method_name, params, body) => {
                // Add private method to prototype using the '#name' key
                let closure_data = ClosureData::new(params, body, env, None);
                let method_closure = Value::Closure(Rc::new(closure_data));
                obj_set_key_value(&prototype_obj, &format!("#{}", method_name).into(), method_closure)?;
            }
            ClassMember::PrivateGetter(getter_name, body) => {
                let key = format!("#{}", getter_name);
                // Merge into existing property descriptor if present
                if let Some(existing_rc) = crate::core::get_own_property(&prototype_obj, &key.clone().into()) {
                    match &*existing_rc.borrow() {
                        Value::Property {
                            value,
                            getter: _old_getter,
                            setter,
                        } => {
                            let new_prop = Value::Property {
                                value: value.clone(),
                                getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                                setter: setter.clone(),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &key.clone().into(), Rc::new(RefCell::new(new_prop)));
                        }
                        _ => {
                            let new_prop = Value::Property {
                                value: None,
                                getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                                setter: None,
                            };
                            crate::core::obj_set_rc(&prototype_obj, &key.into(), Rc::new(RefCell::new(new_prop)));
                        }
                    }
                } else {
                    let new_prop = Value::Property {
                        value: None,
                        getter: Some((body.clone(), env.clone(), Some(prototype_obj.clone()))),
                        setter: None,
                    };
                    obj_set_key_value(&prototype_obj, &key.into(), new_prop)?;
                }
            }
            ClassMember::PrivateSetter(setter_name, param, body) => {
                let key = format!("#{}", setter_name);
                if let Some(existing_rc) = crate::core::get_own_property(&prototype_obj, &key.clone().into()) {
                    match &*existing_rc.borrow() {
                        Value::Property {
                            value,
                            getter,
                            setter: _old_setter,
                        } => {
                            let new_prop = Value::Property {
                                value: value.clone(),
                                getter: getter.clone(),
                                setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &key.clone().into(), Rc::new(RefCell::new(new_prop)));
                        }
                        _ => {
                            let new_prop = Value::Property {
                                value: None,
                                getter: None,
                                setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                            };
                            crate::core::obj_set_rc(&prototype_obj, &key.into(), Rc::new(RefCell::new(new_prop)));
                        }
                    }
                } else {
                    let new_prop = Value::Property {
                        value: None,
                        getter: None,
                        setter: Some((param.clone(), body.clone(), env.clone(), Some(prototype_obj.clone()))),
                    };
                    obj_set_key_value(&prototype_obj, &key.into(), new_prop)?;
                }
            }
            ClassMember::PrivateStaticProperty(prop_name, value_expr) => {
                // Add private static property to class object using the '#name' key
                let value = evaluate_expr(env, value_expr)?;
                obj_set_key_value(&class_obj, &format!("#{}", prop_name).into(), value)?;
            }
            ClassMember::PrivateStaticGetter(getter_name, body) => {
                let key = format!("#{}", getter_name);
                let getter = Value::Getter(body.clone(), env.clone(), Some(class_obj.clone()));
                obj_set_key_value(&class_obj, &key.into(), getter)?;
            }
            ClassMember::PrivateStaticSetter(setter_name, param, body) => {
                let key = format!("#{}", setter_name);
                let setter = Value::Setter(param.clone(), body.clone(), env.clone(), Some(class_obj.clone()));
                obj_set_key_value(&class_obj, &key.into(), setter)?;
            }
            ClassMember::PrivateStaticMethod(method_name, params, body) => {
                // Add private static method to class object using the '#name' key
                let closure_data = ClosureData::new(params, body, env, Some(&class_obj));
                let method_closure = Value::Closure(Rc::new(closure_data));
                obj_set_key_value(&class_obj, &format!("#{}", method_name).into(), method_closure)?;
            }
            ClassMember::StaticBlock(body) => {
                let block_env = new_js_object_data();
                block_env.borrow_mut().prototype = Some(env.clone());
                obj_set_key_value(&block_env, &"this".into(), Value::Object(class_obj.clone()))?;
                evaluate_statements(&block_env, body)?;
            }
        }
    }

    Ok(Value::Object(class_obj))
}

pub(crate) fn call_static_method(
    class_obj: &JSObjectDataPtr,
    method: &str,
    args: &[Expr],
    env: &JSObjectDataPtr,
) -> Result<Value, JSError> {
    // Look for static method directly on the class object
    if let Some(method_val) = obj_get_key_value(class_obj, &method.into())? {
        match &*method_val.borrow() {
            Value::Closure(data) | Value::AsyncClosure(data) => {
                let params = &data.params;
                let body = &data.body;
                let _captured_env = &data.env;
                // Collect all arguments, expanding spreads
                let mut evaluated_args = Vec::new();
                crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                // Create function environment with 'this' bound to the class object and bind params
                let func_env = prepare_function_call_env(
                    None,
                    Some(Value::Object(class_obj.clone())),
                    Some(params),
                    &evaluated_args,
                    None,
                    None,
                )?;

                // Execute method body
                return evaluate_statements(&func_env, body);
            }
            _ => {
                return Err(raise_eval_error!(format!("'{method}' is not a static method")));
            }
        }
    }
    Err(raise_eval_error!(format!("Static method '{method}' not found on class")))
}

pub(crate) fn call_class_method(obj_map: &JSObjectDataPtr, method: &str, args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let proto_obj = get_class_proto_obj(obj_map)?;
    // Look for method in prototype
    if let Some(method_val) = obj_get_key_value(&proto_obj, &method.into())? {
        log::trace!("Found method {method} in prototype");
        match &*method_val.borrow() {
            Value::Closure(data) | Value::AsyncClosure(data) => {
                let params = &data.params;
                let body = &data.body;
                let captured_env = &data.env;
                let home_obj = data.home_object.borrow().clone();
                log::trace!("Method is a closure with {} params", params.len());
                // Collect all arguments, expanding spreads
                let mut evaluated_args = Vec::new();
                crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                // Create function environment based on the closure's captured env and bind params, binding `this` to the instance
                let func_env = prepare_function_call_env(
                    Some(captured_env),
                    Some(Value::Object(obj_map.clone())),
                    Some(params),
                    &evaluated_args,
                    None,
                    None,
                )?;

                if let Some(home) = home_obj {
                    crate::core::obj_set_key_value(&func_env, &"__home_object__".into(), Value::Object(home.clone()))?;
                }

                log::trace!("Bound 'this' to instance");

                // Execute method body
                log::trace!("Executing method body");
                return evaluate_statements(&func_env, body);
            }
            Value::Function(func_name) => {
                // Handle built-in functions on prototype (Object.prototype, Date.prototype, boxed primitives, etc.)
                // Evaluate args when needed
                // Note: handlers expect Expr args and env so pass them through
                if let Some(v) = crate::js_function::handle_receiver_builtin(func_name, obj_map, args, env)? {
                    return Ok(v);
                }
                if func_name.starts_with("Object.prototype.") || func_name == "Error.prototype.toString" {
                    if let Some(v) = crate::js_object::handle_object_prototype_builtin(func_name, obj_map, args, env)? {
                        return Ok(v);
                    }
                    if func_name == "Error.prototype.toString" {
                        return crate::js_object::handle_error_to_string_method(&Value::Object(obj_map.clone()), args);
                    }
                    return crate::js_function::handle_global_function(func_name, args, env);
                }

                return crate::js_function::handle_global_function(func_name, args, env);
            }
            _ => {
                log::warn!("Method is not a closure: {:?}", method_val.borrow());
            }
        }
    }
    // Other object methods not implemented
    Err(raise_eval_error!(format!("Method '{method}' not found on class instance")))
}

pub(crate) fn is_instance_of(obj: &JSObjectDataPtr, constructor: &JSObjectDataPtr) -> Result<bool, JSError> {
    // Get the prototype of the constructor
    if let Some(constructor_proto) = obj_get_key_value(constructor, &"prototype".into())? {
        log::trace!("is_instance_of: constructor.prototype raw = {:?}", constructor_proto);
        if let Value::Object(constructor_proto_obj) = &*constructor_proto.borrow() {
            // Walk the internal prototype chain directly (don't use obj_get_key_value for __proto__)
            let mut current_proto_opt: Option<JSObjectDataPtr> = obj.borrow().prototype.clone();
            log::trace!(
                "is_instance_of: starting internal current_proto = {:?}",
                current_proto_opt.as_ref().map(Rc::as_ptr)
            );
            while let Some(proto_obj) = current_proto_opt {
                log::trace!(
                    "is_instance_of: proto_obj={:p}, constructor_proto_obj={:p}",
                    Rc::as_ptr(&proto_obj),
                    Rc::as_ptr(constructor_proto_obj)
                );
                if Rc::ptr_eq(&proto_obj, constructor_proto_obj) {
                    return Ok(true);
                }
                current_proto_opt = proto_obj.borrow().prototype.clone();
            }
        }
    }
    Ok(false)
}

pub(crate) fn evaluate_super(env: &JSObjectDataPtr) -> Result<Value, JSError> {
    // super refers to the parent class prototype
    // We need to find it from the current class context
    if let Some(this_val) = obj_get_key_value(env, &"this".into())?
        && let Value::Object(instance) = &*this_val.borrow()
        && let Some(proto_val) = obj_get_key_value(instance, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        // Get the parent prototype from the current prototype's __proto__
        if let Some(parent_proto_val) = obj_get_key_value(proto_obj, &"__proto__".into())? {
            return Ok(parent_proto_val.borrow().clone());
        }
    }
    Err(raise_eval_error!("super can only be used in class methods or constructors"))
}

pub(crate) fn evaluate_super_call(env: &JSObjectDataPtr, args: &[Expr]) -> Result<Value, JSError> {
    // super() calls the parent constructor
    if let Some(this_val) = obj_get_key_value(env, &"this".into())?
        && let Value::Object(instance) = &*this_val.borrow()
        && let Some(proto_val) = obj_get_key_value(instance, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        // Get the parent prototype
        if let Some(parent_proto_val) = obj_get_key_value(proto_obj, &"__proto__".into())?
            && let Value::Object(parent_proto_obj) = &*parent_proto_val.borrow()
        {
            // Find the parent class constructor
            if let Some(parent_class_def_val) = obj_get_key_value(parent_proto_obj, &"__class_def__".into())?
                && let Value::ClassDefinition(ref parent_class_def) = *parent_class_def_val.borrow()
            {
                // Call parent constructor
                for member in &parent_class_def.members {
                    if let ClassMember::Constructor(params, body) = member {
                        // Collect all arguments, expanding spreads
                        let mut evaluated_args = Vec::new();
                        crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                        let func_env = prepare_function_call_env(
                            None,
                            Some(Value::Object(instance.clone())),
                            Some(params),
                            &evaluated_args,
                            None,
                            None,
                        )?;

                        // Execute parent constructor body
                        return evaluate_statements(&func_env, body);
                    }
                }
                return Ok(Value::Undefined);
            } else {
                // Fallback: Handle built-in constructors (like Error, Array, etc.)
                // parent_proto_obj is the prototype of the parent class (e.g. Error.prototype).
                // We need the constructor itself (e.g. Error).

                let parent_ctor_val = if let Some(ctor) = obj_get_key_value(parent_proto_obj, &"constructor".into())? {
                    ctor.borrow().clone()
                } else {
                    Value::Undefined
                };

                if let Value::Object(parent_ctor_obj) = parent_ctor_val {
                    let parent_ctor_expr = Expr::Value(Value::Object(parent_ctor_obj));
                    let new_instance_val = evaluate_new(env, &parent_ctor_expr, args)?;

                    if let Value::Object(new_instance) = new_instance_val {
                        // Fix up the prototype chain:
                        // The new instance has Parent.prototype.
                        // We want it to have the original instance's prototype (CurrentClass.prototype).
                        if let Some(original_proto) = obj_get_key_value(instance, &"__proto__".into())? {
                            obj_set_key_value(&new_instance, &"__proto__".into(), original_proto.borrow().clone())?;
                            if let Value::Object(proto_obj) = &*original_proto.borrow() {
                                new_instance.borrow_mut().prototype = Some(proto_obj.clone());
                            }
                        }

                        // Update 'this' in the current environment to point to the new instance
                        obj_set_key_value(env, &"this".into(), Value::Object(new_instance.clone()))?;

                        return Ok(Value::Object(new_instance));
                    }
                    return Ok(new_instance_val);
                }
                // If we can't find a constructor, we can't call super().
                return Err(raise_type_error!("super() failed: parent constructor not found"));
            }
        }
    }
    Err(raise_eval_error!("super() can only be called in class constructors"))
}

pub(crate) fn evaluate_super_property(env: &JSObjectDataPtr, prop: &str) -> Result<Value, JSError> {
    // super.property accesses parent class properties
    // Use [[HomeObject]] if available
    if let Some(home_obj_val) = obj_get_key_value(env, &"__home_object__".into())? {
        if let Value::Object(home_obj) = &*home_obj_val.borrow() {
            // Super is the prototype of HomeObject
            if let Some(super_obj) = &home_obj.borrow().prototype {
                // Look up property on super object
                if let Some(prop_val) = obj_get_key_value(super_obj, &prop.into())? {
                    return Ok(prop_val.borrow().clone());
                }
                return Ok(Value::Undefined);
            }
        }
    }

    // Fallback for legacy class implementation (if any)
    if let Some(this_val) = obj_get_key_value(env, &"this".into())?
        && let Value::Object(instance) = &*this_val.borrow()
        && let Some(proto_val) = obj_get_key_value(instance, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        // Get the parent prototype
        if let Some(parent_proto_val) = obj_get_key_value(proto_obj, &"__proto__".into())?
            && let Value::Object(parent_proto_obj) = &*parent_proto_val.borrow()
        {
            // Look for property in parent prototype
            if let Some(prop_val) = obj_get_key_value(parent_proto_obj, &prop.into())? {
                return Ok(prop_val.borrow().clone());
            }
        }
    }
    Err(raise_eval_error!(format!("Property '{prop}' not found in parent class")))
}

pub(crate) fn evaluate_super_method(env: &JSObjectDataPtr, method: &str, args: &[Expr]) -> Result<Value, JSError> {
    // super.method() calls parent class methods

    // Use [[HomeObject]] if available
    if let Some(home_obj_val) = obj_get_key_value(env, &"__home_object__".into())? {
        if let Value::Object(home_obj) = &*home_obj_val.borrow() {
            // Super is the prototype of HomeObject
            if let Some(super_obj) = &home_obj.borrow().prototype {
                // Log a concise debug line for super resolution (reduced verbosity)
                log::trace!(
                    "evaluate_super_method - home_ptr={:p} super_ptr={:p} method={}",
                    Rc::as_ptr(home_obj),
                    Rc::as_ptr(super_obj),
                    method
                );
                // Look up method on super object
                if let Some(method_val) = obj_get_key_value(super_obj, &method.into())? {
                    // Reduce verbosity: only log a short method type rather than full Value debug
                    let method_type = match &*method_val.borrow() {
                        Value::Closure(..) => "Closure",
                        Value::AsyncClosure(..) => "AsyncClosure",
                        Value::Function(_) => "Function",
                        Value::Object(_) => "Object",
                        _ => "Other",
                    };
                    log::trace!("evaluate_super_method - found method on super: method={method} type={method_type}");
                    // We need to call this method with the current 'this'
                    if let Some(this_val) = obj_get_key_value(env, &"this".into())? {
                        match &*method_val.borrow() {
                            Value::Closure(data) | Value::AsyncClosure(data) => {
                                let params = &data.params;
                                let body = &data.body;
                                let captured_env = &data.env;
                                let home_obj = data.home_object.borrow().clone();

                                // Collect all arguments, expanding spreads
                                let mut evaluated_args = Vec::new();
                                crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                                // Create function environment and bind params/this
                                let func_env = prepare_function_call_env(
                                    Some(captured_env),
                                    Some(this_val.borrow().clone()),
                                    Some(params),
                                    &evaluated_args,
                                    None,
                                    None,
                                )?;

                                if let Some(home) = home_obj {
                                    obj_set_key_value(&func_env, &"__home_object__".into(), Value::Object(home.clone()))?;
                                }

                                // Execute method body
                                return evaluate_statements(&func_env, body);
                            }
                            Value::Function(func_name) => {
                                if func_name == "Object.prototype.toString" {
                                    return crate::js_object::handle_to_string_method(&this_val.borrow().clone(), args, env);
                                }
                                if func_name == "Object.prototype.valueOf" {
                                    return crate::js_object::handle_value_of_method(&this_val.borrow().clone(), args, env);
                                }
                            }
                            Value::Object(func_obj) => {
                                if let Some(cl_rc) = obj_get_key_value(func_obj, &"__closure__".into())? {
                                    match &*cl_rc.borrow() {
                                        Value::Closure(data) | Value::AsyncClosure(data) => {
                                            let params = &data.params;
                                            let body = &data.body;
                                            let captured_env = &data.env;
                                            let home_obj = data.home_object.borrow().clone();

                                            // Collect all arguments, expanding spreads
                                            let mut evaluated_args = Vec::new();
                                            crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                                            // Create function environment and bind params/this
                                            let func_env = prepare_function_call_env(
                                                Some(captured_env),
                                                Some(this_val.borrow().clone()),
                                                Some(params),
                                                &evaluated_args,
                                                None,
                                                None,
                                            )?;

                                            if let Some(home) = home_obj {
                                                obj_set_key_value(&func_env, &"__home_object__".into(), Value::Object(home.clone()))?;
                                            }

                                            // Execute method body
                                            return evaluate_statements(&func_env, body);
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    // Fallback for legacy class implementation (if any)
    if let Some(this_val) = obj_get_key_value(env, &"this".into())?
        && let Value::Object(instance) = &*this_val.borrow()
        && let Some(proto_val) = obj_get_key_value(instance, &"__proto__".into())?
        && let Value::Object(proto_obj) = &*proto_val.borrow()
    {
        // Get the parent prototype
        if let Some(parent_proto_val) = obj_get_key_value(proto_obj, &"__proto__".into())?
            && let Value::Object(parent_proto_obj) = &*parent_proto_val.borrow()
        {
            // Look for method in parent prototype
            if let Some(method_val) = obj_get_key_value(parent_proto_obj, &method.into())? {
                match &*method_val.borrow() {
                    Value::Closure(data) | Value::AsyncClosure(data) => {
                        let params = &data.params;
                        let body = &data.body;
                        let captured_env = &data.env;

                        // Collect all arguments, expanding spreads
                        let mut evaluated_args = Vec::new();
                        crate::core::expand_spread_in_call_args(env, args, &mut evaluated_args)?;

                        // Create function environment with 'this' bound to the instance and bind params
                        let func_env = prepare_function_call_env(
                            Some(captured_env),
                            Some(Value::Object(instance.clone())),
                            Some(params),
                            &evaluated_args,
                            None,
                            None,
                        )?;

                        // Execute method body
                        return evaluate_statements(&func_env, body);
                    }
                    _ => {
                        return Err(raise_eval_error!(format!("'{method}' is not a method in parent class")));
                    }
                }
            }
        }
    }
    Err(raise_eval_error!(format!("Method '{method}' not found in parent class")))
}

/// Handle Object constructor calls
pub(crate) fn handle_object_constructor(args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    if args.is_empty() {
        // Object() - create empty object
        let obj = new_js_object_data();
        return Ok(Value::Object(obj));
    }
    // Object(value) - convert value to object
    let arg_val = evaluate_expr(env, &args[0])?;
    match arg_val {
        Value::Undefined => {
            // Object(undefined) creates empty object
            let obj = new_js_object_data();
            Ok(Value::Object(obj))
        }
        Value::Object(obj) => {
            // Object(object) returns the object itself
            Ok(Value::Object(obj))
        }
        Value::Number(n) => {
            // Object(number) creates Number object
            let obj = new_js_object_data();
            obj_set_key_value(&obj, &"valueOf".into(), Value::Function("Number_valueOf".to_string()))?;
            obj_set_key_value(&obj, &"toString".into(), Value::Function("Number_toString".to_string()))?;
            obj_set_key_value(&obj, &"__value__".into(), Value::Number(n))?;
            // Set internal prototype to Number.prototype if available
            crate::core::set_internal_prototype_from_constructor(&obj, env, "Number")?;
            Ok(Value::Object(obj))
        }
        Value::Boolean(b) => {
            // Object(boolean) creates Boolean object
            let obj = new_js_object_data();
            obj_set_key_value(&obj, &"valueOf".into(), Value::Function("Boolean_valueOf".to_string()))?;
            obj_set_key_value(&obj, &"toString".into(), Value::Function("Boolean_toString".to_string()))?;
            obj_set_key_value(&obj, &"__value__".into(), Value::Boolean(b))?;
            // Set internal prototype to Boolean.prototype if available
            crate::core::set_internal_prototype_from_constructor(&obj, env, "Boolean")?;
            Ok(Value::Object(obj))
        }
        Value::String(s) => {
            // Object(string) creates String object
            let obj = new_js_object_data();
            obj_set_key_value(&obj, &"valueOf".into(), Value::Function("String_valueOf".to_string()))?;
            obj_set_key_value(&obj, &"toString".into(), Value::Function("String_toString".to_string()))?;
            obj_set_key_value(&obj, &"length".into(), Value::Number(s.len() as f64))?;
            obj_set_key_value(&obj, &"__value__".into(), Value::String(s))?;
            // Set internal prototype to String.prototype if available
            crate::core::set_internal_prototype_from_constructor(&obj, env, "String")?;
            Ok(Value::Object(obj))
        }
        Value::BigInt(h) => {
            // Object(bigint) creates a boxed BigInt-like object
            let obj = new_js_object_data();
            obj_set_key_value(&obj, &"valueOf".into(), Value::Function("BigInt_valueOf".to_string()))?;
            obj_set_key_value(&obj, &"toString".into(), Value::Function("BigInt_toString".to_string()))?;
            obj_set_key_value(&obj, &"__value__".into(), Value::BigInt(h.clone()))?;
            // Set internal prototype to BigInt.prototype if available
            crate::core::set_internal_prototype_from_constructor(&obj, env, "BigInt")?;
            Ok(Value::Object(obj))
        }
        Value::Symbol(sd) => {
            // Object(symbol) creates Symbol object
            let obj = new_js_object_data();
            obj_set_key_value(&obj, &"valueOf".into(), Value::Function("Symbol_valueOf".to_string()))?;
            obj_set_key_value(&obj, &"toString".into(), Value::Function("Symbol_toString".to_string()))?;
            obj_set_key_value(&obj, &"__value__".into(), Value::Symbol(sd.clone()))?;
            // Set internal prototype to Symbol.prototype if available
            crate::core::set_internal_prototype_from_constructor(&obj, env, "Symbol")?;
            Ok(Value::Object(obj))
        }
        _ => {
            // For other types, return empty object
            let obj = new_js_object_data();
            Ok(Value::Object(obj))
        }
    }
}

/// Handle Number constructor calls
pub(crate) fn handle_number_constructor(args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let num_val = if args.is_empty() {
        // Number() - returns 0
        0.0
    } else {
        // Number(value) - convert value to number
        let arg_val = evaluate_expr(env, &args[0])?;
        match arg_val {
            Value::Number(n) => n,
            Value::String(s) => {
                let str_val = String::from_utf16_lossy(&s);
                str_val.trim().parse::<f64>().unwrap_or(f64::NAN)
            }
            Value::Boolean(b) => {
                if b {
                    1.0
                } else {
                    0.0
                }
            }
            Value::Undefined => f64::NAN,
            Value::Object(_) => f64::NAN,
            _ => f64::NAN,
        }
    };

    // Create Number object
    let obj = new_js_object_data();
    obj_set_key_value(&obj, &"valueOf".into(), Value::Function("Number_valueOf".to_string()))?;
    obj_set_key_value(&obj, &"toString".into(), Value::Function("Number_toString".to_string()))?;
    obj_set_key_value(&obj, &"__value__".into(), Value::Number(num_val))?;
    // Set internal prototype to Number.prototype if available
    crate::core::set_internal_prototype_from_constructor(&obj, env, "Number")?;
    Ok(Value::Object(obj))
}

/// Handle Boolean constructor calls
pub(crate) fn handle_boolean_constructor(args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let bool_val = if args.is_empty() {
        // Boolean() - returns false
        false
    } else {
        // Boolean(value) - convert value to boolean
        let arg_val = evaluate_expr(env, &args[0])?;
        match arg_val {
            Value::Boolean(b) => b,
            Value::Number(n) => n != 0.0 && !n.is_nan(),
            Value::String(s) => !s.is_empty(),
            Value::Undefined => false,
            Value::Object(_) => true,
            _ => false,
        }
    };

    // Create Boolean object
    let obj = new_js_object_data();
    obj_set_key_value(&obj, &"valueOf".into(), Value::Function("Boolean_valueOf".to_string()))?;
    obj_set_key_value(&obj, &"toString".into(), Value::Function("Boolean_toString".to_string()))?;
    obj_set_key_value(&obj, &"__value__".into(), Value::Boolean(bool_val))?;
    // Set internal prototype to Boolean.prototype if available
    crate::core::set_internal_prototype_from_constructor(&obj, env, "Boolean")?;
    Ok(Value::Object(obj))
}

pub(crate) fn boolean_prototype_to_string(_args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let this_val = evaluate_this(env)?;
    match this_val {
        Value::Boolean(b) => Ok(Value::String(utf8_to_utf16(&b.to_string()))),
        Value::Object(obj) => {
            if let Some(val) = obj_get_key_value(&obj, &"__value__".into())? {
                if let Value::Boolean(b) = *val.borrow() {
                    return Ok(Value::String(utf8_to_utf16(&b.to_string())));
                }
            }
            Err(raise_type_error!("Boolean.prototype.toString requires that 'this' be a Boolean"))
        }
        _ => Err(raise_type_error!("Boolean.prototype.toString requires that 'this' be a Boolean")),
    }
}

pub(crate) fn boolean_prototype_value_of(_args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let this_val = evaluate_this(env)?;
    match this_val {
        Value::Boolean(b) => Ok(Value::Boolean(b)),
        Value::Object(obj) => {
            if let Some(val) = obj_get_key_value(&obj, &"__value__".into())? {
                if let Value::Boolean(b) = *val.borrow() {
                    return Ok(Value::Boolean(b));
                }
            }
            Err(raise_type_error!("Boolean.prototype.valueOf requires that 'this' be a Boolean"))
        }
        _ => Err(raise_type_error!("Boolean.prototype.valueOf requires that 'this' be a Boolean")),
    }
}

/// Handle String constructor calls
pub(crate) fn handle_string_constructor(args: &[Expr], env: &JSObjectDataPtr) -> Result<Value, JSError> {
    let str_val = if args.is_empty() {
        // String() - returns empty string
        Vec::new()
    } else {
        // String(value) - convert value to string
        let arg_val = evaluate_expr(env, &args[0])?;
        match arg_val {
            Value::String(s) => s.clone(),
            Value::Number(n) => utf8_to_utf16(&n.to_string()),
            Value::Boolean(b) => utf8_to_utf16(&b.to_string()),
            Value::Undefined => utf8_to_utf16("undefined"),
            Value::Null => utf8_to_utf16("null"),
            Value::Object(_) => utf8_to_utf16("[object Object]"),
            Value::Function(name) => utf8_to_utf16(&format!("[Function: {}]", name)),
            Value::Closure(..) | Value::AsyncClosure(..) => utf8_to_utf16("[Function]"),
            Value::ClassDefinition(_) => utf8_to_utf16("[Class]"),
            Value::Getter(..) => utf8_to_utf16("[Getter]"),
            Value::Setter(..) => utf8_to_utf16("[Setter]"),
            Value::Property { .. } => utf8_to_utf16("[Property]"),
            Value::Promise(_) => utf8_to_utf16("[object Promise]"),
            Value::Symbol(_) => utf8_to_utf16("[object Symbol]"),
            Value::BigInt(s) => utf8_to_utf16(&s.to_string()),
            Value::Map(_) => utf8_to_utf16("[object Map]"),
            Value::Set(_) => utf8_to_utf16("[object Set]"),
            Value::WeakMap(_) => utf8_to_utf16("[object WeakMap]"),
            Value::WeakSet(_) => utf8_to_utf16("[object WeakSet]"),
            Value::GeneratorFunction(..) => utf8_to_utf16("[GeneratorFunction]"),
            Value::Generator(_) => utf8_to_utf16("[object Generator]"),
            Value::Proxy(_) => utf8_to_utf16("[object Proxy]"),
            Value::ArrayBuffer(_) => utf8_to_utf16("[object ArrayBuffer]"),
            Value::DataView(_) => utf8_to_utf16("[object DataView]"),
            Value::TypedArray(_) => utf8_to_utf16("[object TypedArray]"),
            Value::Uninitialized => utf8_to_utf16("undefined"),
        }
    };

    // Create String object
    let obj = new_js_object_data();
    obj_set_key_value(&obj, &"valueOf".into(), Value::Function("String_valueOf".to_string()))?;
    obj_set_key_value(&obj, &"toString".into(), Value::Function("String_toString".to_string()))?;
    obj_set_key_value(&obj, &"length".into(), Value::Number(str_val.len() as f64))?;
    obj_set_key_value(&obj, &"__value__".into(), Value::String(str_val))?;
    // Set internal prototype to String.prototype if available
    crate::core::set_internal_prototype_from_constructor(&obj, env, "String")?;
    Ok(Value::Object(obj))
}