-
-
Notifications
You must be signed in to change notification settings - Fork 620
Expand file tree
/
Copy pathmod.rs
More file actions
1526 lines (1345 loc) · 57 KB
/
mod.rs
File metadata and controls
1526 lines (1345 loc) · 57 KB
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
//! 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 super::{
Array, BuiltInBuilder, BuiltInConstructor, Date, IntrinsicObject, RegExp, error::Error,
};
use crate::builtins::function::arguments::{MappedArguments, UnmappedArguments};
use crate::property::CompletePropertyDescriptor;
use crate::value::JsVariant;
use crate::{
Context, JsArgs, JsData, JsExpect, JsResult, JsString,
builtins::{BuiltInObject, iterable::IteratorHint, map},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
js_error, js_string,
native_function::NativeFunction,
object::{
FunctionObjectBuilder, IntegrityLevel, JsObject,
internal_methods::{InternalMethodPropertyContext, get_prototype_from_constructor},
},
property::{Attribute, PropertyDescriptor, PropertyKey, PropertyNameKind},
realm::Realm,
string::StaticJsStrings,
symbol::JsSymbol,
value::JsValue,
};
use boa_gc::{Finalize, Trace};
use boa_macros::js_str;
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 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__"))
.length(1)
.build();
BuiltInBuilder::from_standard_constructor::<Self>(realm)
.inherits(None)
.accessor(
js_string!("__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 CONSTRUCTOR_ARGUMENTS: usize = 1;
const PROTOTYPE_STORAGE_SLOTS: usize = 12;
const CONSTRUCTOR_STORAGE_SLOTS: usize = 23;
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 InternalMethodPropertyContext::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).variant() {
JsVariant::Object(proto) => Some(proto.clone()),
JsVariant::Null => None,
_ => return Ok(JsValue::undefined()),
};
// 3. If Type(O) is not Object, return undefined.
let JsVariant::Object(object) = this.variant() else {
return Ok(JsValue::undefined());
};
// 4. Let status be ? O.[[SetPrototypeOf]](proto).
let status =
object.__set_prototype_of__(proto, &mut InternalMethodPropertyContext::new(context))?;
// 5. If status is false, throw a TypeError exception.
if !status {
return Err(js_error!(TypeError: "__proto__ called on null or undefined"));
}
// 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(js_error!(TypeError:
"Object.prototype.__defineGetter__: expected 'getter' to be a Function object",
));
}
// 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(js_error!(TypeError:
"Object.prototype.__defineSetter__: expected 'setter' to be a Function object",
));
}
// 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 InternalMethodPropertyContext::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 let CompletePropertyDescriptor::Accessor { get, .. } = current_desc {
Ok(get.map(JsValue::new).unwrap_or_default())
} else {
// ii. Return undefined.
Ok(JsValue::undefined())
};
}
match obj.__get_prototype_of__(&mut InternalMethodPropertyContext::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 InternalMethodPropertyContext::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 let CompletePropertyDescriptor::Accessor { set, .. } = current_desc {
Ok(set.map(JsValue::new).unwrap_or_default())
} else {
// ii. Return undefined.
Ok(JsValue::undefined())
};
}
match obj.__get_prototype_of__(&mut InternalMethodPropertyContext::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.variant() {
JsVariant::Object(_) | JsVariant::Null => {
JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
prototype.as_object(),
OrdinaryObject,
)
.upcast()
}
_ => {
return Err(js_error!(TypeError:
"Object.create: expected 'proto' to be an Object or null, got `{}`",
prototype.type_of()
));
}
};
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 InternalMethodPropertyContext::new(context))?;
// 4. Return FromPropertyDescriptor(desc).
Self::from_property_descriptor(desc.map(Into::into), 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 InternalMethodPropertyContext::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 InternalMethodPropertyContext::new(context))?;
// b. Let descriptor be FromPropertyDescriptor(desc).
let descriptor = Self::from_property_descriptor(desc.map(Into::into), context)
.expect("should never fail");
// c. If descriptor is not undefined,
// perform ! CreateDataPropertyOrThrow(descriptors, key, descriptor).
if !descriptor.is_undefined() {
descriptors
.create_data_property_or_throw(key, descriptor, context)
.js_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,
) -> JsResult<JsValue> {
// 1. If Desc is undefined, return undefined.
let Some(desc) = desc else {
return Ok(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(js_string!("value"), value.clone(), context)
.js_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(js_string!("writable"), writable, context)
.js_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(js_string!("get"), get.clone(), context)
.js_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(js_string!("set"), set.clone(), context)
.js_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(js_string!("enumerable"), enumerable, context)
.js_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(js_string!("configurable"), configurable, context)
.js_expect("CreateDataPropertyOrThrow cannot fail here")?;
}
// 10. Return obj.
Ok(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(js_error!(TypeError:
"Object.getPrototypeOf: At least 1 argument required, but only 0 passed",
));
}
// 1. Let obj be ? ToObject(O).
let obj = args[0].clone().to_object(context)?;
// 2. Return ? obj.[[GetPrototypeOf]]().
Ok(obj
.__get_prototype_of__(&mut InternalMethodPropertyContext::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(js_error!(TypeError:
"Object.setPrototypeOf: At least 2 arguments required, but only {} passed",
args.len()
));
}
// 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).variant() {
JsVariant::Object(obj) => Some(obj.clone()),
JsVariant::Null => None,
// 2. If Type(proto) is neither Object nor Null, throw a TypeError exception.
val => {
return Err(js_error!(TypeError:
"Object.setPrototypeOf: expected 'proto' to be an Object or null, got `{}`",
val.type_of()
));
}
};
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 InternalMethodPropertyContext::new(context))?;
if !status {
return Err(js_error!(TypeError: "can't set prototype of this object"));
}
// 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> {
if let Some(object) = args.get_or_undefined(0).as_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(js_error!(TypeError: "Object.defineProperty: expected 'this' to be an Object"))
}
}
/// `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 Some(obj) = arg.as_object() {
let props = args.get_or_undefined(1);
object_define_properties(&obj, props, context)?;
Ok(arg.clone())
} else {
Err(js_error!(TypeError: "Object.defineProperties: expected 'this' to be an Object"))
}
}
/// `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)
.js_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()? {
js_str!("Array")
} else if o.is::<UnmappedArguments>() || o.is::<MappedArguments>() {
// 6. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
js_str!("Arguments")
} else if o.is_callable() {
// 7. Else if O has a [[Call]] internal method, let builtinTag be "Function".
js_str!("Function")
} else if o.is::<Error>() {
// 8. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
js_str!("Error")
} else if o.is::<bool>() {
// 9. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
js_str!("Boolean")
} else if o.is::<f64>() {
// 10. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
js_str!("Number")
} else if o.is::<JsString>() {
// 11. Else if O has a [[StringData]] internal slot, let builtinTag be "String".
js_str!("String")
} else if o.is::<Date>() {
// 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
js_str!("Date")
} else if o.is::<RegExp>() {
// 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
js_str!("RegExp")
} else {
// 14. Else, let builtinTag be "Object".
js_str!("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 = tag.as_string();
let tag = tag.as_ref().map_or(builtin_tag, JsString::as_str);
// 17. Return the string-concatenation of "[object ", tag, and "]".
Ok(js_string!(js_str!("[object "), tag, js_str!("]")).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(js_string!("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 InternalMethodPropertyContext::new(context))?;
Ok(own_prop
.as_ref()
.is_some_and(CompletePropertyDescriptor::enumerable)
.into())
}
/// `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)
.js_expect("this ToObject call must not fail")?;
// 3.a.ii. Let keys be ? from.[[OwnPropertyKeys]]().
let keys =
from.__own_property_keys__(&mut InternalMethodPropertyContext::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 InternalMethodPropertyContext::new(context),
)? {
// 3.a.iii.2. If desc is not undefined and desc.[[Enumerable]] is true, then
if desc.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)?;
}
}
}
}