quickjs-pure 0.17.32

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
//! `Object` and `Object.prototype`.
//!
//! This is the most load-bearing module in the library: `hasOwnProperty`,
//! `toString` and `Object.keys` are what test helpers and scripts reach for first,
//! and `Object.defineProperty` is how the rest of the library would describe its own
//! properties.
//!
//! `Object.prototype.toString` is also where the `[object X]` tag comes from, which
//! `assert.js` compares with `==`. The tag is decided the way the spec decides it —
//! arrays are `Array`, functions are `Function`, `null` and `undefined` are their own
//! names — not by inspecting a class field, because a value without a class still has
//! to answer.

use crate::builtins::{arg, define_method, this_object};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, ObjectKind, Property, PropertyKey};
use crate::value::Value;
use js_gc::Gc;

/// Install `Object` and its prototype methods.
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    define_method(object_proto, "toString", 0, to_string, interp);
    // Remembered as the *intrinsic*, for `Array.prototype.toString`'s fallback: §23.1.3.33
    // step 3 names `%Object.prototype.toString%`, not the property, so a script that
    // deletes or replaces it must not change the fallback
    // (`Array/prototype/toString/non-callable-join-string-tag`).
    interp.realm.object_proto_to_string = object_proto
        .own_property("toString")
        .and_then(|property| property.value)
        .and_then(|value| value.as_object().cloned());
    define_method(object_proto, "toLocaleString", 0, to_locale_string, interp);
    define_method(object_proto, "valueOf", 0, value_of, interp);
    define_method(object_proto, "hasOwnProperty", 1, has_own_property, interp);
    // The `__defineGetter__` family (Annex B.2.2.2). Deprecated but not removable: plenty of
    // existing code uses them, and the reference still ships all four.
    define_method(object_proto, "__lookupGetter__", 1, lookup_getter, interp);
    define_method(object_proto, "__lookupSetter__", 1, lookup_setter, interp);
    define_method(object_proto, "__defineGetter__", 2, define_getter, interp);
    define_method(object_proto, "__defineSetter__", 2, define_setter, interp);
    define_method(object_proto, "isPrototypeOf", 1, is_prototype_of, interp);
    define_method(
        object_proto,
        "propertyIsEnumerable",
        1,
        property_is_enumerable,
        interp,
    );

    // `__proto__` is an accessor on `Object.prototype`, not a magic property of every
    // object: `({}).__proto__` finds it here, and a plain `{__proto__: x}` literal never
    // goes through it (the parser handles that form itself).
    let getter = interp.new_native("get __proto__", 0, proto_getter);
    let setter = interp.new_native("set __proto__", 1, proto_setter);
    object_proto.define(
        "__proto__",
        Property {
            getter: Some(Value::Object(getter)),
            setter: Some(Value::Object(setter)),
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );

    let constructor = interp.new_native_constructor("Object", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(object_proto.clone()), false, false),
    );
    object_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, length, func) in [
        ("keys", 1, keys as crate::object::NativeFn),
        ("values", 1, values),
        ("entries", 1, entries),
        ("assign", 2, assign),
        ("create", 2, create),
        ("getPrototypeOf", 1, get_prototype_of),
        ("setPrototypeOf", 2, set_prototype_of),
        ("defineProperty", 3, define_property),
        ("defineProperties", 2, define_properties),
        ("hasOwn", 2, has_own),
        ("getOwnPropertyDescriptors", 1, get_own_property_descriptors),
        ("groupBy", 2, group_by),
        ("getOwnPropertyNames", 1, get_own_property_names),
        ("getOwnPropertySymbols", 1, get_own_property_symbols),
        ("getOwnPropertyDescriptor", 2, get_own_property_descriptor),
        ("freeze", 1, freeze),
        ("isFrozen", 1, is_frozen),
        ("seal", 1, seal),
        ("isSealed", 1, is_sealed),
        ("preventExtensions", 1, prevent_extensions),
        ("isExtensible", 1, is_extensible),
        ("is", 2, is),
        ("fromEntries", 1, from_entries),
    ] {
        define_method(&constructor, name, length, func, interp);
    }
    let global = interp.realm.global.clone();
    global.define(
        "Object",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

/// `Object(value)`: a new object for `null`/`undefined`, the value itself for an
/// object, a box for a primitive.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.1.1.1 step 1: `If NewTarget is neither undefined nor the active function, return
    // OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")`. So a subclass's
    // `super(value)` ignores the argument entirely and builds from `NewTarget.prototype` —
    // `new (class O extends Object {})({a: 1})` has no `a` on the result
    // (`Object/subclass-object-arg`).
    if interp.is_constructing() {
        let intrinsic = interp
            .realm
            .object_proto
            .own_property("constructor")
            .and_then(|property| property.value);
        let target = interp.current_new_target();
        let is_intrinsic = match (&intrinsic, &target) {
            (Some(Value::Object(intrinsic)), Value::Object(target)) => intrinsic.ptr_eq(target),
            _ => false,
        };
        if !is_intrinsic {
            let fallback = interp.realm.object_proto.clone();
            return Ok(Value::Object(interp.new_ctor_instance(fallback)?));
        }
    }
    match args.first() {
        None | Some(Value::Undefined) | Some(Value::Null) => {
            let proto = interp.realm.object_proto.clone();
            Ok(Value::Object(interp.new_object(Some(proto))))
        }
        Some(value @ Value::Object(_)) => Ok(value.clone()),
        Some(primitive) => {
            let boxed = this_object(interp, primitive)?;
            Ok(Value::Object(boxed))
        }
    }
}

/// `Object.prototype.toLocaleString`: whatever `this.toString()` answers (§20.1.3.5).
///
/// It used to be installed as a second name for `to_string`, which is wrong in a way that
/// is easy to miss because the two agree on every plain object: `"".toLocaleString()` has to
/// be `""` and `({toString(){return "x"}}).toLocaleString()` has to be `"x"`, and both were
/// answering `[object String]`/`[object Object]`. The difference shows up through
/// `Array.prototype.toLocaleString`, which is specified in terms of this method.
fn to_locale_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // `Invoke(this, "toString")` is `GetV`, which for a primitive is
    // `ToObject(this).[Get](P, this)` — the box is the *owner*, the primitive is the
    // **receiver**. So a getter installed on `Boolean.prototype.toString` sees `this`
    // === `true`, not the wrapper (`Object/prototype/toLocaleString/
    // primitive_this_value_getter` reads `typeof this` inside exactly that getter).
    let key = PropertyKey::from("toString");
    let method = match &this {
        Value::Object(object) => interp.get_property_key(object, &key)?,
        primitive => {
            let boxed = interp.object_from(primitive)?;
            interp.get_property_key_for(&boxed, Some(primitive), &key)?
        }
    };
    match method {
        Some(method) => interp.call_value(method, this, Vec::new()),
        None => Err(interp.type_error("toString is not a function")),
    }
}

/// §20.1.3.6 `Object.prototype.toString`.
///
/// The order of the two halves is the whole specification here, and getting it wrong is
/// invisible until a test moves a tag: **`builtinTag` is computed first (steps 4–14), then
/// `Get(O, @@toStringTag)` (step 15)**, and the tag only wins when it is a *String*.
///
/// Three consequences that each cost a test262 case:
///
/// * `ToObject(this)` (step 3) happens **before** the tag is read, so a primitive receiver
///   sees its prototype's tag: `Boolean.prototype[@@toStringTag] = "test262"` makes
///   `toString.call(true)` answer `[object test262]`. Reading the tag only when `this` was
///   already an object answered `[object Boolean]`.
/// * A **non-string** tag falls back to `builtinTag`, and the get stops at the first
///   property found on the chain — it does not keep looking for a string further up.
///   `%GeneratorPrototype%[@@toStringTag]` is `"Generator"`, so replacing the tag on
///   `genFn.prototype` with a getter that answers `{}` has to give `[object Object]`.
/// * `builtinTag` is computed *before* the get, so `IsArray` runs on a live proxy:
///   `proxy-revoked-during-get-call` revokes the proxy from inside its own `get` trap and
///   still expects `[object Array]`.
fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // Steps 1–2: `undefined` and `null` are answered before `ToObject`, which would throw.
    match &this {
        Value::Undefined => return Ok(interp.string("[object Undefined]")),
        Value::Null => return Ok(interp.string("[object Null]")),
        _ => {}
    }
    // Step 3.
    let object = interp.object_from(&this)?;
    // Steps 4–14, before the tag is read.
    let builtin = builtin_tag(interp, &object);
    // Step 15: a real `[[Get]]` up the chain, so a getter runs and a proxy's trap fires.
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::ToStringTag);
    // Step 16: only a String tag overrides the built-in one. `new String("x")` is *not*
    // unwrapped — `symbol-tag-string-builtin` guards exactly that.
    if let Some(Value::String(tag)) = interp.get_property_key(&object, &key)? {
        let tag = tag.to_string_lossy().into_owned();
        return Ok(interp.string(format!("[object {tag}]")));
    }
    Ok(interp.string(format!("[object {builtin}]")))
}

/// Steps 4–14 of §20.1.3.6: the tag a value has when nothing overrides it.
///
/// Only the slots the specification names are consulted, which is why a `Map`, a `Set`, a
/// `Promise` or a generator answer `Object` here — their tags come from
/// `@@toStringTag` on their prototypes and disappear with it.
fn builtin_tag(interp: &Interp<'_>, object: &Gc<JsObject>) -> &'static str {
    // Step 5 `IsArray(O)`, which for a proxy asks its target. Deliberately not "does the
    // object's kind say Array": a proxy over an array is an array for this purpose, and a
    // revoked proxy whose revocation happened *after* this point still answers from the
    // target it had (`proxy-revoked-during-get-call`).
    if is_array_through_proxy(object) {
        return "Array";
    }
    // Step 7 `[[Call]]`. A proxy built over a callable target *does* have `[[Call]]`
    // (§10.5.12), and it keeps it after revocation, which `proxy-function` and
    // `symbol-tag-non-str-proxy-function` both rely on — so this has to be asked before the
    // blanket proxy answer below.
    if object.is_callable() {
        return "Function";
    }
    // A proxy has none of the remaining slots, so everything below answers `Object` —
    // including a proxy wrapped around an `Error` or a `RegExp`, where recursing into the
    // target would wrongly say `Error`/`RegExp`.
    if object.proxy_state().is_some() {
        return "Object";
    }
    match object.with(|data| match &data.kind {
        // Step 13 `[[RegExpMatcher]]`. (Step 7 is answered above.)
        ObjectKind::RegExp(_) => Some("RegExp"),
        _ => None,
    }) {
        Some(tag) => tag,
        None => {
            // Step 6 `[[ParameterMap]]`, step 8 `[[ErrorData]]` and step 12 `[[DateValue]]`
            // are all carried in `_class`, which is the engine's stand-in for those slots.
            match interp
                .internal_get(object, "_class")
                .map(|value| value.to_js_string())
                .as_deref()
            {
                Some("Arguments") => return "Arguments",
                Some("Error") => return "Error",
                Some("Date") => return "Date",
                _ => {}
            }
            // Steps 9–11 `[[BooleanData]]`, `[[NumberData]]`, `[[StringData]]`: `_value` is
            // the box marker and holds the wrapped primitive.
            //
            // `Object(1n)` and `Object(Symbol())` are deliberately *not* here: this
            // test262 revision has no `[[BigIntData]]`/`[[SymbolData]]` step, and
            // `symbol-tag-non-str-bigint` asserts `[object Object]` once the prototype tag
            // is replaced with a non-string.
            match interp.internal_get(object, "_value") {
                Some(Value::Bool(_)) => "Boolean",
                Some(Value::Int(_) | Value::Float(_)) => "Number",
                Some(Value::String(_)) => "String",
                // Step 14.
                _ => "Object",
            }
        }
    }
}

/// `IsArray`, following a proxy to its target.
///
/// A revoked proxy has no target left; the specification makes `IsArray` throw there, but
/// this is only ever reached *after* the caller already read a property, so answering
/// `false` is both unreachable in practice and harmless.
fn is_array_through_proxy(object: &Gc<JsObject>) -> bool {
    let mut current = object.clone();
    for _ in 0..1_000 {
        if let Some(state) = current.proxy_state() {
            let next = state.borrow().target.clone();
            match next {
                Some(target) => current = target,
                None => return false,
            }
            continue;
        }
        return current.with(|data| matches!(data.kind, ObjectKind::Array { .. }));
    }
    false
}

/// §20.1.3.7 `Object.prototype.valueOf`.
///
/// `ToObject(this)` — nothing else. A primitive receiver comes back as its **wrapper**
/// (`typeof Object.prototype.valueOf.call(true) === "object"`), and `null`/`undefined` throw,
/// which is what `S15.2.4.4_A12` through `_A15` each check from a different call site.
///
/// Returning the primitive unchanged — what this did — made the four `typeof` cases answer
/// `"boolean"`/`"number"` and made `(1, Object.prototype.valueOf)()` a silent `undefined`.
fn value_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(Value::Object(crate::builtins::this_object(interp, &this)?))
}

fn has_own_property(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.1.3.2 step 1 is `ToPropertyKey(P)` and step 2 is `ToObject(this)`. The order is
    // observable: `hasOwnProperty.call(null, {toString(){throw e}})` reports the key's
    // error, not the receiver's TypeError (`topropertykey_before_toobject`).
    let key = interp.property_key(&arg(args, 0))?;
    let object = this_object(interp, &this)?;
    // `[[GetOwnProperty]]`, not a peek at the property table: a proxy answers this with
    // its `getOwnPropertyDescriptor` trap, and it may still be holding a `TypeError` for
    // a handler that lied about a fixed property.
    Ok(Value::Bool(
        interp.object_get_own_property(&object, &key)?.is_some(),
    ))
}

/// `Object.hasOwn`: `[[GetOwnProperty]]` on a `ToObject`'d target.
///
/// Not `o.hasOwnProperty(k)`: this one works on a primitive and on an object that
/// shadows or replaces `hasOwnProperty`, which is the whole reason it exists.
fn has_own(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let object = interp.object_from(&arg(args, 0))?;
    let key = interp.property_key(&arg(args, 1))?;
    Ok(Value::Bool(
        interp.object_get_own_property(&object, &key)?.is_some(),
    ))
}

/// `Object.getOwnPropertyDescriptors`: every own descriptor, keyed the same way.
fn get_own_property_descriptors(
    interp: &mut Interp<'_>,
    _this: Value,
    args: &[Value],
) -> JsResult<Value> {
    let object = interp.object_from(&arg(args, 0))?;
    // §20.1.2.10: `ObjectCreate(null)`? No — an **ordinary** object, with
    // `%Object.prototype%`. Only `Object.groupBy`'s buckets are null-prototype, and
    // copying that choice here answered `null` where the test reads `Object.prototype`
    // (`getOwnPropertyDescriptors/normal-object`).
    let prototype = interp.realm.object_proto.clone();
    let result = interp.new_object(Some(prototype));
    for key in interp.object_own_property_keys(&object)? {
        let Some(property) = interp.object_get_own_property(&object, &key)? else {
            continue;
        };
        let descriptor = describe(interp, &property);
        result.define_key(&key, Property::with_attributes(descriptor, true, true));
    }
    Ok(Value::Object(result))
}

/// One property as the descriptor object `getOwnPropertyDescriptor` answers with.
fn describe(interp: &Interp<'_>, property: &Property) -> Value {
    let proto = interp.realm.object_proto.clone();
    let descriptor = interp.new_object(Some(proto));
    if property.is_accessor() {
        descriptor.define_data("get", property.getter.clone().unwrap_or(Value::Undefined));
        descriptor.define_data("set", property.setter.clone().unwrap_or(Value::Undefined));
    } else {
        descriptor.define_data("value", property.value.clone().unwrap_or(Value::Undefined));
        descriptor.define_data("writable", Value::Bool(property.writable));
    }
    descriptor.define_data("enumerable", Value::Bool(property.enumerable));
    descriptor.define_data("configurable", Value::Bool(property.configurable));
    Value::Object(descriptor)
}

/// `Object.groupBy(items, callback)`: bucket the elements by `callback`'s answer.
///
/// The result has a **null** prototype and its buckets are ordinary arrays. A key of
/// `"__proto__"` is therefore just a key: with `Object.prototype` in the chain, writing it
/// would have replaced the result's prototype instead of creating a bucket.
fn group_by(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let items = arg(args, 0);
    let callback = arg(args, 1);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    let result = interp.new_object(None);
    let iterator = interp.get_iterator(&items)?;
    let mut index = 0i32;
    loop {
        let (value, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        let key = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value.clone(), Value::Int(index)],
        )?;
        // `ToPropertyKey`, so a symbol key stays a symbol and `1` becomes `"1"`.
        let key = interp.property_key(&key)?;
        let bucket = match result.own_property_key(&key) {
            Some(existing) => existing.value.unwrap_or(Value::Undefined),
            None => {
                let bucket = interp.new_array(Vec::new());
                let bucket = Value::Object(bucket);
                result.define_key(&key, Property::with_attributes(bucket.clone(), true, true));
                bucket
            }
        };
        if let Value::Object(array) = &bucket {
            let length = array.array_length().unwrap_or(0);
            array.array_set(interp.heap, length, value);
            array.array_set_length(interp.heap, length + 1);
        }
        index += 1;
    }
    Ok(Value::Object(result))
}

/// `__lookupGetter__`: walk the chain for an accessor with a getter.
fn lookup_getter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    lookup_accessor(interp, this, args, true)
}

/// `__lookupSetter__`.
fn lookup_setter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    lookup_accessor(interp, this, args, false)
}

fn lookup_accessor(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    want_getter: bool,
) -> JsResult<Value> {
    let object = interp.object_from(&this)?;
    let key = interp.property_key(&arg(args, 0))?;
    let mut current = Some(object);
    // Bounded: a proxy could answer `getPrototypeOf` with a cycle, and `for…in` over the
    // same object has the same problem.
    for _ in 0..10_000 {
        let Some(object) = current else {
            return Ok(Value::Undefined);
        };
        if let Some(property) = interp.object_get_own_property(&object, &key)? {
            // B.2.2.3 step 3: the walk stops at the first property found, and an own **data**
            // property answers `undefined` — it does not keep looking further up. Continuing
            // past it found an unrelated accessor on a prototype
            // (`__lookupGetter__/lookup-own-data`).
            if !property.is_accessor() {
                return Ok(Value::Undefined);
            }
            let half = if want_getter {
                property.getter
            } else {
                property.setter
            };
            return Ok(half.unwrap_or(Value::Undefined));
        }
        current = interp.object_prototype_of(&object)?;
    }
    Ok(Value::Undefined)
}

/// `__defineGetter__`: an accessor with this getter, keeping any existing setter.
fn define_getter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    define_accessor(interp, this, args, true)
}

/// `__defineSetter__`.
fn define_setter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    define_accessor(interp, this, args, false)
}

fn define_accessor(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    is_getter: bool,
) -> JsResult<Value> {
    let object = interp.object_from(&this)?;
    let function = arg(args, 1);
    if !matches!(&function, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    let key = interp.property_key(&arg(args, 0))?;
    // Annex B.2.2.2: unspecified attributes default to `true`, unlike
    // `Object.defineProperty`, and the *other* half of an existing accessor is preserved.
    let existing = interp.object_get_own_property(&object, &key)?;
    // B.2.2.2 step 3 builds the descriptor as exactly `{ [[Get]]: getter, [[Enumerable]]:
    // true, [[Configurable]]: true }` — `enumerable` is **always** true and does not inherit
    // the existing property's flag (`define-existing` checks a data property becoming
    // enumerable). `[[Set]]` is absent, which is what leaves an existing setter alone.
    let mut property = Property {
        value: None,
        getter: None,
        setter: None,
        writable: false,
        enumerable: true,
        configurable: true,
        // A **partial** descriptor, so `ValidateAndApplyPropertyDescriptor` runs. A whole
        // `Property` skips that check by design (internal callers mean "just write it"), and
        // with `None` here `__defineGetter__` silently reshaped a non-configurable data
        // property (`define-non-configurable`).
        descriptor_fields: Some(crate::object::DescriptorFields {
            value: false,
            writable: false,
            enumerable: true,
            configurable: true,
            get: is_getter,
            set: !is_getter,
        }),
    };
    if let Some(existing) = &existing
        && existing.is_accessor()
    {
        property.getter = existing.getter.clone();
        property.setter = existing.setter.clone();
    }
    if is_getter {
        property.getter = Some(function);
    } else {
        property.setter = Some(function);
    }
    if !interp.object_define_own_property(&object, &key, property)? {
        // Step 5 is `DefinePropertyOrThrow`: a non-configurable property or a non-extensible
        // object is a `TypeError`, not a silent no-op (`define-non-configurable`,
        // `define-non-extensible`).
        return Err(interp.type_error("cannot define the accessor on this object"));
    }
    Ok(Value::Undefined)
}

fn is_prototype_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.1.3.4 step 1 comes **before** step 2: a non-object `V` answers `false` without
    // `ToObject` ever running, so `isPrototypeOf.call(null, 10)` is `false` rather than the
    // `TypeError` `ToObject(null)` would raise (`null-this-and-primitive-arg-returns-false`).
    let Some(target) = arg(args, 0).as_object().cloned() else {
        return Ok(Value::Bool(false));
    };
    let proto = this_object(interp, &this)?;
    // §20.1.3.4: `O.[[GetPrototypeOf]]()` per hop, **not** a walk of the static slots. The
    // difference is a proxy: `isPrototypeOf(proxy)` has to consult the `getPrototypeOf` trap
    // at every step (`arg-is-proxy`), and `chain()` sees the empty slot a proxy keeps and
    // stops immediately. Same mistake as the batch that fixed the nine proxy internal
    // methods; this one is the prototype-walk in the *other* direction.
    let mut current = Some(target);
    let mut guard = 0;
    while let Some(object) = current {
        current = interp.object_prototype_of(&object)?;
        if current.as_ref().is_some_and(|next| next.ptr_eq(&proto)) {
            return Ok(Value::Bool(true));
        }
        guard += 1;
        if guard > 10_000 {
            break;
        }
    }
    Ok(Value::Bool(false))
}

fn property_is_enumerable(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = this_object(interp, &this)?;
    // A symbol argument is a symbol key, not the string `Symbol(x)`. Stringifying it made
    // `Object.prototype.propertyIsEnumerable.call(o, sym)` answer `false` for every symbol
    // property, which is how a whole family of test262 class tests — those that verify a
    // computed symbol key through `verifyProperty` — failed on a property that was
    // perfectly enumerable.
    let key = interp.propkey(&arg(args, 0))?;
    // `? O.[[GetOwnProperty]](P)` — the internal method, not the property table. Reading
    // the table directly answered `false` for every property reached through a proxy (a
    // proxy's table is empty by design), and `verifyProperty` calls this to cross-check
    // `enumerable`, so the whole `Proxy/getOwnPropertyDescriptor/trap-is-*` family failed
    // on a descriptor that was in fact correct.
    let enumerable = interp
        .object_get_own_property(&object, &key)?
        .is_some_and(|property| property.enumerable);
    Ok(Value::Bool(enumerable))
}

fn keys(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.1.2.17 step 1 is `ToObject(O)` — through the **wrapper**, so `Object.keys("ab")`
    // is `["0","1"]` (the index properties are own and enumerable) and `Object.keys(null)`
    // is the `TypeError` `ToObject` raises (`keys/15.2.3.14-1-4`). Answering the primitive
    // cases by hand is what lost that error.
    let value = Value::Object(interp.object_from(&arg(args, 0))?);
    // A proxy reports its own key list, and asks about each key's enumerability one at
    // a time — `Object.keys(proxyOfFrozen)` must not see a key the handler hides.
    let keys: Vec<Value> = own_enumerable_keys(interp, &value)?
        .iter()
        .map(|key| interp.key_value(key))
        .collect();
    let array = interp.new_array(keys);
    Ok(Value::Object(array))
}

/// The own **string** keys of `object`, in `[[OwnPropertyKeys]]` order, with no
/// enumerability filter.
///
/// `EnumerableOwnProperties` (§7.3.23) walks the list it snapshotted here and asks
/// `[[GetOwnProperty]]` for each key **as it reaches it**, so a getter that makes a later
/// key non-enumerable removes it from the result — and the traps interleave as
/// `ownKeys, gOPD:a, get:a, gOPD:b, get:b, …` (`entries/observable-operations`,
/// `entries/getter-making-future-key-nonenumerable`). Filtering the list up front gets both
/// wrong.
fn own_string_keys(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<Vec<PropertyKey>> {
    Ok(interp
        .object_own_property_keys(object)?
        .into_iter()
        .filter(|key| !key.is_symbol())
        .collect())
}

/// The own enumerable **string** keys of `value`, in the order `[[OwnPropertyKeys]]`
/// reports them.
///
/// This goes through the interpreter rather than reading the object directly, which is
/// what makes `Object.keys(proxy)` ask the handler: a proxy's own property table is empty
/// by design, so reading it would answer "no keys" for every proxy.
fn own_enumerable_keys(interp: &mut Interp<'_>, value: &Value) -> JsResult<Vec<PropertyKey>> {
    own_enumerable_keys_of(interp, value, false)
}

/// [`own_enumerable_keys`] with the symbol *keys* kept, for the callers whose specification
/// says `[[OwnPropertyKeys]]` rather than "string keys".
///
/// `Object.assign` is the one that matters: §20.1.2.1 step 4 walks every own enumerable key
/// **including symbols**, which is also why a frozen target with a symbol-keyed data
/// property has to throw (`assign/target-is-frozen-data-property-set-throws`). `Object.keys`
/// and friends filter symbols out on purpose, so the choice belongs at the call site.
fn own_enumerable_keys_of(
    interp: &mut Interp<'_>,
    value: &Value,
    include_symbols: bool,
) -> JsResult<Vec<PropertyKey>> {
    let Some(object) = value.as_object().cloned() else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for key in interp.object_own_property_keys(&object)? {
        if key.is_symbol() && !include_symbols {
            continue;
        }
        let enumerable = interp
            .object_get_own_property(&object, &key)?
            .is_some_and(|property| property.enumerable);
        if enumerable {
            out.push(key);
        }
    }
    Ok(out)
}

fn values(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToObject(O)` first — `Object.values(null)` is a `TypeError`
    // (`values/exception-not-object-coercible`) — and the key list is taken **once**,
    // before any value is read: a getter that makes a later key non-enumerable must not
    // remove it from the result (`values/getter-making-future-key-nonenumerable`).
    let object = interp.object_from(&arg(args, 0))?;
    let mut out = Vec::new();
    for key in own_string_keys(interp, &object)? {
        let enumerable = interp
            .object_get_own_property(&object, &key)?
            .is_some_and(|property| property.enumerable);
        if !enumerable {
            continue;
        }
        if let Some(found) = interp.get_property_key(&object, &key)? {
            out.push(found);
        }
    }
    let array = interp.new_array(out);
    Ok(Value::Object(array))
}

fn entries(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToObject` and a single key snapshot, for the same two reasons as [`values`].
    let object = interp.object_from(&arg(args, 0))?;
    let mut out = Vec::new();
    for key in own_string_keys(interp, &object)? {
        // Per key, and *before* the value is read: see [`own_string_keys`].
        let enumerable = interp
            .object_get_own_property(&object, &key)?
            .is_some_and(|property| property.enumerable);
        if !enumerable {
            continue;
        }
        if let Some(found) = interp.get_property_key(&object, &key)? {
            let name = interp.key_value(&key);
            let pair = interp.new_array(vec![name, found]);
            out.push(Value::Object(pair));
        }
    }
    let array = interp.new_array(out);
    Ok(Value::Object(array))
}

fn assign(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToObject(target)`: a primitive target is boxed and the box is returned, so
    // `Object.assign(1, {a: 1})` answers a Number object. Refusing the primitive
    // outright was wrong, and it is the shape most `Object.assign` tests use.
    let target_object = interp.object_from(&arg(args, 0))?;
    let target = Value::Object(target_object.clone());
    for source in args.iter().skip(1) {
        // `ToObject(source)` too: a string source has index properties, so
        // `Object.assign({}, "ab")` copies `0` and `1`. `null`/`undefined` are skipped
        // rather than converted, which is the one exception the spec makes here.
        if matches!(source, Value::Undefined | Value::Null) {
            continue;
        }
        let source_object = interp.object_from(source)?;
        let source = &Value::Object(source_object);
        // `Object.assign` copies exactly the own enumerable keys, so it goes through
        // `[[OwnPropertyKeys]]` and `[[Get]]` — which is what makes it see a proxy's
        // handler rather than the empty property table behind it.
        for as_key in own_enumerable_keys_of(interp, source, true)? {
            if let Some(found) =
                interp.get_property_key(source.as_object().expect("checked above"), &as_key)?
            {
                interp.set_property_with_key(
                    &target_object,
                    &as_key,
                    found,
                    crate::interp::DeleteFailure::Throw,
                )?;
            }
        }
    }
    Ok(target)
}

fn create(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let proto = match arg(args, 0) {
        Value::Object(object) => Some(object),
        Value::Null => None,
        other => {
            return Err(interp.type_error(format!(
                "Object.create prototype must be an object or null, got {}",
                other.type_of()
            )));
        }
    };
    let object = interp.new_object(proto);
    // The second argument, `PropertiesFromDescriptors`, was read and then dropped: the
    // object came out empty and `Object.create(null, {a: {value: 1}})` had no `a` at all.
    // Five test262 cases depend on it just in the Iterator area, because a
    // null-prototype object is how those tests build a clean properties bag.
    let properties = arg(args, 1);
    if !matches!(properties, Value::Undefined) {
        define_properties(
            interp,
            Value::Undefined,
            &[Value::Object(object.clone()), properties],
        )?;
    }
    Ok(Value::Object(object))
}

fn get_prototype_of(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.1.2.9 step 1 is `ToObject(O)`, so a primitive answers **its wrapper's**
    // prototype: `Object.getPrototypeOf(0)` is `Number.prototype`, not
    // `Object.prototype` (`getPrototypeOf/15.2.3.2-1` and the two beside it), and
    // `null`/`undefined` are the `TypeError` `ToObject` raises.
    let object = interp.object_from(&arg(args, 0))?;
    Ok(interp
        .object_prototype_of(&object)?
        .map_or(Value::Null, Value::Object))
}

/// §B.2.2.1.1 `get Object.prototype.__proto__`.
///
/// ```text
/// 1  O = RequireObjectCoercible(this)     → TypeError for null/undefined
/// 2  Type(O) is not Object → undefined
/// 3  O.[[GetPrototypeOf]]()               → the *internal method*, not `proto()`
/// ```
///
/// Step 3 is why this cannot read the slot directly: through a proxy the answer has to come
/// from the `getPrototypeOf` trap, and a trap that throws must propagate
/// (`get-abrupt`). Reading `object.proto()` also reported `null` for a proxy, whose slot is
/// always empty.
fn proto_getter(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // Step 1.
    if matches!(this, Value::Undefined | Value::Null) {
        return Err(interp.type_error("Object.prototype.__proto__ called on null or undefined"));
    }
    // A primitive receiver is boxed, which the specification puts in `GetV` rather than
    // here — but *our* member-access path hands a getter the raw primitive (the boxing a
    // sloppy `function(){ return typeof this }` sees happens at the bytecode call
    // boundary, not before a **native** getter). So `(1).__proto__` has to box itself, or
    // it answers `undefined` instead of `Number.prototype`.
    //
    // Step 2's "not an object → undefined" is then unreachable from script: `GetV` boxes,
    // and `undefined`/`null` have already thrown above.
    let object = match this.as_object().cloned() {
        Some(object) => object,
        None => crate::builtins::this_object(interp, &this)?,
    };
    Ok(match interp.object_prototype_of(&object)? {
        // A null prototype reports `null`, not `undefined`.
        None => Value::Null,
        Some(proto) => Value::Object(proto),
    })
}

/// §B.2.2.1.2 `set Object.prototype.__proto__`.
///
/// ```text
/// 1  O = RequireObjectCoercible(this)
/// 2  proto is neither an Object nor null → undefined
/// 3  Type(O) is not Object → undefined
/// 4  Return ? O.[[SetPrototypeOf]](proto)   ← the `?` is the point
/// ```
///
/// Step 4 propagates: a cycle, a non-extensible object or a proxy trap that answers `false`
/// makes this setter **throw a `TypeError`** rather than quietly doing nothing. It reads like
/// a plain assignment, and in sloppy mode `o.__proto__ = p` does swallow one — but the
/// swallow happens in `Set`, after the accessor has already thrown, so the setter itself
/// must raise. Every `set-*` case in `Object/prototype/__proto__/` checks one of those.
fn proto_setter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // Step 1.
    if matches!(this, Value::Undefined | Value::Null) {
        return Err(interp.type_error("Object.prototype.__proto__ called on null or undefined"));
    }
    // Step 2.
    let proto = match arg(args, 0) {
        Value::Object(proto) => Some(proto),
        Value::Null => None,
        _ => return Ok(Value::Undefined),
    };
    // Step 3.
    let Some(object) = this.as_object().cloned() else {
        return Ok(Value::Undefined);
    };
    // Step 4.
    if !interp.object_set_prototype_of(&object, proto)? {
        return Err(interp.type_error("cannot set the prototype of this object"));
    }
    Ok(Value::Undefined)
}

fn set_prototype_of(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    let proto = match arg(args, 1) {
        Value::Object(object) => Some(object),
        Value::Null => None,
        _ => return Err(interp.type_error("prototype must be an object or null")),
    };
    if let Some(object) = target.as_object() {
        // A proxy answers through `setPrototypeOf` and may refuse; the `Object.` entry
        // point turns a refusal into a `TypeError` rather than reporting `false`.
        if !interp.object_set_prototype_of(object, proto)? {
            return Err(interp.type_error("proxy refused to change its prototype"));
        }
    }
    Ok(target)
}

fn define_property(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    let Value::Object(object) = &target else {
        return Err(interp.type_error("Object.defineProperty target is not an object"));
    };
    if !define_property_on(interp, object, args)? {
        return Err(interp.type_error("cannot redefine property"));
    }
    Ok(target)
}

/// `Object.defineProperties(target, descriptors)`.
///
/// Missing outright until now, which surfaced as "undefined is not a function" rather than
/// as an absent feature — a missing method and a broken one look identical from a test.
/// The descriptors are collected first and applied second, as the spec does, so one that
/// throws leaves the target untouched.
fn define_properties(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    let Value::Object(object) = &target else {
        return Err(interp.type_error("Object.defineProperties target is not an object"));
    };
    // `ObjectDefineProperties` runs `ToObject` on the descriptor map, so a primitive is
    // not automatically an error: `Object.defineProperties({}, 5)` is a no-op because a
    // Number wrapper has no own enumerable properties. Only `null`/`undefined` are
    // refused outright, and a *non-empty* string is refused one step later, when its
    // indexed values ("a", "b", …) fail `ToPropertyDescriptor`.
    let descriptors = match arg(args, 1) {
        Value::Object(object) => object,
        Value::Undefined | Value::Null => {
            return Err(interp.type_error("cannot convert to object"));
        }
        Value::String(text) if text.utf16_len() > 0 => {
            return Err(interp.type_error("not an object"));
        }
        _ => return Ok(target),
    };
    // Collect first, apply second: a descriptor that throws must leave the target alone.
    let mut pending: Vec<(Value, Value)> = Vec::new();
    for key in interp.object_own_property_keys(&descriptors)? {
        // Only the *enumerable* own properties of the descriptor map are used, which is
        // what makes `Object.defineProperties(o, {a: {...}})` skip a non-enumerable `a`.
        // `[[GetOwnProperty]]`, not the property table: the descriptor map may be a
        // **proxy**, whose own table is empty by design, and §20.1.2.3.1 asks its
        // `getOwnPropertyDescriptor` trap once per key
        // (`defineProperties/proxy-no-ownkeys-returned-keys-order` counts those calls).
        let enumerable = interp
            .object_get_own_property(&descriptors, &key)?
            .is_some_and(|property| property.enumerable);
        if !enumerable {
            continue;
        }
        let Some(descriptor) = interp.get_property_key(&descriptors, &key)? else {
            continue;
        };
        let key_value = match &key {
            PropertyKey::String(text) => interp.string_wtf8(text.clone()),
            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
        };
        pending.push((key_value, descriptor));
    }
    for (key_value, descriptor) in pending {
        if !define_property_on(interp, object, &[target.clone(), key_value, descriptor])? {
            return Err(interp.type_error("cannot redefine property"));
        }
    }
    Ok(target)
}

/// The shared body of `Object.defineProperty` and `Reflect.defineProperty`.
///
/// `args` is `[target, key, descriptor]`; the target object is passed separately
/// because the two entry points disagree only in how they report failure.
pub fn define_property_on(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    args: &[Value],
) -> JsResult<bool> {
    let key = interp.property_key(&arg(args, 1))?;
    let Value::Object(descriptor) = arg(args, 2) else {
        return Err(interp.type_error("property descriptor must be an object"));
    };
    // Array-aware: an element lives in the element vector, so a descriptor that changes
    // only attributes (`{configurable: false}`) must still see the current value rather
    // than fall back to `undefined` and blank the element.
    let previous = crate::object::own_property_including_array(object, &key);
    let getter = interp.get_property(&descriptor, "get")?;
    let setter = interp.get_property(&descriptor, "set")?;
    // ToPropertyDescriptor: a `get`/`set` that is present must be callable. `undefined`
    // means "absent" and is allowed, but `get: null` is a TypeError — accepting it stored
    // a non-callable getter that no read could run.
    for function in [&getter, &setter].into_iter().flatten() {
        if !matches!(function, Value::Undefined)
            && !matches!(function.as_object(), Some(object) if object.is_callable())
        {
            return Err(interp.type_error("getter or setter is not callable"));
        }
    }
    // "The descriptor **has** [[Get]]" is a presence test, not a value test: §6.2.6.5
    // `ToPropertyDescriptor` makes `{get: undefined, set: undefined}` an **accessor**
    // descriptor whose getter and setter are both `undefined`. Testing the value instead
    // turned it into a data property, so `getOwnPropertyDescriptor` came back with
    // `value`/`writable` where the test reads `get`/`set`
    // (`defineProperty/15.2.3.6-4-430` and its siblings).
    let has_get = getter.is_some();
    let has_set = setter.is_some();
    // An accessor property *stays* an accessor when the descriptor only touches the
    // generic attributes. `Object.defineProperty(o, "e", {enumerable: true})` on an
    // accessor must keep the getter: ValidateAndApplyPropertyDescriptor step 9 says a
    // descriptor with no `[[Value]]`/`[[Writable]]`/`[[Get]]`/`[[Set]]` only updates
    // `[[Enumerable]]`/`[[Configurable]]`. Deciding `has_accessor` from the descriptor
    // alone converted the property to a data property and blanked its value.
    let descriptor_is_data = interp.get_property(&descriptor, "value")?.is_some()
        || interp.get_property(&descriptor, "writable")?.is_some();
    let has_accessor = has_get
        || has_set
        || (previous.as_ref().is_some_and(|p| p.is_accessor()) && !descriptor_is_data);
    // A descriptor may not be both kinds: `{value: 12, set: f}` is a TypeError, which
    // `ToPropertyDescriptor` refuses rather than silently preferring one half.
    if has_accessor
        && (interp.get_property(&descriptor, "value")?.is_some()
            || interp.get_property(&descriptor, "writable")?.is_some())
    {
        return Err(interp.type_error("cannot have both a value and a getter/setter"));
    }
    // A proxy must be handed the **partial** descriptor, not this merged one.
    //
    // Two things go wrong if it is merged first. The proxy's own property table is empty,
    // so `previous` is `None` and every omitted attribute defaults to `false` — the merge
    // then *locks down* the target's property instead of keeping it
    // (`Object.defineProperty(new Proxy({a:1},{}), "a", {value:2})` left `a` non-writable,
    // non-enumerable and non-configurable). And §10.5.4's invariants are stated over "Desc
    // *has* [[Writable]]", which a merged `Property` cannot express — `{writable: false}`
    // and an omitted `writable` were indistinguishable, worth four test262 cases.
    //
    // So the proxy gets the descriptor as written, plus the record of which fields were
    // named; `object_define_own_property` merges it against whatever object it lands on
    // (the target, when there is no trap).
    if object.proxy_state().is_some() {
        let named = crate::object::DescriptorFields {
            value: interp.get_property(&descriptor, "value")?.is_some(),
            writable: interp.get_property(&descriptor, "writable")?.is_some(),
            enumerable: interp.get_property(&descriptor, "enumerable")?.is_some(),
            configurable: interp.get_property(&descriptor, "configurable")?.is_some(),
            get: has_get,
            set: has_set,
        };
        let property = if has_accessor {
            Property {
                getter,
                setter,
                value: None,
                writable: false,
                enumerable: descriptor_bool(interp, &descriptor, "enumerable")?.unwrap_or(false),
                configurable: descriptor_bool(interp, &descriptor, "configurable")?
                    .unwrap_or(false),
                descriptor_fields: Some(named),
            }
        } else {
            Property {
                value: interp.get_property(&descriptor, "value")?,
                writable: descriptor_bool(interp, &descriptor, "writable")?.unwrap_or(false),
                enumerable: descriptor_bool(interp, &descriptor, "enumerable")?.unwrap_or(false),
                configurable: descriptor_bool(interp, &descriptor, "configurable")?
                    .unwrap_or(false),
                getter: None,
                setter: None,
                descriptor_fields: Some(named),
            }
        };
        return interp.object_define_own_property(object, &key, property);
    }
    // An attribute the descriptor does not mention is *kept* when the property already
    // exists and is of the same kind — `Object.defineProperty({a: 1}, "a", {value: 5})`
    // leaves `a` writable, enumerable and configurable. Only a brand-new property, or a
    // switch between a data and an accessor property, defaults the omitted ones to false
    // (ValidateAndApplyPropertyDescriptor steps 8 and 9). Defaulting everything to false
    // silently locked a property down on every attribute-only redefine.
    // The two *generic* attributes are always inherited when the descriptor omits them,
    // even across a data/accessor conversion: ValidateAndApplyPropertyDescriptor steps 9
    // and 10 convert the property while keeping `[[Configurable]]` and `[[Enumerable]]`
    // from the existing one. `writable` and `value` are not generic — an accessor has
    // neither — so they are only inherited when both sides are data properties.
    let same_kind = previous
        .as_ref()
        .is_some_and(|existing| existing.is_accessor() == has_accessor);
    let inherited = |named: Option<bool>, pick: fn(&Property) -> bool, across: bool| -> bool {
        named
            .or_else(|| previous.as_ref().filter(|_| across || same_kind).map(pick))
            .unwrap_or(false)
    };
    let enumerable = inherited(
        descriptor_bool(interp, &descriptor, "enumerable")?,
        |p| p.enumerable,
        true,
    );
    let configurable = inherited(
        descriptor_bool(interp, &descriptor, "configurable")?,
        |p| p.configurable,
        true,
    );
    let writable = inherited(
        descriptor_bool(interp, &descriptor, "writable")?,
        |p| p.writable,
        false,
    );
    // `defineProperty` defaults every attribute to `false` when the descriptor omits
    // it, but keeps the *value* when the descriptor is a pure attribute change.
    let property = if has_accessor {
        // A half-specified accessor keeps the other half: `{set: f}` on an existing
        // getter/setter pair must not drop the getter.
        let previous_getter = previous.as_ref().and_then(|p| p.getter.clone());
        let previous_setter = previous.as_ref().and_then(|p| p.setter.clone());
        Property {
            getter: getter.or(previous_getter),
            setter: setter.or(previous_setter),
            enumerable,
            configurable,
            writable: false,
            value: None,
            descriptor_fields: None,
        }
    } else {
        let value = match interp.get_property(&descriptor, "value")? {
            Some(value) => value,
            None => previous
                .as_ref()
                .and_then(|property| property.value.clone())
                .unwrap_or(Value::Undefined),
        };
        Property {
            value: Some(value),
            writable,
            enumerable,
            configurable,
            getter: None,
            setter: None,
            descriptor_fields: None,
        }
    };
    // An array's `length` is exotic: it is not in the property table, and it has its own
    // writability. Handled here because only this function knows which descriptor fields
    // were actually present — `object_define_own_property` receives a filled-in `Property`
    // and cannot tell `{writable: false}` from `{value: 3, writable: false}`.
    if object.is_array() && key.as_str() == Some("length") {
        let requested_value = interp.get_property(&descriptor, "value")?;
        let requested_writable = descriptor_bool(interp, &descriptor, "writable")?;
        // `length` may only ever be a non-enumerable data property: it cannot become
        // configurable, enumerable, or an accessor.
        // §10.4.2.4 `ArraySetLength` step 5 (`ToUint32` vs `ToNumber`, a `RangeError`) runs
        // **before** the `[[Enumerable]]`/`[[Configurable]]` refusal below, so
        // `Object.defineProperty([], "length", {value: -1, configurable: true})` is a
        // `RangeError` and not the `TypeError` a refused definition would produce
        // (`length/define-own-prop-length-error`).
        let requested_uint = match &requested_value {
            // Two `ToNumber` calls, both observable — see
            // `Interp::coerce_array_length_twice`.
            Some(value) => Some(interp.coerce_array_length_twice(value)?),
            None => None,
        };
        if configurable
            || descriptor_bool(interp, &descriptor, "enumerable")? == Some(true)
            || (has_get || has_set)
        {
            return Ok(false);
        }
        // `ArraySetLength` step 3 runs `ToUint32`, not `ToNumber`: an object whose
        // `valueOf` gives a fraction falls through to `ToString`, so `{toString: () => "2"}`
        // is a valid length while `{valueOf: () => 2.5}` is a `RangeError`. Comparing
        // `ToNumber` against the current length also made `{toString: () => "2"}` look like
        // `NaN` and refused it.
        if !object.length_writable() {
            // A read-only `length` refuses both a new value and being made writable again.
            if requested_writable == Some(true) {
                return Ok(false);
            }
            if requested_uint
                .is_some_and(|value| value as usize != object.array_length().unwrap_or(0))
            {
                return Ok(false);
            }
            return Ok(true);
        }
        if let Some(requested) = requested_uint {
            let current = object.array_length().unwrap_or(0);
            let requested = requested as usize;
            if requested < current {
                // `ArraySetLength` walks down from the top and, on hitting a non-deletable
                // element, stops with `[[Length]]` set to *that* index plus one — so
                // `[0,1,2]` with a fixed index 1 ends at length 2, neither 3 nor 0.
                let blocked = object.last_undeletable_at_or_above(requested, current);
                if let Some(blocked) = blocked {
                    object.array_truncate(interp.heap, blocked + 1);
                    // §10.4.2.4 `ArraySetLength` step 3.i: the refusal still applies
                    // `[[Writable]]: false` when the descriptor asked for it. Returning
                    // `false` alone left the length writable, which `verifyProperty`
                    // catches (`defineProperties/15.2.3.7-6-a-164` and `-176`).
                    if requested_writable == Some(false) {
                        object.set_length_writable(false);
                    }
                    return Ok(false);
                }
            }
            object.array_set_length(interp.heap, requested);
        }
        if let Some(writable) = requested_writable {
            object.set_length_writable(writable);
        }
        return Ok(true);
    }
    // §10.4.4.2 `[[DefineOwnProperty]]` for a mapped `arguments` index: the alias to the
    // parameter survives every descriptor *except* one that makes the property
    // non-writable. `Object.defineProperty(arguments, "0", {configurable: false})` keeps
    // the mapping, while `{writable: false}` drops it and the index freezes at whatever
    // the parameter last had.
    //
    // Handled here rather than in `object_define_own_property` because only this function
    // still knows whether `writable` was *present* in the descriptor: it receives
    // `Some(false)` for both `{writable: false}` and an omitted `writable` that inherited
    // `false` from the existing property.
    if let Some(index) = key.as_str().and_then(crate::object::array_index)
        && object.mapped_argument_cell(index as usize).is_some()
    {
        // §10.4.4.2 step 8.a: an *accessor* descriptor, or one that makes the index
        // non-writable, both end the alias. Anything else keeps it.
        let becomes_accessor = has_get || has_set;
        if becomes_accessor || descriptor_bool(interp, &descriptor, "writable")? == Some(false) {
            if becomes_accessor {
                // The user's accessor replaces ours outright; there is no value to freeze.
                //
                // Built from the descriptor alone: `property` inherited the missing half
                // from the *existing* property, which here is the cell accessor, so a
                // `{set}` descriptor would have kept our getter and `arguments[0]` would
                // still have answered the parameter.
                object.drop_mapped_argument(index as usize);
                object.define_key(
                    &key,
                    Property {
                        getter: interp
                            .get_property(&descriptor, "get")?
                            .filter(|v| !matches!(v, Value::Undefined)),
                        setter: interp
                            .get_property(&descriptor, "set")?
                            .filter(|v| !matches!(v, Value::Undefined)),
                        value: None,
                        writable: false,
                        enumerable: property.enumerable,
                        configurable: property.configurable,
                        descriptor_fields: None,
                    },
                );
                return Ok(true);
            }
            // `{writable: false}` ends the alias; the index freezes at the parameter's
            // current value.
            // A descriptor that names a value wins; otherwise the frozen value is the
            // cell's, because the alias is an accessor and the descriptor path built an
            // accessor `Property` with no value at all.
            let value = match interp.get_property(&descriptor, "value")? {
                Some(value) => {
                    // §10.4.4.2 step 4.a runs **before** step 4.d drops the alias: a
                    // descriptor that names a value writes it through to the parameter,
                    // and only then does a non-writable descriptor end the mapping.
                    // Dropping first left `a` at its old value while `arguments[0]`
                    // reported the new one (`defineProperty/15.2.3.6-4-292-1` and the
                    // five beside it).
                    if let Some(cell) = object.mapped_argument_cell(index as usize) {
                        cell.set(value.clone());
                    }
                    value
                }
                None => object
                    .mapped_argument_cell(index as usize)
                    .map(|cell| cell.get())
                    .unwrap_or(Value::Undefined),
            };
            object.drop_mapped_argument(index as usize);
            object.define_key(
                &key,
                Property {
                    value: Some(value),
                    writable: false,
                    enumerable: property.enumerable,
                    configurable: property.configurable,
                    ..Property::default()
                },
            );
            return Ok(true);
        }
        // A non-configurable index may only be redefined compatibly, and the alias must
        // not be a way around that: `{configurable: true}` on a locked index is a
        // `TypeError` exactly as it would be on an ordinary object.
        // Only `configurable` and `enumerable` may not be relaxed once set. A value is
        // still assignable while the index is writable, and a mapped index always is —
        // `existing` describes the *accessor* that implements the alias, whose
        // `writable` is `false` and says nothing about the parameter.
        if let Some(existing) = &previous
            && !existing.configurable
            && (property.configurable || property.enumerable != existing.enumerable)
        {
            return Err(interp.type_error("cannot redefine property"));
        }
        // §10.4.4.2 step 8.b: a descriptor that names a value writes it *through* to
        // the parameter, and the alias stays.
        if let Some(value) = interp.get_property(&descriptor, "value")?
            && let Some(cell) = object.mapped_argument_cell(index as usize)
        {
            cell.set(value);
        }
        // Any other descriptor keeps the alias. The accessor that implements it must
        // stay in the table, so the generic attributes are applied to it directly rather
        // than letting the ordinary path replace it with a data property — which would
        // have reported `writable: false` and silently stopped tracking the parameter.
        let mut accessor = object
            .own_property_key(&key)
            .unwrap_or_else(|| Property::accessor(None, None));
        accessor.enumerable = property.enumerable;
        accessor.configurable = property.configurable;
        object.define_key(&key, accessor);
        return Ok(true);
    }
    // A module namespace answers `[[DefineOwnProperty]]` itself (§10.4.6.6), and it has to
    // be asked **before** the descriptor is merged with the existing property. The merge
    // assumes an ordinary property — it converts a redefine of an accessor into an accessor
    // descriptor and inherits `writable: false` from it — so by the time
    // `object_define_own_property` sees the result, "which fields the descriptor named" is
    // gone. For a namespace that distinction is the whole answer: `{}` names nothing and
    // succeeds, `{writable: false}` names a field and fails.
    if object.module_namespace_marker() {
        return interp.namespace_define_from_descriptor(object, &key, &descriptor);
    }
    // A new property may not appear on a non-extensible object.
    if previous.is_none() && !object.is_extensible() {
        return Ok(false);
    }
    // ValidateAndApplyPropertyDescriptor: a non-configurable property may not be
    // redefined, except to the same values. Without this every redefine "succeeded" and
    // silently overwrote a property the script had locked.
    if let Some(existing) = &previous
        && !existing.configurable
    {
        let kind_changed = existing.is_accessor() != property.is_accessor();
        // Compare the *merged* accessor halves, not the descriptor's presence bits: a
        // descriptor that says `set: undefined` presents no setter, yet on a
        // non-configurable property that is still a change from a real setter. Judging by
        // presence let `Object.defineProperties(arr, {1: {set: undefined}})` quietly
        // succeed on a locked accessor.
        let accessor_changed = property.is_accessor()
            && (!same_accessor_half(&property.getter, &existing.getter)
                || !same_accessor_half(&property.setter, &existing.setter));
        let attribute_changed =
            enumerable != existing.enumerable || configurable || kind_changed || accessor_changed;
        let data_changed = !kind_changed
            && existing.is_accessor() == property.is_accessor()
            && !existing.writable
            && (writable
                // `SameValue`, not `===`: redefining a frozen `NaN` property with `NaN`
                // is not a change, because `SameValue(NaN, NaN)` holds.
                || property.value.as_ref().is_some_and(|value| {
                    !existing
                        .value
                        .as_ref()
                        .is_some_and(|old| old.same_value(value))
                }));
        if attribute_changed || data_changed {
            // `false`, not a throw: the two entry points disagree about reporting, and
            // `Reflect.defineProperty` must answer `false` where `Object.defineProperty`
            // raises. The conversion happens in the callers.
            return Ok(false);
        }
    }
    // A proxy decides through `defineProperty`, and a refusal is a `TypeError` here
    // because `Object.defineProperty` reports failure that way.
    interp.object_define_own_property(object, &key, property)
}
/// Whether two getter/setter slots hold the same function.
///
/// An absent half and an explicit `undefined` are the same thing: an accessor with no
/// getter reads as `undefined` either way, so redefining it as `undefined` is not a
/// change and redefining it as a function is.
pub(crate) fn same_accessor_half(left: &Option<Value>, right: &Option<Value>) -> bool {
    let left = left
        .as_ref()
        .filter(|value| !matches!(value, Value::Undefined));
    let right = right
        .as_ref()
        .filter(|value| !matches!(value, Value::Undefined));
    match (left, right) {
        (None, None) => true,
        (Some(left), Some(right)) => left.same_value(right),
        _ => false,
    }
}

/// One boolean field of a property descriptor, or `None` when it is absent.
fn descriptor_bool(
    interp: &mut Interp<'_>,
    descriptor: &Gc<JsObject>,
    field: &str,
) -> JsResult<Option<bool>> {
    Ok(interp
        .get_property(descriptor, field)?
        .filter(|value| !matches!(value, Value::Undefined))
        .map(|value| value.to_boolean()))
}

fn get_own_property_names(
    interp: &mut Interp<'_>,
    _this: Value,
    args: &[Value],
) -> JsResult<Value> {
    // §20.1.2.10 step 1 is `ToObject(O)`: a string becomes its wrapper, whose index
    // properties and `length` *are* own properties, and `undefined`/`null` are the
    // `TypeError` `ToObject` raises (`getOwnPropertyNames/non-object-argument-invalid`).
    let object = interp.object_from(&arg(args, 0))?;
    let names: Vec<Value> = interp
        .object_own_property_keys(&object)?
        .iter()
        .filter(|key| !key.is_symbol())
        .map(|key| interp.key_value(key))
        .collect();
    let array = interp.new_array(names);
    Ok(Value::Object(array))
}

/// `Object.getOwnPropertySymbols(obj)`.
///
/// The only way to enumerate symbol keys, and the reason a symbol-keyed property is
/// effectively private: nothing else reports it.
fn get_own_property_symbols(
    interp: &mut Interp<'_>,
    _this: Value,
    args: &[Value],
) -> JsResult<Value> {
    // `ToObject`, like the rest of §20.1.2: a primitive is boxed rather than refused, and
    // only `undefined`/`null` throw (`getOwnPropertySymbols/non-object-argument-valid`).
    let object = interp.object_from(&arg(args, 0))?;
    let symbols: Vec<Value> = interp
        .object_own_property_keys(&object)?
        .into_iter()
        .filter(|key| key.is_symbol())
        .map(|key| interp.key_value(&key))
        .collect();
    let array = interp.new_array(symbols);
    Ok(Value::Object(array))
}

fn get_own_property_descriptor(
    interp: &mut Interp<'_>,
    _this: Value,
    args: &[Value],
) -> JsResult<Value> {
    // §20.1.2.8 step 1 is `ToObject(O)`: `Object.getOwnPropertyDescriptor("foo", 0)` has
    // to answer the **wrapper's** index descriptor (`{value: "f", writable: false,
    // enumerable: true, configurable: false}`), and `"foo"` also owns `length`
    // (`getOwnPropertyDescriptor/primitive-string`). Refusing a primitive outright made
    // every one of those a `TypeError`.
    let object = interp.object_from(&arg(args, 0))?;
    let key = interp.property_key(&arg(args, 1))?;
    let Some(property) = interp.object_get_own_property(&object, &key)? else {
        return Ok(Value::Undefined);
    };
    let proto = interp.realm.object_proto.clone();
    let descriptor = interp.new_object(Some(proto));
    if property.is_accessor() {
        descriptor.define_data("get", property.getter.unwrap_or(Value::Undefined));
        descriptor.define_data("set", property.setter.unwrap_or(Value::Undefined));
    } else {
        descriptor.define_data("value", property.value.unwrap_or(Value::Undefined));
        descriptor.define_data("writable", Value::Bool(property.writable));
    }
    descriptor.define_data("enumerable", Value::Bool(property.enumerable));
    descriptor.define_data("configurable", Value::Bool(property.configurable));
    Ok(Value::Object(descriptor))
}

/// `Object.freeze`, `seal` and `preventExtensions`.
///
/// The distinctions the spec draws are observable through `isFrozen`/`isSealed`, so
/// they are kept apart: frozen clears `writable` and `configurable`, sealed clears
/// `configurable` only, and both imply non-extensible.
/// §7.3.3 `SetIntegrityLevel(O, level)`.
///
/// The spec's shape matters here and the hand-rolled version had all three parts wrong:
///
/// 1. `[[PreventExtensions]]` first — through the proxy trap when there is one, which is
///    what makes `Object.freeze(new Proxy({}, {preventExtensions(){throw 1}}))` throw
///    (`abrupt-completion`).
/// 2. `[[OwnPropertyKeys]]` next — again through the proxy's `ownKeys` trap, so freezing a
///    proxy describes what the *trap* returned and not what a table holds
///    (`proxy-no-ownkeys-returned-keys-order`).
/// 3. `[[DefineOwnProperty]]` per key — not a direct table rewrite. That is what routes
///    the descriptor through a proxy's `defineProperty` trap and what makes an array's
///    elements come back frozen: an element lives in a vector and its descriptor is
///    synthesised, so writing the table left `Object.getOwnPropertyDescriptor(a, "0")`
///    still reporting `writable: true` (`15.2.3.9-2-a-14`).
///
/// `level` is `Frozen` for `Object.freeze` and `Sealed` for `Object.seal`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum IntegrityLevel {
    Sealed,
    Frozen,
}

/// `SetIntegrityLevel(object, frozen)`, for the runtime's own frozen objects.
///
/// The template object is the one place the spec asks for this outside `Object.freeze`, and
/// it cannot go through the builtin: that reads `Object.preventExtensions`, which a script
/// may have replaced.
pub(crate) fn freeze_object(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<()> {
    set_integrity_level(interp, object, IntegrityLevel::Frozen)
}

fn set_integrity_level(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    level: IntegrityLevel,
) -> JsResult<()> {
    if !interp.object_prevent_extensions(object)? {
        return Err(interp.type_error("proxy refused to become non-extensible"));
    }
    for key in interp.object_own_property_keys(object)? {
        let Some(property) = interp.object_get_own_property(object, &key)? else {
            continue;
        };
        // §7.3.3 step 3.a builds a *partial* descriptor: `{ [[Configurable]]: false }`, plus
        // `{ [[Writable]]: false }` at `Frozen`. Only a data property gets the `writable`
        // half — an accessor has no such field and naming it on one makes the definition
        // refuse the property outright, which is how an object with a getter came back
        // `Object.freeze` failing.
        //
        // The partial shape is also what a proxy's `defineProperty` trap must be shown:
        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` and
        // `descriptor.enumerable === undefined`, i.e. the trap sees exactly the two fields
        // the spec named and nothing inherited from the current descriptor.
        // The descriptor is *partial*: only `configurable`, plus `writable` at §Frozen and
        // only for a data property (an accessor has no `[[Writable]]`, and naming it makes
        // the definition refuse). Everything else is left to the merge in
        // `object_define_own_property`, which is what keeps `value` and `enumerable` — a
        // whole-property descriptor here reset both to `false`/`undefined`, so
        // `Object.freeze({a: 1}).a` read back as `undefined`.
        let mut descriptor = Property {
            configurable: false,
            descriptor_fields: Some(crate::object::DescriptorFields {
                value: false,
                writable: level == IntegrityLevel::Frozen && !property.is_accessor(),
                enumerable: false,
                configurable: true,
                get: false,
                set: false,
            }),
            ..Property::default()
        };
        descriptor.writable = false;
        if !interp.object_define_own_property(object, &key, descriptor)? {
            return Err(
                interp.type_error(format!("cannot make the property '{key}' non-configurable"))
            );
        }
    }
    // Array elements and `length` are *not* own keys — the vector and the derived length
    // have no property to describe — so the per-key loop above never reaches them. These
    // two flags are what `[[Set]]` consults for a store into an element slot, and freezing
    // an array is exactly when they must flip.
    if object.is_array() {
        object.set_elements_writable(false);
        if level == IntegrityLevel::Frozen {
            object.set_length_writable(false);
        }
    }
    Ok(())
}

fn freeze(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    if let Some(object) = target.as_object() {
        set_integrity_level(interp, object, IntegrityLevel::Frozen)?;
    }
    Ok(target)
}

fn seal(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    if let Some(object) = target.as_object() {
        set_integrity_level(interp, object, IntegrityLevel::Sealed)?;
    }
    Ok(target)
}

/// Whether any own property of `object` is still `configurable` and/or `writable`.
///
/// §7.3.13/§7.3.14 share this walk, and it has to go through `[[OwnPropertyKeys]]` and
/// `[[GetOwnProperty]]` rather than the raw table: a proxy answers from its traps, and an
/// array's elements and `length` are not in the table at all.
fn own_keys_unlocked(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    check_configurable: bool,
    check_writable: bool,
) -> JsResult<bool> {
    for key in interp.object_own_property_keys(object)? {
        let Some(property) = interp.object_get_own_property(object, &key)? else {
            continue;
        };
        if (check_configurable && property.configurable) || (check_writable && property.writable) {
            return Ok(true);
        }
    }
    // The element vector and the derived `length` carry their own flags; no key describes
    // them, so an array frozen through `set_elements_writable` would otherwise read as
    // frozen while a store into it still succeeded.
    if object.is_array() {
        if (check_configurable || check_writable) && object.elements_writable() {
            return Ok(true);
        }
        // `length` is writable or not, but never configurable, so only `isFrozen` cares.
        if check_writable && object.length_writable() {
            return Ok(true);
        }
    }
    Ok(false)
}

fn is_frozen(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    let Some(object) = target.as_object() else {
        // §7.3.14 step 1: a non-object is frozen by definition, `null` included. The
        // `null`-exclusion here was wrong — `Object.isFrozen(null)` is `true`, and
        // `15.2.3.12-1-2` asserts exactly that.
        return Ok(Value::Bool(true));
    };
    // §7.3.14 step 2.b asks `[[GetOwnProperty]]` for **every own key**, not for every
    // key in the property table. The two differ for an array (elements and `length`) and
    // for a *native* function's derived `length`/`name`, which is why
    // `own_property_including_array` is the reader here rather than `own_property_key`.
    // `[[IsExtensible]]` and `[[OwnPropertyKeys]]` both go through the interpreter, so a
    // proxy's `isExtensible` and `ownKeys` traps run — `proxy-no-ownkeys-returned-keys-order`
    // counts the latter's calls.
    // Both attributes: §7.3.14 asks for `configurable` **or** `writable`.
    let anything_writable = own_keys_unlocked(interp, object, true, true)?;
    Ok(Value::Bool(
        !interp.object_is_extensible(object)? && !anything_writable,
    ))
}

fn is_sealed(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    let Some(object) = target.as_object() else {
        // §7.3.13 step 1: a non-object is sealed, `null` included.
        return Ok(Value::Bool(true));
    };
    let anything_configurable = own_keys_unlocked(interp, object, true, false)?;
    Ok(Value::Bool(
        !interp.object_is_extensible(object)? && !anything_configurable,
    ))
}

fn prevent_extensions(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    if let Some(object) = target.as_object() {
        if !interp.object_prevent_extensions(object)? {
            return Err(interp.type_error("proxy refused to become non-extensible"));
        }
    }
    Ok(target)
}

fn is_extensible(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let target = arg(args, 0);
    Ok(Value::Bool(match target.as_object() {
        Some(object) => interp.object_is_extensible(object)?,
        None => false,
    }))
}

/// `Object.is`, which differs from `===` on exactly two values: `NaN` and `-0`.
fn is(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let (a, b) = (arg(args, 0), arg(args, 1));
    // Same-type check first: `0` and `-0` are both numbers and compare equal under
    // `===`, so the sign has to be inspected explicitly.
    let same = match (&a, &b) {
        (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
            let (x, y) = (a.to_number(), b.to_number());
            if x.is_nan() && y.is_nan() {
                true
            } else if x == 0.0 && y == 0.0 {
                x.is_sign_negative() == y.is_sign_negative()
            } else {
                x == y
            }
        }
        _ => a.strict_equals(&b),
    };
    let _ = interp;
    Ok(Value::Bool(same))
}

/// `Object.fromEntries(iterable)`: build an object from `[key, value]` entries.
///
/// This used to walk an *array* by index and skip anything that was not an object, which
/// got three things wrong: a non-iterable argument answered `{}` instead of a `TypeError`,
/// an entry that was not an object was skipped instead of refused, and — the reason most of
/// the tests exist — the iterator was never closed when an entry's key or value threw.
fn from_entries(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let proto = interp.realm.object_proto.clone();
    let object = interp.new_object(Some(proto));
    let iterable = arg(args, 0);
    let iterator = interp.get_iterator(&iterable)?;
    loop {
        let (entry, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        // `AddEntriesFromIterable` wraps the body in `IfAbruptCloseIterator`: a refused
        // entry, a throwing key accessor or a throwing `ToPropertyKey` all close the
        // iterator, and the original error is the one that propagates.
        let outcome = (|| -> JsResult<(crate::object::PropertyKey, Value)> {
            let Some(pair) = entry.as_object().cloned() else {
                return Err(interp.type_error("not an object"));
            };
            // §20.1.2.7 `AddEntriesFromIterable` reads **both** properties before the
            // key is converted: `? Get(nextItem, "0")`, `IfAbruptCloseIterator`, `?
            // Get(nextItem, "1")`, `? ToPropertyKey(k)`. Converting the key first made
            // the observable order `get 0, toString, get 1` instead of
            // `get 0, get 1, toString` (`fromEntries/evaluation-order`).
            let key = interp.get_property(&pair, "0")?.unwrap_or(Value::Undefined);
            let value = interp.get_property(&pair, "1")?.unwrap_or(Value::Undefined);
            let key = interp.property_key(&key)?;
            Ok((key, value))
        })();
        match outcome {
            Ok((key, value)) => {
                // `CreateDataPropertyOrThrow`, so a key of `"__proto__"` becomes an own
                // property rather than replacing the prototype.
                object.define_key(&key, Property::data(value));
            }
            Err(signal) => {
                let _ = close_iterator(interp, &iterator);
                return Err(signal);
            }
        }
    }
    Ok(Value::Object(object))
}

/// `IteratorClose`, ignoring an error from `return` itself.
fn close_iterator(interp: &mut Interp<'_>, iterator: &crate::interp::Iterator) -> JsResult<()> {
    let Some(target) = iterator.object.as_object().cloned() else {
        return Ok(());
    };
    match interp.get_property(&target, "return")? {
        Some(Value::Object(function)) if function.is_callable() => {
            interp.call_value(Value::Object(function), iterator.object.clone(), Vec::new())?;
            Ok(())
        }
        _ => Ok(()),
    }
}