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
//! Boa's implementation of ECMAScript's global `Object` object.
//!
//! The `Object` class represents one of ECMAScript's data types.
//!
//! It is used to store various keyed collections and more complex entities.
//! Objects can be created using the `Object()` constructor or the
//! object initializer / literal syntax.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
use std::ops::Deref;
use super::{
error::ErrorObject, Array, BuiltInBuilder, BuiltInConstructor, Date, IntrinsicObject, RegExp,
};
use crate::{
builtins::{map, BuiltInObject},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
error::JsNativeError,
js_string,
native_function::NativeFunction,
object::{
internal_methods::{get_prototype_from_constructor, InternalMethodContext},
FunctionObjectBuilder, IntegrityLevel, JsObject,
},
property::{Attribute, PropertyDescriptor, PropertyKey, PropertyNameKind},
realm::Realm,
string::{common::StaticJsStrings, utf16},
symbol::JsSymbol,
value::JsValue,
Context, JsArgs, JsData, JsResult, JsString,
};
use boa_gc::{Finalize, Trace};
use boa_profiler::Profiler;
use tap::{Conv, Pipe};
pub(crate) mod for_in_iterator;
#[cfg(test)]
mod tests;
/// An ordinary Javascript `Object`.
#[derive(Debug, Default, Clone, Copy, Trace, Finalize, JsData)]
#[boa_gc(empty_trace)]
pub struct OrdinaryObject;
impl IntrinsicObject for OrdinaryObject {
fn init(realm: &Realm) {
let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init");
let legacy_proto_getter = BuiltInBuilder::callable(realm, Self::legacy_proto_getter)
.name(js_string!("get __proto__"))
.build();
let legacy_setter_proto = BuiltInBuilder::callable(realm, Self::legacy_proto_setter)
.name(js_string!("set __proto__"))
.build();
BuiltInBuilder::from_standard_constructor::<Self>(realm)
.inherits(None)
.accessor(
utf16!("__proto__"),
Some(legacy_proto_getter),
Some(legacy_setter_proto),
Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.method(Self::has_own_property, js_string!("hasOwnProperty"), 1)
.method(
Self::property_is_enumerable,
js_string!("propertyIsEnumerable"),
1,
)
.method(Self::to_string, js_string!("toString"), 0)
.method(Self::to_locale_string, js_string!("toLocaleString"), 0)
.method(Self::value_of, js_string!("valueOf"), 0)
.method(Self::is_prototype_of, js_string!("isPrototypeOf"), 1)
.method(
Self::legacy_define_getter,
js_string!("__defineGetter__"),
2,
)
.method(
Self::legacy_define_setter,
js_string!("__defineSetter__"),
2,
)
.method(
Self::legacy_lookup_getter,
js_string!("__lookupGetter__"),
1,
)
.method(
Self::legacy_lookup_setter,
js_string!("__lookupSetter__"),
1,
)
.static_method(Self::create, js_string!("create"), 2)
.static_method(Self::set_prototype_of, js_string!("setPrototypeOf"), 2)
.static_method(Self::get_prototype_of, js_string!("getPrototypeOf"), 1)
.static_method(Self::define_property, js_string!("defineProperty"), 3)
.static_method(Self::define_properties, js_string!("defineProperties"), 2)
.static_method(Self::assign, js_string!("assign"), 2)
.static_method(Self::is, js_string!("is"), 2)
.static_method(Self::keys, js_string!("keys"), 1)
.static_method(Self::values, js_string!("values"), 1)
.static_method(Self::entries, js_string!("entries"), 1)
.static_method(Self::seal, js_string!("seal"), 1)
.static_method(Self::is_sealed, js_string!("isSealed"), 1)
.static_method(Self::freeze, js_string!("freeze"), 1)
.static_method(Self::is_frozen, js_string!("isFrozen"), 1)
.static_method(Self::prevent_extensions, js_string!("preventExtensions"), 1)
.static_method(Self::is_extensible, js_string!("isExtensible"), 1)
.static_method(
Self::get_own_property_descriptor,
js_string!("getOwnPropertyDescriptor"),
2,
)
.static_method(
Self::get_own_property_descriptors,
js_string!("getOwnPropertyDescriptors"),
1,
)
.static_method(
Self::get_own_property_names,
js_string!("getOwnPropertyNames"),
1,
)
.static_method(
Self::get_own_property_symbols,
js_string!("getOwnPropertySymbols"),
1,
)
.static_method(Self::has_own, js_string!("hasOwn"), 2)
.static_method(Self::from_entries, js_string!("fromEntries"), 1)
.static_method(Self::group_by, js_string!("groupBy"), 2)
.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
}
impl BuiltInObject for OrdinaryObject {
const NAME: JsString = StaticJsStrings::OBJECT;
}
impl BuiltInConstructor for OrdinaryObject {
const LENGTH: usize = 1;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::object;
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. If NewTarget is neither undefined nor the active function object, then
if !new_target.is_undefined()
&& new_target
!= &context
.active_function_object()
.unwrap_or_else(|| context.intrinsics().constructors().object().constructor())
.into()
{
// a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::object, context)?;
let object = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
prototype,
OrdinaryObject,
);
return Ok(object.into());
}
let value = args.get_or_undefined(0);
// 2. If value is undefined or null, return OrdinaryObjectCreate(%Object.prototype%).
if value.is_null_or_undefined() {
Ok(JsObject::with_object_proto(context.intrinsics()).into())
} else {
// 3. Return ! ToObject(value).
value.to_object(context).map(JsValue::from)
}
}
}
impl OrdinaryObject {
/// `get Object.prototype.__proto__`
///
/// The `__proto__` getter function exposes the value of the
/// internal `[[Prototype]]` of an object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-object.prototype.__proto__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
pub fn legacy_proto_getter(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? ToObject(this value).
let obj = this.to_object(context)?;
// 2. Return ? O.[[GetPrototypeOf]]().
let proto = obj.__get_prototype_of__(&mut InternalMethodContext::new(context))?;
Ok(proto.map_or(JsValue::Null, JsValue::new))
}
/// `set Object.prototype.__proto__`
///
/// The `__proto__` setter allows the `[[Prototype]]` of
/// an object to be mutated.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-set-object.prototype.__proto__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
pub fn legacy_proto_setter(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. If Type(proto) is neither Object nor Null, return undefined.
let proto = match args.get_or_undefined(0) {
JsValue::Object(proto) => Some(proto.clone()),
JsValue::Null => None,
_ => return Ok(JsValue::undefined()),
};
// 3. If Type(O) is not Object, return undefined.
let JsValue::Object(object) = this else {
return Ok(JsValue::undefined());
};
// 4. Let status be ? O.[[SetPrototypeOf]](proto).
let status =
object.__set_prototype_of__(proto, &mut InternalMethodContext::new(context))?;
// 5. If status is false, throw a TypeError exception.
if !status {
return Err(JsNativeError::typ()
.with_message("__proto__ called on null or undefined")
.into());
}
// 6. Return undefined.
Ok(JsValue::undefined())
}
/// `Object.prototype.__defineGetter__(prop, func)`
///
/// Binds an object's property to a function to be called when that property is looked up.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.__defineGetter__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__
pub fn legacy_define_getter(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let getter = args.get_or_undefined(1);
// 1. Let O be ? ToObject(this value).
let obj = this.to_object(context)?;
// 2. If IsCallable(getter) is false, throw a TypeError exception.
if !getter.is_callable() {
return Err(JsNativeError::typ()
.with_message("Object.prototype.__defineGetter__: Expecting function")
.into());
}
// 3. Let desc be PropertyDescriptor { [[Get]]: getter, [[Enumerable]]: true, [[Configurable]]: true }.
let desc = PropertyDescriptor::builder()
.get(getter.clone())
.enumerable(true)
.configurable(true);
// 4. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(0).to_property_key(context)?;
// 5. Perform ? DefinePropertyOrThrow(O, key, desc).
obj.define_property_or_throw(key, desc, context)?;
// 6. Return undefined.
Ok(JsValue::undefined())
}
/// `Object.prototype.__defineSetter__(prop, func)`
///
/// Binds an object's property to a function to be called when an attempt is made to set that property.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.__defineSetter__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__
pub fn legacy_define_setter(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let setter = args.get_or_undefined(1);
// 1. Let O be ? ToObject(this value).
let obj = this.to_object(context)?;
// 2. If IsCallable(setter) is false, throw a TypeError exception.
if !setter.is_callable() {
return Err(JsNativeError::typ()
.with_message("Object.prototype.__defineSetter__: Expecting function")
.into());
}
// 3. Let desc be PropertyDescriptor { [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: true }.
let desc = PropertyDescriptor::builder()
.set(setter.clone())
.enumerable(true)
.configurable(true);
// 4. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(0).to_property_key(context)?;
// 5. Perform ? DefinePropertyOrThrow(O, key, desc).
obj.define_property_or_throw(key, desc, context)?;
// 6. Return undefined.
Ok(JsValue::undefined())
}
/// `Object.prototype.__lookupGetter__(prop)`
///
/// Returns the function bound as a getter to the specified property.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.__lookupGetter__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__
pub fn legacy_lookup_getter(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? ToObject(this value).
let mut obj = this.to_object(context)?;
// 2. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(0).to_property_key(context)?;
// 3. Repeat
loop {
// a. Let desc be ? O.[[GetOwnProperty]](key).
let desc = obj.__get_own_property__(&key, &mut InternalMethodContext::new(context))?;
// b. If desc is not undefined, then
if let Some(current_desc) = desc {
// i. If IsAccessorDescriptor(desc) is true, return desc.[[Get]].
return if current_desc.is_accessor_descriptor() {
Ok(current_desc.expect_get().clone())
} else {
// ii. Return undefined.
Ok(JsValue::undefined())
};
}
match obj.__get_prototype_of__(&mut InternalMethodContext::new(context))? {
// c. Set O to ? O.[[GetPrototypeOf]]().
Some(o) => obj = o,
// d. If O is null, return undefined.
None => return Ok(JsValue::undefined()),
}
}
}
/// `Object.prototype.__lookupSetter__(prop)`
///
/// Returns the function bound as a getter to the specified property.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.__lookupSetter__
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__
pub fn legacy_lookup_setter(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? ToObject(this value).
let mut obj = this.to_object(context)?;
// 2. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(0).to_property_key(context)?;
// 3. Repeat
loop {
// a. Let desc be ? O.[[GetOwnProperty]](key).
let desc = obj.__get_own_property__(&key, &mut InternalMethodContext::new(context))?;
// b. If desc is not undefined, then
if let Some(current_desc) = desc {
// i. If IsAccessorDescriptor(desc) is true, return desc.[[Set]].
return if current_desc.is_accessor_descriptor() {
Ok(current_desc.expect_set().clone())
} else {
// ii. Return undefined.
Ok(JsValue::undefined())
};
}
match obj.__get_prototype_of__(&mut InternalMethodContext::new(context))? {
// c. Set O to ? O.[[GetPrototypeOf]]().
Some(o) => obj = o,
// d. If O is null, return undefined.
None => return Ok(JsValue::undefined()),
}
}
}
/// `Object.create( proto, [propertiesObject] )`
///
/// Creates a new object from the provided prototype.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.create
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
pub fn create(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let prototype = args.get_or_undefined(0);
let properties = args.get_or_undefined(1);
let obj = match prototype {
JsValue::Object(_) | JsValue::Null => JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
prototype.as_object().cloned(),
OrdinaryObject,
),
_ => {
return Err(JsNativeError::typ()
.with_message(format!(
"Object prototype may only be an Object or null: {}",
prototype.display()
))
.into())
}
};
if !properties.is_undefined() {
object_define_properties(&obj, properties, context)?;
return Ok(obj.into());
}
Ok(obj.into())
}
/// `Object.getOwnPropertyDescriptor( object, property )`
///
/// Returns an object describing the configuration of a specific property on a given object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor
pub fn get_own_property_descriptor(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(O).
let obj = args.get_or_undefined(0).to_object(context)?;
// 2. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(1).to_property_key(context)?;
// 3. Let desc be ? obj.[[GetOwnProperty]](key).
let desc = obj.__get_own_property__(&key, &mut InternalMethodContext::new(context))?;
// 4. Return FromPropertyDescriptor(desc).
Ok(Self::from_property_descriptor(desc, context))
}
/// `Object.getOwnPropertyDescriptors( object )`
///
/// Returns all own property descriptors of a given object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors
pub fn get_own_property_descriptors(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(O).
let obj = args.get_or_undefined(0).to_object(context)?;
// 2. Let ownKeys be ? obj.[[OwnPropertyKeys]]().
let own_keys = obj.__own_property_keys__(&mut InternalMethodContext::new(context))?;
// 3. Let descriptors be OrdinaryObjectCreate(%Object.prototype%).
let descriptors = JsObject::with_object_proto(context.intrinsics());
// 4. For each element key of ownKeys, do
for key in own_keys {
// a. Let desc be ? obj.[[GetOwnProperty]](key).
let desc = obj.__get_own_property__(&key, &mut InternalMethodContext::new(context))?;
// b. Let descriptor be FromPropertyDescriptor(desc).
let descriptor = Self::from_property_descriptor(desc, context);
// c. If descriptor is not undefined,
// perform ! CreateDataPropertyOrThrow(descriptors, key, descriptor).
if !descriptor.is_undefined() {
descriptors
.create_data_property_or_throw(key, descriptor, context)
.expect("should not fail according to spec");
}
}
// 5. Return descriptors.
Ok(descriptors.into())
}
/// The abstract operation `FromPropertyDescriptor`.
///
/// [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-frompropertydescriptor
pub(crate) fn from_property_descriptor(
desc: Option<PropertyDescriptor>,
context: &mut Context,
) -> JsValue {
// 1. If Desc is undefined, return undefined.
let Some(desc) = desc else {
return JsValue::undefined();
};
// 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
// 3. Assert: obj is an extensible ordinary object with no own properties.
let obj = JsObject::with_object_proto(context.intrinsics());
// 4. If Desc has a [[Value]] field, then
if let Some(value) = desc.value() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "value", Desc.[[Value]]).
obj.create_data_property_or_throw(utf16!("value"), value.clone(), context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 5. If Desc has a [[Writable]] field, then
if let Some(writable) = desc.writable() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "writable", Desc.[[Writable]]).
obj.create_data_property_or_throw(utf16!("writable"), writable, context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 6. If Desc has a [[Get]] field, then
if let Some(get) = desc.get() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "get", Desc.[[Get]]).
obj.create_data_property_or_throw(utf16!("get"), get.clone(), context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 7. If Desc has a [[Set]] field, then
if let Some(set) = desc.set() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "set", Desc.[[Set]]).
obj.create_data_property_or_throw(utf16!("set"), set.clone(), context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 8. If Desc has an [[Enumerable]] field, then
if let Some(enumerable) = desc.enumerable() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "enumerable", Desc.[[Enumerable]]).
obj.create_data_property_or_throw(utf16!("enumerable"), enumerable, context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 9. If Desc has a [[Configurable]] field, then
if let Some(configurable) = desc.configurable() {
// a. Perform ! CreateDataPropertyOrThrow(obj, "configurable", Desc.[[Configurable]]).
obj.create_data_property_or_throw(utf16!("configurable"), configurable, context)
.expect("CreateDataPropertyOrThrow cannot fail here");
}
// 10. Return obj.
obj.into()
}
/// Uses the `SameValue` algorithm to check equality of objects
pub fn is(_: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
let x = args.get_or_undefined(0);
let y = args.get_or_undefined(1);
Ok(JsValue::same_value(x, y).into())
}
/// Get the `prototype` of an object.
///
/// [More information][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.setprototypeof
pub fn get_prototype_of(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
if args.is_empty() {
return Err(JsNativeError::typ()
.with_message(
"Object.getPrototypeOf: At least 1 argument required, but only 0 passed",
)
.into());
}
// 1. Let obj be ? ToObject(O).
let obj = args[0].clone().to_object(context)?;
// 2. Return ? obj.[[GetPrototypeOf]]().
Ok(obj
.__get_prototype_of__(&mut InternalMethodContext::new(context))?
.map_or(JsValue::Null, JsValue::new))
}
/// Set the `prototype` of an object.
///
/// [More information][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.setprototypeof
pub fn set_prototype_of(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
if args.len() < 2 {
return Err(JsNativeError::typ()
.with_message(format!(
"Object.setPrototypeOf: At least 2 arguments required, but only {} passed",
args.len()
))
.into());
}
// 1. Set O to ? RequireObjectCoercible(O).
let o = args
.first()
.cloned()
.unwrap_or_default()
.require_object_coercible()?
.clone();
let proto = match args.get_or_undefined(1) {
JsValue::Object(obj) => Some(obj.clone()),
JsValue::Null => None,
// 2. If Type(proto) is neither Object nor Null, throw a TypeError exception.
val => {
return Err(JsNativeError::typ()
.with_message(format!(
"expected an object or null, got `{}`",
val.type_of()
))
.into())
}
};
let Some(obj) = o.as_object() else {
// 3. If Type(O) is not Object, return O.
return Ok(o);
};
// 4. Let status be ? O.[[SetPrototypeOf]](proto).
let status = obj.__set_prototype_of__(proto, &mut InternalMethodContext::new(context))?;
// 5. If status is false, throw a TypeError exception.
if !status {
return Err(JsNativeError::typ()
.with_message("can't set prototype of this object")
.into());
}
// 6. Return O.
Ok(o)
}
/// `Object.prototype.isPrototypeOf( proto )`
///
/// Check whether or not an object exists within another object's prototype chain.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.isprototypeof
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf
pub fn is_prototype_of(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let v = args.get_or_undefined(0);
if !v.is_object() {
return Ok(JsValue::new(false));
}
let mut v = v.clone();
let o = JsValue::new(this.to_object(context)?);
loop {
v = Self::get_prototype_of(this, &[v], context)?;
if v.is_null() {
return Ok(JsValue::new(false));
}
if JsValue::same_value(&o, &v) {
return Ok(JsValue::new(true));
}
}
}
/// Define a property in an object
pub fn define_property(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let object = args.get_or_undefined(0);
if let JsValue::Object(object) = object {
let key = args
.get(1)
.unwrap_or(&JsValue::Undefined)
.to_property_key(context)?;
let desc = args
.get(2)
.unwrap_or(&JsValue::Undefined)
.to_property_descriptor(context)?;
object.define_property_or_throw(key, desc, context)?;
Ok(object.clone().into())
} else {
Err(JsNativeError::typ()
.with_message("Object.defineProperty called on non-object")
.into())
}
}
/// `Object.defineProperties( proto, [propertiesObject] )`
///
/// Creates or update own properties to the object
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.defineproperties
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
pub fn define_properties(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let arg = args.get_or_undefined(0);
if let JsValue::Object(obj) = arg {
let props = args.get_or_undefined(1);
object_define_properties(obj, props, context)?;
Ok(arg.clone())
} else {
Err(JsNativeError::typ()
.with_message("Expected an object")
.into())
}
}
/// `Object.prototype.valueOf()`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.valueof
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
pub fn value_of(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Return ? ToObject(this value).
Ok(this.to_object(context)?.into())
}
/// `Object.prototype.toString()`
///
/// This method returns a string representing the object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.tostring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
#[allow(clippy::wrong_self_convention)]
pub fn to_string(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. If the this value is undefined, return "[object Undefined]".
if this.is_undefined() {
return Ok(js_string!("[object Undefined]").into());
}
// 2. If the this value is null, return "[object Null]".
if this.is_null() {
return Ok(js_string!("[object Null]").into());
}
// 3. Let O be ! ToObject(this value).
let o = this.to_object(context).expect("toObject cannot fail here");
// 4. Let isArray be ? IsArray(O).
// 5. If isArray is true, let builtinTag be "Array".
let builtin_tag = if o.is_array_abstract()? {
utf16!("Array")
} else {
let o_borrow = o.borrow();
if o_borrow.is_arguments() {
// 6. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
utf16!("Arguments")
} else if o.is_callable() {
// 7. Else if O has a [[Call]] internal method, let builtinTag be "Function".
utf16!("Function")
} else if o.is::<ErrorObject>() {
// 8. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
utf16!("Error")
} else if o.is::<bool>() {
// 9. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
utf16!("Boolean")
} else if o.is::<f64>() {
// 10. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
utf16!("Number")
} else if o.is::<JsString>() {
// 11. Else if O has a [[StringData]] internal slot, let builtinTag be "String".
utf16!("String")
} else if o.is::<Date>() {
// 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
utf16!("Date")
} else if o.is::<RegExp>() {
// 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
utf16!("RegExp")
} else {
// 14. Else, let builtinTag be "Object".
utf16!("Object")
}
};
// 15. Let tag be ? Get(O, @@toStringTag).
let tag = o.get(JsSymbol::to_string_tag(), context)?;
// 16. If Type(tag) is not String, set tag to builtinTag.
let tag_str = tag.as_string().map_or(builtin_tag, JsString::deref);
// 17. Return the string-concatenation of "[object ", tag, and "]".
Ok(js_string!(utf16!("[object "), tag_str, utf16!("]")).into())
}
/// `Object.prototype.toLocaleString( [ reserved1 [ , reserved2 ] ] )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.tolocalestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString
#[allow(clippy::wrong_self_convention)]
pub fn to_locale_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be the this value.
// 2. Return ? Invoke(O, "toString").
this.invoke(utf16!("toString"), &[], context)
}
/// `Object.prototype.hasOwnProperty( property )`
///
/// The method returns a boolean indicating whether the object has the specified property
/// as its own property (as opposed to inheriting it).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.hasownproperty
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
pub fn has_own_property(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let P be ? ToPropertyKey(V).
let key = args.get_or_undefined(0).to_property_key(context)?;
// 2. Let O be ? ToObject(this value).
let object = this.to_object(context)?;
// 3. Return ? HasOwnProperty(O, P).
Ok(object.has_own_property(key, context)?.into())
}
/// `Object.prototype.propertyIsEnumerable( property )`
///
/// This method returns a Boolean indicating whether the specified property is
/// enumerable and is the object's own property.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable
pub fn property_is_enumerable(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let Some(key) = args.first() else {
return Ok(JsValue::new(false));
};
let key = key.to_property_key(context)?;
let own_prop = this
.to_object(context)?
.__get_own_property__(&key, &mut InternalMethodContext::new(context))?;
own_prop
.as_ref()
.and_then(PropertyDescriptor::enumerable)
.unwrap_or_default()
.conv::<JsValue>()
.pipe(Ok)
}
/// `Object.assign( target, ...sources )`
///
/// This method copies all enumerable own properties from one or more
/// source objects to a target object. It returns the target object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.assign
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
pub fn assign(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let to be ? ToObject(target).
let to = args.get_or_undefined(0).to_object(context)?;
// 2. If only one argument was passed, return to.
if args.len() == 1 {
return Ok(to.into());
}
// 3. For each element nextSource of sources, do
for source in &args[1..] {
// 3.a. If nextSource is neither undefined nor null, then
if !source.is_null_or_undefined() {
// 3.a.i. Let from be ! ToObject(nextSource).
let from = source
.to_object(context)
.expect("this ToObject call must not fail");
// 3.a.ii. Let keys be ? from.[[OwnPropertyKeys]]().
let keys = from.__own_property_keys__(&mut InternalMethodContext::new(context))?;
// 3.a.iii. For each element nextKey of keys, do
for key in keys {
// 3.a.iii.1. Let desc be ? from.[[GetOwnProperty]](nextKey).
if let Some(desc) =
from.__get_own_property__(&key, &mut InternalMethodContext::new(context))?
{
// 3.a.iii.2. If desc is not undefined and desc.[[Enumerable]] is true, then
if desc.expect_enumerable() {
// 3.a.iii.2.a. Let propValue be ? Get(from, nextKey).
let property = from.get(key.clone(), context)?;
// 3.a.iii.2.b. Perform ? Set(to, nextKey, propValue, true).
to.set(key, property, true, context)?;
}
}
}
}
}
// 4. Return to.
Ok(to.into())
}
/// `Object.keys( target )`
///
/// This method returns an array of a given object's own enumerable
/// property names, iterated in the same order that a normal loop would.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.keys
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
pub fn keys(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(target).
let obj = args
.first()
.cloned()
.unwrap_or_default()
.to_object(context)?;
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, key).
let name_list = obj.enumerable_own_property_names(PropertyNameKind::Key, context)?;
// 3. Return CreateArrayFromList(nameList).
let result = Array::create_array_from_list(name_list, context);
Ok(result.into())
}
/// `Object.values( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.values
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
pub fn values(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(target).
let obj = args
.first()
.cloned()
.unwrap_or_default()
.to_object(context)?;
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, value).
let name_list = obj.enumerable_own_property_names(PropertyNameKind::Value, context)?;
// 3. Return CreateArrayFromList(nameList).
let result = Array::create_array_from_list(name_list, context);
Ok(result.into())
}
/// `Object.entries( target )`
///
/// This method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
/// This is the same as iterating with a for...in loop,
/// except that a for...in loop enumerates properties in the prototype chain as well).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.entries
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
pub fn entries(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(target).
let obj = args
.first()
.cloned()
.unwrap_or_default()
.to_object(context)?;
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, key+value).
let name_list =
obj.enumerable_own_property_names(PropertyNameKind::KeyAndValue, context)?;
// 3. Return CreateArrayFromList(nameList).
let result = Array::create_array_from_list(name_list, context);
Ok(result.into())
}
/// `Object.seal( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.seal
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
pub fn seal(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
if let Some(o) = o.as_object() {
// 2. Let status be ? SetIntegrityLevel(O, sealed).
let status = o.set_integrity_level(IntegrityLevel::Sealed, context)?;
// 3. If status is false, throw a TypeError exception.
if !status {
return Err(JsNativeError::typ()
.with_message("cannot seal object")
.into());
}
}
// 1. If Type(O) is not Object, return O.
// 4. Return O.
Ok(o.clone())
}
/// `Object.isSealed( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.issealed
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed
pub fn is_sealed(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
// 1. If Type(O) is not Object, return true.
// 2. Return ? TestIntegrityLevel(O, sealed).
if let Some(o) = o.as_object() {
Ok(o.test_integrity_level(IntegrityLevel::Sealed, context)?
.into())
} else {
Ok(JsValue::new(true))
}
}
/// `Object.freeze( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.freeze
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
pub fn freeze(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
if let Some(o) = o.as_object() {
// 2. Let status be ? SetIntegrityLevel(O, frozen).
let status = o.set_integrity_level(IntegrityLevel::Frozen, context)?;
// 3. If status is false, throw a TypeError exception.
if !status {
return Err(JsNativeError::typ()
.with_message("cannot freeze object")
.into());
}
}
// 1. If Type(O) is not Object, return O.
// 4. Return O.
Ok(o.clone())
}
/// `Object.isFrozen( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.isfrozen
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen
pub fn is_frozen(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
// 1. If Type(O) is not Object, return true.
// 2. Return ? TestIntegrityLevel(O, frozen).
if let Some(o) = o.as_object() {
Ok(o.test_integrity_level(IntegrityLevel::Frozen, context)?
.into())
} else {
Ok(JsValue::new(true))
}
}
/// `Object.preventExtensions( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.preventextensions
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions
pub fn prevent_extensions(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
if let Some(o) = o.as_object() {
// 2. Let status be ? O.[[PreventExtensions]]().
let status = o.__prevent_extensions__(&mut InternalMethodContext::new(context))?;
// 3. If status is false, throw a TypeError exception.
if !status {
return Err(JsNativeError::typ()
.with_message("cannot prevent extensions")
.into());
}
}
// 1. If Type(O) is not Object, return O.
// 4. Return O.
Ok(o.clone())
}
/// `Object.isExtensible( target )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.isextensible
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible
pub fn is_extensible(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let o = args.get_or_undefined(0);
// 1. If Type(O) is not Object, return false.
if let Some(o) = o.as_object() {
// 2. Return ? IsExtensible(O).
Ok(o.is_extensible(context)?.into())
} else {
Ok(JsValue::new(false))
}
}
/// `Object.getOwnPropertyNames( object )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.getownpropertynames
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
pub fn get_own_property_names(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Return ? GetOwnPropertyKeys(O, string).
let o = args.get_or_undefined(0);
get_own_property_keys(o, PropertyKeyType::String, context)
}
/// `Object.getOwnPropertySymbols( object )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.getownpropertysymbols
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols
pub fn get_own_property_symbols(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Return ? GetOwnPropertyKeys(O, symbol).
let o = args.get_or_undefined(0);
get_own_property_keys(o, PropertyKeyType::Symbol, context)
}
/// `Object.hasOwn( object, property )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.hasown
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
pub fn has_own(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(O).
let obj = args.get_or_undefined(0).to_object(context)?;
// 2. Let key be ? ToPropertyKey(P).
let key = args.get_or_undefined(1).to_property_key(context)?;
// 3. Return ? HasOwnProperty(obj, key).
Ok(obj.has_own_property(key, context)?.into())
}
/// `Object.fromEntries( iterable )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.fromentries
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
pub fn from_entries(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Perform ? RequireObjectCoercible(iterable).
let iterable = args.get_or_undefined(0).require_object_coercible()?;
// 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
// 3. Assert: obj is an extensible ordinary object with no own properties.
let obj = JsObject::with_object_proto(context.intrinsics());
// 4. Let closure be a new Abstract Closure with parameters (key, value) that captures
// obj and performs the following steps when called:
let closure = FunctionObjectBuilder::new(
context.realm(),
NativeFunction::from_copy_closure_with_captures(
|_, args, obj, context| {
let key = args.get_or_undefined(0);
let value = args.get_or_undefined(1);
// a. Let propertyKey be ? ToPropertyKey(key).
let property_key = key.to_property_key(context)?;
// b. Perform ! CreateDataPropertyOrThrow(obj, propertyKey, value).
obj.create_data_property_or_throw(property_key, value.clone(), context)?;
// c. Return undefined.
Ok(JsValue::undefined())
},
obj.clone(),
),
);
// 5. Let adder be ! CreateBuiltinFunction(closure, 2, "", « »).
let adder = closure.length(2).name("").build();
// 6. Return ? AddEntriesFromIterable(obj, iterable, adder).
map::add_entries_from_iterable(&obj, iterable, &adder.into(), context)
}
/// [`Object.groupBy ( items, callbackfn )`][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.groupby
pub(crate) fn group_by(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
use std::hash::BuildHasherDefault;
use indexmap::IndexMap;
use rustc_hash::FxHasher;
use crate::builtins::{iterable::if_abrupt_close_iterator, Number};
let items = args.get_or_undefined(0);
let callback = args.get_or_undefined(1);
// 1. Let groups be ? GroupBy(items, callbackfn, property).
// `GroupBy`
// https://tc39.es/proposal-array-grouping/#sec-group-by
// inlined to change the key type.
// 1. Perform ? RequireObjectCoercible(items).
items.require_object_coercible()?;
// 2. If IsCallable(callbackfn) is false, throw a TypeError exception.
let callback = callback.as_callable().ok_or_else(|| {
JsNativeError::typ().with_message("callback must be a callable object")
})?;
// 3. Let groups be a new empty List.
let mut groups: IndexMap<PropertyKey, Vec<JsValue>, BuildHasherDefault<FxHasher>> =
IndexMap::default();
// 4. Let iteratorRecord be ? GetIterator(items).
let mut iterator = items.get_iterator(context, None, None)?;
// 5. Let k be 0.
let mut k = 0u64;
// 6. Repeat,
loop {
// a. If k ≥ 2^53 - 1, then
if k >= Number::MAX_SAFE_INTEGER as u64 {
// i. Let error be ThrowCompletion(a newly created TypeError object).
let error = JsNativeError::typ()
.with_message("exceeded maximum safe integer")
.into();
// ii. Return ? IteratorClose(iteratorRecord, error).
return iterator.close(Err(error), context);
}
// b. Let next be ? IteratorStep(iteratorRecord).
let done = iterator.step(context)?;
// c. If next is false, then
if done {
// i. Return groups.
break;
}
// d. Let value be ? IteratorValue(next).
let value = iterator.value(context)?;
// e. Let key be Completion(Call(callbackfn, undefined, « value, 𝔽(k) »)).
let key = callback.call(&JsValue::undefined(), &[value.clone(), k.into()], context);
// f. IfAbruptCloseIterator(key, iteratorRecord).
let key = if_abrupt_close_iterator!(key, iterator, context);
// g. If keyCoercion is property, then
// i. Set key to Completion(ToPropertyKey(key)).
let key = key.to_property_key(context);
// ii. IfAbruptCloseIterator(key, iteratorRecord).
let key = if_abrupt_close_iterator!(key, iterator, context);
// i. Perform AddValueToKeyedGroup(groups, key, value).
groups.entry(key).or_default().push(value);
// j. Set k to k + 1.
k += 1;
}
// 2. Let obj be OrdinaryObjectCreate(null).
let obj = JsObject::with_null_proto();
// 3. For each Record { [[Key]], [[Elements]] } g of groups, do
for (key, elements) in groups {
// a. Let elements be CreateArrayFromList(g.[[Elements]]).
let elements = Array::create_array_from_list(elements, context);
// b. Perform ! CreateDataPropertyOrThrow(obj, g.[[Key]], elements).
obj.create_data_property_or_throw(key, elements, context)
.expect("cannot fail for a newly created object");
}
// 4. Return obj.
Ok(obj.into())
}
}
/// The abstract operation `ObjectDefineProperties`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-object.defineproperties
fn object_define_properties(
object: &JsObject,
props: &JsValue,
context: &mut Context,
) -> JsResult<()> {
// 1. Assert: Type(O) is Object.
// 2. Let props be ? ToObject(Properties).
let props = &props.to_object(context)?;
// 3. Let keys be ? props.[[OwnPropertyKeys]]().
let keys = props.__own_property_keys__(&mut InternalMethodContext::new(context))?;
// 4. Let descriptors be a new empty List.
let mut descriptors: Vec<(PropertyKey, PropertyDescriptor)> = Vec::new();
// 5. For each element nextKey of keys, do
for next_key in keys {
// a. Let propDesc be ? props.[[GetOwnProperty]](nextKey).
// b. If propDesc is not undefined and propDesc.[[Enumerable]] is true, then
if let Some(prop_desc) =
props.__get_own_property__(&next_key, &mut InternalMethodContext::new(context))?
{
if prop_desc.expect_enumerable() {
// i. Let descObj be ? Get(props, nextKey).
let desc_obj = props.get(next_key.clone(), context)?;
// ii. Let desc be ? ToPropertyDescriptor(descObj).
let desc = desc_obj.to_property_descriptor(context)?;
// iii. Append the pair (a two element List) consisting of nextKey and desc to the end of descriptors.
descriptors.push((next_key, desc));
}
}
}
// 6. For each element pair of descriptors, do
// a. Let P be the first element of pair.
// b. Let desc be the second element of pair.
for (p, d) in descriptors {
// c. Perform ? DefinePropertyOrThrow(O, P, desc).
object.define_property_or_throw(p, d, context)?;
}
// 7. Return O.
Ok(())
}
/// Type enum used in the abstract operation `GetOwnPropertyKeys`.
#[derive(Debug, Copy, Clone)]
enum PropertyKeyType {
String,
Symbol,
}
/// The abstract operation `GetOwnPropertyKeys`.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-getownpropertykeys
fn get_own_property_keys(
o: &JsValue,
r#type: PropertyKeyType,
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let obj be ? ToObject(o).
let obj = o.to_object(context)?;
// 2. Let keys be ? obj.[[OwnPropertyKeys]]().
let keys = obj.__own_property_keys__(&mut InternalMethodContext::new(context))?;
// 3. Let nameList be a new empty List.
// 4. For each element nextKey of keys, do
let name_list = keys.iter().filter_map(|next_key| {
// a. If Type(nextKey) is Symbol and type is symbol or Type(nextKey) is String and type is string, then
// i. Append nextKey as the last element of nameList.
match (r#type, &next_key) {
(PropertyKeyType::String, PropertyKey::String(_))
| (PropertyKeyType::Symbol, PropertyKey::Symbol(_)) => Some(next_key.into()),
(PropertyKeyType::String, PropertyKey::Index(index)) => {
Some(js_string!(index.get().to_string()).into())
}
_ => None,
}
});
// 5. Return CreateArrayFromList(nameList).
Ok(Array::create_array_from_list(name_list, context).into())
}