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
//! Boa's implementation of ECMAScript's global `Proxy` object.
//!
//! The `Proxy` object enables you to create a proxy for another object,
//! which can intercept and redefine fundamental operations for that object.
//!
//! More information:
//!  - [ECMAScript reference][spec]
//!  - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-proxy-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

use crate::{
    builtins::{array, BuiltInObject},
    context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
    error::JsNativeError,
    js_string,
    native_function::NativeFunction,
    object::{
        internal_methods::{
            is_compatible_property_descriptor, CallValue, InternalMethodContext,
            InternalObjectMethods, ORDINARY_INTERNAL_METHODS,
        },
        shape::slot::SlotAttributes,
        JsData, JsFunction, JsObject, JsPrototype,
    },
    property::{PropertyDescriptor, PropertyKey},
    realm::Realm,
    string::{common::StaticJsStrings, utf16},
    value::Type,
    Context, JsArgs, JsResult, JsString, JsValue,
};
use boa_gc::{Finalize, GcRefCell, Trace};
use boa_profiler::Profiler;
use rustc_hash::FxHashSet;

use super::{BuiltInBuilder, BuiltInConstructor, IntrinsicObject, OrdinaryObject};
/// Javascript `Proxy` object.
#[derive(Debug, Clone, Trace, Finalize)]
pub struct Proxy {
    // (target, handler)
    data: Option<(JsObject, JsObject)>,
}

impl JsData for Proxy {
    fn internal_methods(&self) -> &'static InternalObjectMethods {
        static BASIC: InternalObjectMethods = InternalObjectMethods {
            __get_prototype_of__: proxy_exotic_get_prototype_of,
            __set_prototype_of__: proxy_exotic_set_prototype_of,
            __is_extensible__: proxy_exotic_is_extensible,
            __prevent_extensions__: proxy_exotic_prevent_extensions,
            __get_own_property__: proxy_exotic_get_own_property,
            __define_own_property__: proxy_exotic_define_own_property,
            __has_property__: proxy_exotic_has_property,
            __get__: proxy_exotic_get,
            __set__: proxy_exotic_set,
            __delete__: proxy_exotic_delete,
            __own_property_keys__: proxy_exotic_own_property_keys,
            ..ORDINARY_INTERNAL_METHODS
        };

        static CALLABLE: InternalObjectMethods = InternalObjectMethods {
            __call__: proxy_exotic_call,
            ..BASIC
        };

        static CONSTRUCTOR: InternalObjectMethods = InternalObjectMethods {
            __call__: proxy_exotic_call,
            __construct__: proxy_exotic_construct,
            ..BASIC
        };

        let Some(data) = &self.data else {
            return &BASIC;
        };

        if data.0.is_constructor() {
            &CONSTRUCTOR
        } else if data.0.is_callable() {
            &CALLABLE
        } else {
            &BASIC
        }
    }
}

impl IntrinsicObject for Proxy {
    fn init(realm: &Realm) {
        let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init");

        BuiltInBuilder::from_standard_constructor::<Self>(realm)
            .static_method(Self::revocable, js_string!("revocable"), 2)
            .build_without_prototype();
    }

    fn get(intrinsics: &Intrinsics) -> JsObject {
        Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
    }
}

impl BuiltInObject for Proxy {
    const NAME: JsString = StaticJsStrings::PROXY;
}

impl BuiltInConstructor for Proxy {
    const LENGTH: usize = 2;

    const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
        StandardConstructors::proxy;

    /// `28.2.1.1 Proxy ( target, handler )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-proxy-target-handler
    fn constructor(
        new_target: &JsValue,
        args: &[JsValue],
        context: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. If NewTarget is undefined, throw a TypeError exception.
        if new_target.is_undefined() {
            return Err(JsNativeError::typ()
                .with_message("Proxy constructor called on undefined new target")
                .into());
        }

        // 2. Return ? ProxyCreate(target, handler).
        Self::create(args.get_or_undefined(0), args.get_or_undefined(1), context).map(JsValue::from)
    }
}

impl Proxy {
    pub(crate) fn new(target: JsObject, handler: JsObject) -> Self {
        Self {
            data: Some((target, handler)),
        }
    }

    /// This is an internal method only built for usage in the proxy internal methods.
    ///
    /// It returns the (target, handler) of the proxy.
    pub(crate) fn try_data(&self) -> JsResult<(JsObject, JsObject)> {
        self.data.clone().ok_or_else(|| {
            JsNativeError::typ()
                .with_message("Proxy object has empty handler and target")
                .into()
        })
    }

    // `10.5.14 ProxyCreate ( target, handler )`
    //
    // More information:
    //  - [ECMAScript reference][spec]
    //
    // [spec]: https://tc39.es/ecma262/#sec-proxycreate
    pub(crate) fn create(
        target: &JsValue,
        handler: &JsValue,
        context: &mut Context,
    ) -> JsResult<JsObject> {
        // 1. If Type(target) is not Object, throw a TypeError exception.
        let target = target.as_object().ok_or_else(|| {
            JsNativeError::typ().with_message("Proxy constructor called with non-object target")
        })?;

        // 2. If Type(handler) is not Object, throw a TypeError exception.
        let handler = handler.as_object().ok_or_else(|| {
            JsNativeError::typ().with_message("Proxy constructor called with non-object handler")
        })?;

        // 3. Let P be ! MakeBasicObject(« [[ProxyHandler]], [[ProxyTarget]] »).
        // 4. Set P's essential internal methods, except for [[Call]] and [[Construct]], to the definitions specified in 10.5.
        // 5. If IsCallable(target) is true, then
        // a. Set P.[[Call]] as specified in 10.5.12.
        // b. If IsConstructor(target) is true, then
        // i. Set P.[[Construct]] as specified in 10.5.13.
        // 6. Set P.[[ProxyTarget]] to target.
        // 7. Set P.[[ProxyHandler]] to handler.
        let p = JsObject::from_proto_and_data_with_shared_shape(
            context.root_shape(),
            context.intrinsics().constructors().object().prototype(),
            Self::new(target.clone(), handler.clone()),
        );

        // 8. Return P.
        Ok(p)
    }

    pub(crate) fn revoker(proxy: JsObject, context: &mut Context) -> JsFunction {
        // 3. Let revoker be ! CreateBuiltinFunction(revokerClosure, 0, "", « [[RevocableProxy]] »).
        // 4. Set revoker.[[RevocableProxy]] to p.

        NativeFunction::from_copy_closure_with_captures(
            |_, _, revocable_proxy, _| {
                // a. Let F be the active function object.
                // b. Let p be F.[[RevocableProxy]].
                // d. Set F.[[RevocableProxy]] to null.
                if let Some(p) = std::mem::take(&mut *revocable_proxy.borrow_mut()) {
                    // e. Assert: p is a Proxy object.
                    // f. Set p.[[ProxyTarget]] to null.
                    // g. Set p.[[ProxyHandler]] to null.
                    p.downcast_mut::<Proxy>()
                        .expect("[[RevocableProxy]] must be a proxy object")
                        .data = None;
                }

                // c. If p is null, return undefined.
                // h. Return undefined.
                Ok(JsValue::undefined())
            },
            GcRefCell::new(Some(proxy)),
        )
        .to_js_function(context.realm())
    }

    /// `28.2.2.1 Proxy.revocable ( target, handler )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-proxy.revocable
    fn revocable(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
        // 1. Let p be ? ProxyCreate(target, handler).
        let p = Self::create(args.get_or_undefined(0), args.get_or_undefined(1), context)?;

        // Revoker creation steps on `Proxy::revoker`
        let revoker = Self::revoker(p.clone(), context);

        // 5. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
        let result = JsObject::with_object_proto(context.intrinsics());

        // 6. Perform ! CreateDataPropertyOrThrow(result, "proxy", p).
        result
            .create_data_property_or_throw(utf16!("proxy"), p, context)
            .expect("CreateDataPropertyOrThrow cannot fail here");

        // 7. Perform ! CreateDataPropertyOrThrow(result, "revoke", revoker).
        result
            .create_data_property_or_throw(utf16!("revoke"), revoker, context)
            .expect("CreateDataPropertyOrThrow cannot fail here");

        // 8. Return result.
        Ok(result.into())
    }
}

/// `10.5.1 [[GetPrototypeOf]] ( )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof
pub(crate) fn proxy_exotic_get_prototype_of(
    obj: &JsObject,
    context: &mut Context,
) -> JsResult<JsPrototype> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "getPrototypeOf").
    let Some(trap) = handler.get_method(utf16!("getPrototypeOf"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[GetPrototypeOf]]().
        return target.__get_prototype_of__(context);
    };

    // 7. Let handlerProto be ? Call(trap, handler, « target »).
    let handler_proto = trap.call(&handler.into(), &[target.clone().into()], context)?;

    // 8. If Type(handlerProto) is neither Object nor Null, throw a TypeError exception.
    let handler_proto = match &handler_proto {
        JsValue::Object(obj) => Some(obj.clone()),
        JsValue::Null => None,
        _ => {
            return Err(JsNativeError::typ()
                .with_message("Proxy trap result is neither object nor null")
                .into())
        }
    };

    // 9. Let extensibleTarget be ? IsExtensible(target).
    // 10. If extensibleTarget is true, return handlerProto.
    if target.is_extensible(context)? {
        return Ok(handler_proto);
    }

    // 11. Let targetProto be ? target.[[GetPrototypeOf]]().
    let target_proto = target.__get_prototype_of__(context)?;

    // 12. If SameValue(handlerProto, targetProto) is false, throw a TypeError exception.
    if handler_proto != target_proto {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap returned unexpected prototype")
            .into());
    }

    // 13. Return handlerProto.
    Ok(handler_proto)
}

/// `10.5.2 [[SetPrototypeOf]] ( V )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v
pub(crate) fn proxy_exotic_set_prototype_of(
    obj: &JsObject,
    val: JsPrototype,
    context: &mut Context,
) -> JsResult<bool> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "setPrototypeOf").
    let Some(trap) = handler.get_method(utf16!("setPrototypeOf"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[SetPrototypeOf]](V).
        return target.__set_prototype_of__(val, context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, V »)).
    // 8. If booleanTrapResult is false, return false.
    if !trap
        .call(
            &handler.into(),
            &[
                target.clone().into(),
                val.clone().map_or(JsValue::Null, Into::into),
            ],
            context,
        )?
        .to_boolean()
    {
        return Ok(false);
    }

    // 9. Let extensibleTarget be ? IsExtensible(target).
    // 10. If extensibleTarget is true, return true.
    if target.is_extensible(context)? {
        return Ok(true);
    }

    // 11. Let targetProto be ? target.[[GetPrototypeOf]]().
    let target_proto = target.__get_prototype_of__(context)?;

    // 12. If SameValue(V, targetProto) is false, throw a TypeError exception.
    if val != target_proto {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap failed to set prototype")
            .into());
    }

    // 13. Return true.
    Ok(true)
}

/// `10.5.3 [[IsExtensible]] ( )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-isextensible
pub(crate) fn proxy_exotic_is_extensible(obj: &JsObject, context: &mut Context) -> JsResult<bool> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "isExtensible").
    let Some(trap) = handler.get_method(utf16!("isExtensible"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? IsExtensible(target).
        return target.is_extensible(context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target »)).
    let boolean_trap_result = trap
        .call(&handler.into(), &[target.clone().into()], context)?
        .to_boolean();

    // 8. Let targetResult be ? IsExtensible(target).
    let target_result = target.is_extensible(context)?;

    // 9. If SameValue(booleanTrapResult, targetResult) is false, throw a TypeError exception.
    if boolean_trap_result != target_result {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap returned unexpected extensible value")
            .into());
    }

    // 10. Return booleanTrapResult.
    Ok(boolean_trap_result)
}

/// `10.5.4 [[PreventExtensions]] ( )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-preventextensions
pub(crate) fn proxy_exotic_prevent_extensions(
    obj: &JsObject,
    context: &mut Context,
) -> JsResult<bool> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "preventExtensions").
    let Some(trap) = handler.get_method(utf16!("preventExtensions"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[PreventExtensions]]().
        return target.__prevent_extensions__(context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target »)).
    let boolean_trap_result = trap
        .call(&handler.into(), &[target.clone().into()], context)?
        .to_boolean();

    // 8. If booleanTrapResult is true, then
    if boolean_trap_result && target.is_extensible(context)? {
        // a. Let extensibleTarget be ? IsExtensible(target).
        // b. If extensibleTarget is true, throw a TypeError exception.
        return Err(JsNativeError::typ()
            .with_message("Proxy trap failed to set extensible")
            .into());
    }

    // 9. Return booleanTrapResult.
    Ok(boolean_trap_result)
}

/// `10.5.5 [[GetOwnProperty]] ( P )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p
pub(crate) fn proxy_exotic_get_own_property(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<Option<PropertyDescriptor>> {
    context.slot().attributes |= SlotAttributes::NOT_CACHABLE;

    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor").
    let Some(trap) = handler.get_method(utf16!("getOwnPropertyDescriptor"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[GetOwnProperty]](P).
        return target.__get_own_property__(key, context);
    };

    // 7. Let trapResultObj be ? Call(trap, handler, « target, P »).
    let trap_result_obj = trap.call(
        &handler.into(),
        &[target.clone().into(), key.clone().into()],
        context,
    )?;

    // 8. If Type(trapResultObj) is neither Object nor Undefined, throw a TypeError exception.
    if !trap_result_obj.is_object() && !trap_result_obj.is_undefined() {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap result is neither object nor undefined")
            .into());
    }

    // 9. Let targetDesc be ? target.[[GetOwnProperty]](P).
    let target_desc = target.__get_own_property__(key, context)?;

    // 10. If trapResultObj is undefined, then
    if trap_result_obj.is_undefined() {
        if let Some(desc) = target_desc {
            // b. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
            if !desc.expect_configurable() {
                return Err(JsNativeError::typ()
                    .with_message(
                        "Proxy trap result is undefined adn target result is not configurable",
                    )
                    .into());
            }

            // c. Let extensibleTarget be ? IsExtensible(target).
            // d. If extensibleTarget is false, throw a TypeError exception.
            if !target.is_extensible(context)? {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap result is undefined and target is not extensible")
                    .into());
            }
            // e. Return undefined.
            return Ok(None);
        }

        // a. If targetDesc is undefined, return undefined.
        return Ok(None);
    }

    // 11. Let extensibleTarget be ? IsExtensible(target).
    let extensible_target = target.is_extensible(context)?;

    // 12. Let resultDesc be ? ToPropertyDescriptor(trapResultObj).
    let result_desc = trap_result_obj.to_property_descriptor(context)?;

    // 13. Call CompletePropertyDescriptor(resultDesc).
    let result_desc = result_desc.complete_property_descriptor();

    // 14. Let valid be IsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc).
    // 15. If valid is false, throw a TypeError exception.
    if !is_compatible_property_descriptor(
        extensible_target,
        result_desc.clone(),
        target_desc.clone(),
    ) {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap returned unexpected property")
            .into());
    }

    // 16. If resultDesc.[[Configurable]] is false, then
    if !result_desc.expect_configurable() {
        // a. If targetDesc is undefined or targetDesc.[[Configurable]] is true, then
        match &target_desc {
            Some(desc) if !desc.expect_configurable() => {
                // b. If resultDesc has a [[Writable]] field and resultDesc.[[Writable]] is false, then
                if result_desc.writable() == Some(false) {
                    // i. If targetDesc.[[Writable]] is true, throw a TypeError exception.
                    if desc.expect_writable() {
                        return
                            Err(JsNativeError::typ().with_message("Proxy trap result is writable and not configurable while target result is not configurable").into())
                        ;
                    }
                }
            }
            // i. Throw a TypeError exception.
            _ => {
                return Err(JsNativeError::typ()
                    .with_message(
                        "Proxy trap result is not configurable and target result is undefined",
                    )
                    .into())
            }
        }
    }

    // 17. Return resultDesc.
    Ok(Some(result_desc))
}

/// `10.5.6 [[DefineOwnProperty]] ( P, Desc )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc
pub(crate) fn proxy_exotic_define_own_property(
    obj: &JsObject,
    key: &PropertyKey,
    desc: PropertyDescriptor,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<bool> {
    context.slot().attributes |= SlotAttributes::NOT_CACHABLE;

    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "defineProperty").
    let Some(trap) = handler.get_method(utf16!("defineProperty"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[DefineOwnProperty]](P, Desc).
        return target.__define_own_property__(key, desc, context);
    };

    // 7. Let descObj be FromPropertyDescriptor(Desc).
    let desc_obj = OrdinaryObject::from_property_descriptor(Some(desc.clone()), context);

    // 8. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P, descObj »)).
    // 9. If booleanTrapResult is false, return false.
    if !trap
        .call(
            &handler.into(),
            &[target.clone().into(), key.clone().into(), desc_obj],
            context,
        )?
        .to_boolean()
    {
        return Ok(false);
    }

    // 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
    let target_desc = target.__get_own_property__(key, context)?;

    // 11. Let extensibleTarget be ? IsExtensible(target).
    let extensible_target = target.is_extensible(context)?;

    // 12. If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is false, then
    let setting_config_false = matches!(desc.configurable(), Some(false));

    match target_desc {
        // 14. If targetDesc is undefined, then
        None => {
            // a. If extensibleTarget is false, throw a TypeError exception.
            if !extensible_target {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap failed to set property")
                    .into());
            }

            // b. If settingConfigFalse is true, throw a TypeError exception.
            if setting_config_false {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap failed to set property")
                    .into());
            }
        }
        // 15. Else,
        Some(target_desc) => {
            // a. If IsCompatiblePropertyDescriptor(extensibleTarget, Desc, targetDesc) is false, throw a TypeError exception.
            if !is_compatible_property_descriptor(
                extensible_target,
                desc.clone(),
                Some(target_desc.clone()),
            ) {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap set property to unexpected value")
                    .into());
            }

            // b. If settingConfigFalse is true and targetDesc.[[Configurable]] is true, throw a TypeError exception.
            if setting_config_false && target_desc.expect_configurable() {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap set property with unexpected configurable field")
                    .into());
            }

            // c. If IsDataDescriptor(targetDesc) is true, targetDesc.[[Configurable]] is false, and targetDesc.[[Writable]] is true, then
            if target_desc.is_data_descriptor()
                && !target_desc.expect_configurable()
                && target_desc.expect_writable()
            {
                // i. If Desc has a [[Writable]] field and Desc.[[Writable]] is false, throw a TypeError exception.
                if let Some(writable) = desc.writable() {
                    if !writable {
                        return Err(JsNativeError::typ()
                            .with_message("Proxy trap set property with unexpected writable field")
                            .into());
                    }
                }
            }
        }
    }

    // 16. Return true.
    Ok(true)
}

/// `10.5.7 [[HasProperty]] ( P )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p
pub(crate) fn proxy_exotic_has_property(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<bool> {
    context.slot().attributes |= SlotAttributes::NOT_CACHABLE;

    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "has").
    let Some(trap) = handler.get_method(utf16!("has"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[HasProperty]](P).
        return target.has_property(key.clone(), context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P »)).
    let boolean_trap_result = trap
        .call(
            &handler.into(),
            &[target.clone().into(), key.clone().into()],
            context,
        )?
        .to_boolean();

    // 8. If booleanTrapResult is false, then
    if !boolean_trap_result {
        // a. Let targetDesc be ? target.[[GetOwnProperty]](P).
        let target_desc = target.__get_own_property__(key, context)?;

        // b. If targetDesc is not undefined, then
        if let Some(target_desc) = target_desc {
            // i. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
            if !target_desc.expect_configurable() {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap returned unexpected property")
                    .into());
            }

            // ii. Let extensibleTarget be ? IsExtensible(target).
            // iii. If extensibleTarget is false, throw a TypeError exception.
            if !target.is_extensible(context)? {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap returned unexpected property")
                    .into());
            }
        }
    }

    // 9. Return booleanTrapResult.
    Ok(boolean_trap_result)
}

/// `10.5.8 [[Get]] ( P, Receiver )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
pub(crate) fn proxy_exotic_get(
    obj: &JsObject,
    key: &PropertyKey,
    receiver: JsValue,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<JsValue> {
    // Proxy object can't be cached.
    context.slot().attributes |= SlotAttributes::NOT_CACHABLE;

    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "get").
    let Some(trap) = handler.get_method(utf16!("get"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[Get]](P, Receiver).
        return target.__get__(key, receiver, context);
    };

    // 7. Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
    let trap_result = trap.call(
        &handler.into(),
        &[target.clone().into(), key.clone().into(), receiver],
        context,
    )?;

    // 8. Let targetDesc be ? target.[[GetOwnProperty]](P).
    let target_desc = target.__get_own_property__(key, context)?;

    // 9. If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
    if let Some(target_desc) = target_desc {
        if !target_desc.expect_configurable() {
            // a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
            if target_desc.is_data_descriptor() && !target_desc.expect_writable() {
                // i. If SameValue(trapResult, targetDesc.[[Value]]) is false, throw a TypeError exception.
                if !JsValue::same_value(&trap_result, target_desc.expect_value()) {
                    return Err(JsNativeError::typ()
                        .with_message("Proxy trap returned unexpected data descriptor")
                        .into());
                }
            }

            // b. If IsAccessorDescriptor(targetDesc) is true and targetDesc.[[Get]] is undefined, then
            if target_desc.is_accessor_descriptor() && target_desc.expect_get().is_undefined() {
                // i. If trapResult is not undefined, throw a TypeError exception.
                if !trap_result.is_undefined() {
                    return Err(JsNativeError::typ()
                        .with_message("Proxy trap returned unexpected accessor descriptor")
                        .into());
                }
            }
        }
    }

    // 10. Return trapResult.
    Ok(trap_result)
}

/// `10.5.9 [[Set]] ( P, V, Receiver )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver
pub(crate) fn proxy_exotic_set(
    obj: &JsObject,
    key: PropertyKey,
    value: JsValue,
    receiver: JsValue,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<bool> {
    context.slot().attributes |= SlotAttributes::NOT_CACHABLE;

    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "set").
    let Some(trap) = handler.get_method(utf16!("set"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[Set]](P, V, Receiver).
        return target.__set__(key, value, receiver, context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P, V, Receiver »)).
    // 8. If booleanTrapResult is false, return false.
    if !trap
        .call(
            &handler.into(),
            &[
                target.clone().into(),
                key.clone().into(),
                value.clone(),
                receiver,
            ],
            context,
        )?
        .to_boolean()
    {
        return Ok(false);
    }

    // 9. Let targetDesc be ? target.[[GetOwnProperty]](P).
    let target_desc = target.__get_own_property__(&key, context)?;

    // 10. If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
    if let Some(target_desc) = target_desc {
        if !target_desc.expect_configurable() {
            // a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
            if target_desc.is_data_descriptor() && !target_desc.expect_writable() {
                // i. If SameValue(V, targetDesc.[[Value]]) is false, throw a TypeError exception.
                if !JsValue::same_value(&value, target_desc.expect_value()) {
                    return Err(JsNativeError::typ()
                        .with_message("Proxy trap set unexpected data descriptor")
                        .into());
                }
            }

            // b. If IsAccessorDescriptor(targetDesc) is true, then
            if target_desc.is_accessor_descriptor() {
                // i. If targetDesc.[[Set]] is undefined, throw a TypeError exception.
                match target_desc.set() {
                    None | Some(&JsValue::Undefined) => {
                        return Err(JsNativeError::typ()
                            .with_message("Proxy trap set unexpected accessor descriptor")
                            .into());
                    }
                    _ => {}
                }
            }
        }
    }

    // 11. Return true.
    Ok(true)
}

/// `10.5.10 [[Delete]] ( P )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-delete-p
pub(crate) fn proxy_exotic_delete(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut InternalMethodContext<'_>,
) -> JsResult<bool> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "deleteProperty").
    let Some(trap) = handler.get_method(utf16!("deleteProperty"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[Delete]](P).
        return target.__delete__(key, context);
    };

    // 7. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P »)).
    // 8. If booleanTrapResult is false, return false.
    if !trap
        .call(
            &handler.into(),
            &[target.clone().into(), key.clone().into()],
            context,
        )?
        .to_boolean()
    {
        return Ok(false);
    }

    // 9. Let targetDesc be ? target.[[GetOwnProperty]](P).
    match target.__get_own_property__(key, context)? {
        // 10. If targetDesc is undefined, return true.
        None => return Ok(true),
        // 11. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
        Some(target_desc) => {
            if !target_desc.expect_configurable() {
                return Err(JsNativeError::typ()
                    .with_message("Proxy trap failed to delete property")
                    .into());
            }
        }
    }

    // 12. Let extensibleTarget be ? IsExtensible(target).
    // 13. If extensibleTarget is false, throw a TypeError exception.
    if !target.is_extensible(context)? {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap failed to delete property")
            .into());
    }

    // 14. Return true.
    Ok(true)
}

/// `10.5.11 [[OwnPropertyKeys]] ( )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
pub(crate) fn proxy_exotic_own_property_keys(
    obj: &JsObject,
    context: &mut Context,
) -> JsResult<Vec<PropertyKey>> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "ownKeys").
    let Some(trap) = handler.get_method(utf16!("ownKeys"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? target.[[OwnPropertyKeys]]().
        return target.__own_property_keys__(context);
    };

    // 7. Let trapResultArray be ? Call(trap, handler, « target »).
    let trap_result_array = trap.call(&handler.into(), &[target.clone().into()], context)?;

    // 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray, « String, Symbol »).
    let trap_result_raw =
        trap_result_array.create_list_from_array_like(&[Type::String, Type::Symbol], context)?;

    // 9. If trapResult contains any duplicate entries, throw a TypeError exception.
    let mut unchecked_result_keys: FxHashSet<PropertyKey> = FxHashSet::default();
    let mut trap_result = Vec::new();
    for value in &trap_result_raw {
        match value {
            JsValue::String(s) => {
                if !unchecked_result_keys.insert(s.clone().into()) {
                    return Err(JsNativeError::typ()
                        .with_message("Proxy trap result contains duplicate string property keys")
                        .into());
                }
                trap_result.push(s.clone().into());
            }
            JsValue::Symbol(s) => {
                if !unchecked_result_keys.insert(s.clone().into()) {
                    return Err(JsNativeError::typ()
                        .with_message("Proxy trap result contains duplicate symbol property keys")
                        .into());
                }
                trap_result.push(s.clone().into());
            }
            _ => {}
        }
    }

    // 10. Let extensibleTarget be ? IsExtensible(target).
    let extensible_target = target.is_extensible(context)?;

    // 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
    // 12. Assert: targetKeys is a List of property keys.
    // 13. Assert: targetKeys contains no duplicate entries.
    let target_keys = target.__own_property_keys__(context)?;

    // 14. Let targetConfigurableKeys be a new empty List.
    // 15. Let targetNonconfigurableKeys be a new empty List.
    let mut target_configurable_keys = Vec::new();
    let mut target_nonconfigurable_keys = Vec::new();

    // 16. For each element key of targetKeys, do
    for key in target_keys {
        // a. Let desc be ? target.[[GetOwnProperty]](key).
        match target.__get_own_property__(&key, &mut context.into())? {
            // b. If desc is not undefined and desc.[[Configurable]] is false, then
            Some(desc) if !desc.expect_configurable() => {
                // i. Append key as an element of targetNonconfigurableKeys.
                target_nonconfigurable_keys.push(key);
            }
            // c. Else,
            _ => {
                // i. Append key as an element of targetConfigurableKeys.
                target_configurable_keys.push(key);
            }
        }
    }

    // 17. If extensibleTarget is true and targetNonconfigurableKeys is empty, then
    if extensible_target && target_nonconfigurable_keys.is_empty() {
        // a. Return trapResult.
        return Ok(trap_result);
    }

    // 18. Let uncheckedResultKeys be a List whose elements are the elements of trapResult.
    // 19. For each element key of targetNonconfigurableKeys, do
    for key in target_nonconfigurable_keys {
        // a. If key is not an element of uncheckedResultKeys, throw a TypeError exception.
        // b. Remove key from uncheckedResultKeys.
        if !unchecked_result_keys.remove(&key) {
            return Err(JsNativeError::typ()
                .with_message("Proxy trap failed to return all non-configurable property keys")
                .into());
        }
    }

    // 20. If extensibleTarget is true, return trapResult.
    if extensible_target {
        return Ok(trap_result);
    }

    // 21. For each element key of targetConfigurableKeys, do
    for key in target_configurable_keys {
        // a. If key is not an element of uncheckedResultKeys, throw a TypeError exception.
        // b. Remove key from uncheckedResultKeys.
        if !unchecked_result_keys.remove(&key) {
            return Err(JsNativeError::typ()
                .with_message("Proxy trap failed to return all configurable property keys")
                .into());
        }
    }

    // 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
    if !unchecked_result_keys.is_empty() {
        return Err(JsNativeError::typ()
            .with_message("Proxy trap failed to return all property keys")
            .into());
    }

    // 23. Return trapResult.
    Ok(trap_result)
}

/// `10.5.12 [[Call]] ( thisArgument, argumentsList )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist
fn proxy_exotic_call(
    obj: &JsObject,
    argument_count: usize,
    context: &mut Context,
) -> JsResult<CallValue> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Let trap be ? GetMethod(handler, "apply").
    let Some(trap) = handler.get_method(utf16!("apply"), context)? else {
        // 6. If trap is undefined, then
        // a. Return ? Call(target, thisArgument, argumentsList).
        return Ok(target.__call__(argument_count));
    };

    let args = context.vm.pop_n_values(argument_count);

    // 7. Let argArray be ! CreateArrayFromList(argumentsList).
    let arg_array = array::Array::create_array_from_list(args, context);

    // 8. Return ? Call(trap, handler, « target, thisArgument, argArray »).
    let _func = context.vm.pop();
    let this = context.vm.pop();

    context.vm.push(handler); // This
    context.vm.push(trap.clone()); // Function

    context.vm.push(target);
    context.vm.push(this);
    context.vm.push(arg_array);
    Ok(trap.__call__(3))
}

/// `[[Construct]] ( argumentsList, newTarget )`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget
fn proxy_exotic_construct(
    obj: &JsObject,
    argument_count: usize,
    context: &mut Context,
) -> JsResult<CallValue> {
    // 1. Let handler be O.[[ProxyHandler]].
    // 2. If handler is null, throw a TypeError exception.
    // 3. Assert: Type(handler) is Object.
    // 4. Let target be O.[[ProxyTarget]].
    let (target, handler) = obj
        .downcast_ref::<Proxy>()
        .expect("Proxy object internal internal method called on non-proxy object")
        .try_data()?;

    // 5. Assert: IsConstructor(target) is true.
    assert!(target.is_constructor());

    // 6. Let trap be ? GetMethod(handler, "construct").
    let Some(trap) = handler.get_method(utf16!("construct"), context)? else {
        // 7. If trap is undefined, then
        // a. Return ? Construct(target, argumentsList, newTarget).
        return Ok(target.__construct__(argument_count));
    };

    let new_target = context.vm.pop();
    let args = context.vm.pop_n_values(argument_count);
    let _func = context.vm.pop();

    // 8. Let argArray be ! CreateArrayFromList(argumentsList).
    let arg_array = array::Array::create_array_from_list(args, context);

    // 9. Let newObj be ? Call(trap, handler, « target, argArray, newTarget »).
    let new_obj = trap.call(
        &handler.into(),
        &[target.into(), arg_array.into(), new_target],
        context,
    )?;

    // 10. If Type(newObj) is not Object, throw a TypeError exception.
    let new_obj = new_obj.as_object().cloned().ok_or_else(|| {
        JsNativeError::typ().with_message("Proxy trap constructor returned non-object value")
    })?;

    // 11. Return newObj.
    context.vm.push(new_obj);
    Ok(CallValue::Complete)
}