summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/ObjectConstructor.cpp
blob: 8a40e2b17fbf5835a5623f2f473d9c9ac5bf478c (plain)
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
/*
 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Function.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/IteratorOperations.h>
#include <LibJS/Runtime/ObjectConstructor.h>
#include <LibJS/Runtime/ProxyObject.h>
#include <LibJS/Runtime/Shape.h>

namespace JS {

ObjectConstructor::ObjectConstructor(GlobalObject& global_object)
    : NativeFunction(vm().names.Object.as_string(), *global_object.function_prototype())
{
}

void ObjectConstructor::initialize(GlobalObject& global_object)
{
    auto& vm = this->vm();
    NativeFunction::initialize(global_object);

    // 20.1.2.19 Object.prototype, https://tc39.es/ecma262/#sec-object.prototype
    define_direct_property(vm.names.prototype, global_object.object_prototype(), 0);

    u8 attr = Attribute::Writable | Attribute::Configurable;
    define_native_function(vm.names.defineProperty, define_property, 3, attr);
    define_native_function(vm.names.defineProperties, define_properties, 2, attr);
    define_native_function(vm.names.is, is, 2, attr);
    define_native_function(vm.names.getOwnPropertyDescriptor, get_own_property_descriptor, 2, attr);
    define_native_function(vm.names.getOwnPropertyDescriptors, get_own_property_descriptors, 1, attr);
    define_native_function(vm.names.getOwnPropertyNames, get_own_property_names, 1, attr);
    define_native_function(vm.names.getOwnPropertySymbols, get_own_property_symbols, 1, attr);
    define_native_function(vm.names.getPrototypeOf, get_prototype_of, 1, attr);
    define_native_function(vm.names.setPrototypeOf, set_prototype_of, 2, attr);
    define_native_function(vm.names.isExtensible, is_extensible, 1, attr);
    define_native_function(vm.names.isFrozen, is_frozen, 1, attr);
    define_native_function(vm.names.isSealed, is_sealed, 1, attr);
    define_native_function(vm.names.preventExtensions, prevent_extensions, 1, attr);
    define_native_function(vm.names.freeze, freeze, 1, attr);
    define_native_function(vm.names.fromEntries, from_entries, 1, attr);
    define_native_function(vm.names.seal, seal, 1, attr);
    define_native_function(vm.names.keys, keys, 1, attr);
    define_native_function(vm.names.values, values, 1, attr);
    define_native_function(vm.names.entries, entries, 1, attr);
    define_native_function(vm.names.create, create, 2, attr);
    define_native_function(vm.names.hasOwn, has_own, 2, attr);
    define_native_function(vm.names.assign, assign, 2, attr);

    define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
}

ObjectConstructor::~ObjectConstructor()
{
}

// 20.1.1.1 Object ( [ value ] ), https://tc39.es/ecma262/#sec-object-value
Value ObjectConstructor::call()
{
    return construct(*this);
}

// 20.1.1.1 Object ( [ value ] ), https://tc39.es/ecma262/#sec-object-value
Value ObjectConstructor::construct(FunctionObject& new_target)
{
    auto& vm = this->vm();
    auto& global_object = this->global_object();

    if (&new_target != this)
        return TRY_OR_DISCARD(ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype));
    auto value = vm.argument(0);
    if (value.is_nullish())
        return Object::create(global_object, global_object.object_prototype());
    return TRY_OR_DISCARD(value.to_object(global_object));
}

enum class GetOwnPropertyKeysType {
    String,
    Symbol,
};

// 20.1.2.11.1 GetOwnPropertyKeys ( O, type ), https://tc39.es/ecma262/#sec-getownpropertykeys
static Array* get_own_property_keys(GlobalObject& global_object, Value value, GetOwnPropertyKeysType type)
{
    auto& vm = global_object.vm();

    // 1. Let obj be ? ToObject(O).
    auto* object = TRY_OR_DISCARD(value.to_object(global_object));

    // 2. Let keys be ? obj.[[OwnPropertyKeys]]().
    auto keys = TRY_OR_DISCARD(object->internal_own_property_keys());

    // 3. Let nameList be a new empty List.
    auto name_list = MarkedValueList { vm.heap() };

    // 4. For each element nextKey of keys, do
    for (auto& next_key : keys) {
        // a. If Type(nextKey) is Symbol and type is symbol or Type(nextKey) is String and type is string, then
        if ((next_key.is_symbol() && type == GetOwnPropertyKeysType::Symbol) || (next_key.is_string() && type == GetOwnPropertyKeysType::String)) {
            // i. Append nextKey as the last element of nameList.
            name_list.append(next_key);
        }
    }

    // 5. Return CreateArrayFromList(nameList).
    return Array::create_from(global_object, name_list);
}

// 20.1.2.10 Object.getOwnPropertyNames ( O ), https://tc39.es/ecma262/#sec-object.getownpropertynames
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_names)
{
    // 1. Return ? GetOwnPropertyKeys(O, string).
    return get_own_property_keys(global_object, vm.argument(0), GetOwnPropertyKeysType::String);
}

// 20.1.2.11 Object.getOwnPropertySymbols ( O ), https://tc39.es/ecma262/#sec-object.getownpropertysymbols
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_symbols)
{
    // 1. Return ? GetOwnPropertyKeys(O, symbol).
    return get_own_property_keys(global_object, vm.argument(0), GetOwnPropertyKeysType::Symbol);
}

// 20.1.2.12 Object.getPrototypeOf ( O ), https://tc39.es/ecma262/#sec-object.getprototypeof
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_prototype_of)
{
    // 1. Let obj be ? ToObject(O).
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));

    // 2. Return ? obj.[[GetPrototypeOf]]().
    return TRY_OR_DISCARD(object->internal_get_prototype_of());
}

// 20.1.2.21 Object.setPrototypeOf ( O, proto ), https://tc39.es/ecma262/#sec-object.setprototypeof
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::set_prototype_of)
{
    auto proto = vm.argument(1);

    // 1. Set O to ? RequireObjectCoercible(O).
    auto object = TRY_OR_DISCARD(require_object_coercible(global_object, vm.argument(0)));

    // 2. If Type(proto) is neither Object nor Null, throw a TypeError exception.
    if (!proto.is_object() && !proto.is_null()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectPrototypeWrongType);
        return {};
    }

    // 3. If Type(O) is not Object, return O.
    if (!object.is_object())
        return object;

    // 4. Let status be ? O.[[SetPrototypeOf]](proto).
    auto status = TRY_OR_DISCARD(object.as_object().internal_set_prototype_of(proto.is_null() ? nullptr : &proto.as_object()));

    // 5. If status is false, throw a TypeError exception.
    if (!status) {
        // FIXME: Improve/contextualize error message
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectSetPrototypeOfReturnedFalse);
        return {};
    }

    // 6. Return O.
    return object;
}

// 20.1.2.14 Object.isExtensible ( O ), https://tc39.es/ecma262/#sec-object.isextensible
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::is_extensible)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return Value(false);
    return Value(TRY_OR_DISCARD(argument.as_object().is_extensible()));
}

// 20.1.2.15 Object.isFrozen ( O ), https://tc39.es/ecma262/#sec-object.isfrozen
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::is_frozen)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return Value(true);
    return Value(TRY_OR_DISCARD(argument.as_object().test_integrity_level(Object::IntegrityLevel::Frozen)));
}

// 20.1.2.16 Object.isSealed ( O ), https://tc39.es/ecma262/#sec-object.issealed
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::is_sealed)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return Value(true);
    return Value(TRY_OR_DISCARD(argument.as_object().test_integrity_level(Object::IntegrityLevel::Sealed)));
}

// 20.1.2.18 Object.preventExtensions ( O ), https://tc39.es/ecma262/#sec-object.preventextensions
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::prevent_extensions)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return argument;
    auto status = TRY_OR_DISCARD(argument.as_object().internal_prevent_extensions());
    if (!status) {
        // FIXME: Improve/contextualize error message
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectPreventExtensionsReturnedFalse);
        return {};
    }
    return argument;
}

// 20.1.2.6 Object.freeze ( O ), https://tc39.es/ecma262/#sec-object.freeze
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::freeze)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return argument;
    auto status = TRY_OR_DISCARD(argument.as_object().set_integrity_level(Object::IntegrityLevel::Frozen));
    if (!status) {
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectFreezeFailed);
        return {};
    }
    return argument;
}

// 20.1.2.7 Object.fromEntries ( iterable ), https://tc39.es/ecma262/#sec-object.fromentries
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::from_entries)
{
    auto iterable = TRY_OR_DISCARD(require_object_coercible(global_object, vm.argument(0)));

    auto* object = Object::create(global_object, global_object.object_prototype());

    get_iterator_values(global_object, iterable, [&](Value iterator_value) {
        if (vm.exception())
            return IterationDecision::Break;
        if (!iterator_value.is_object()) {
            vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, String::formatted("Iterator value {}", iterator_value.to_string_without_side_effects()));
            return IterationDecision::Break;
        }
        auto key_or_error = iterator_value.as_object().get(0);
        if (key_or_error.is_error())
            return IterationDecision::Break;
        auto key = key_or_error.release_value();
        auto value_or_error = iterator_value.as_object().get(1);
        if (value_or_error.is_error())
            return IterationDecision::Break;
        auto value = value_or_error.release_value();
        auto property_key_or_error = key.to_property_key(global_object);
        if (property_key_or_error.is_error())
            return IterationDecision::Break;
        auto result_or_error = object->create_data_property_or_throw(property_key_or_error.release_value(), value);
        if (result_or_error.is_error())
            return IterationDecision::Break;
        return IterationDecision::Continue;
    });
    if (vm.exception())
        return {};
    return object;
}

// 20.1.2.20 Object.seal ( O ), https://tc39.es/ecma262/#sec-object.seal
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::seal)
{
    auto argument = vm.argument(0);
    if (!argument.is_object())
        return argument;
    auto status = TRY_OR_DISCARD(argument.as_object().set_integrity_level(Object::IntegrityLevel::Sealed));
    if (!status) {
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectSealFailed);
        return {};
    }
    return argument;
}

// 20.1.2.8 Object.getOwnPropertyDescriptor ( O, P ), https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptor)
{
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    auto key = TRY_OR_DISCARD(vm.argument(1).to_property_key(global_object));
    auto descriptor = TRY_OR_DISCARD(object->internal_get_own_property(key));
    return from_property_descriptor(global_object, descriptor);
}

// 20.1.2.9 Object.getOwnPropertyDescriptors ( O ), https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptors)
{
    // 1. Let obj be ? ToObject(O).
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));

    // 2. Let ownKeys be ? obj.[[OwnPropertyKeys]]().
    auto own_keys = TRY_OR_DISCARD(object->internal_own_property_keys());

    // 3. Let descriptors be ! OrdinaryObjectCreate(%Object.prototype%).
    auto* descriptors = Object::create(global_object, global_object.object_prototype());

    // 4. For each element key of ownKeys, do
    for (auto& key : own_keys) {
        auto property_name = PropertyName::from_value(global_object, key);

        // a. Let desc be ? obj.[[GetOwnProperty]](key).
        auto desc = TRY_OR_DISCARD(object->internal_get_own_property(property_name));

        // b. Let descriptor be ! FromPropertyDescriptor(desc).
        auto descriptor = from_property_descriptor(global_object, desc);

        // c. If descriptor is not undefined, perform ! CreateDataPropertyOrThrow(descriptors, key, descriptor).
        if (!descriptor.is_undefined())
            MUST(descriptors->create_data_property_or_throw(property_name, descriptor));
    }

    // 5. Return descriptors.
    return descriptors;
}

// 20.1.2.4 Object.defineProperty ( O, P, Attributes ), https://tc39.es/ecma262/#sec-object.defineproperty
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::define_property)
{
    if (!vm.argument(0).is_object()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, vm.argument(0).to_string_without_side_effects());
        return {};
    }
    auto key = TRY_OR_DISCARD(vm.argument(1).to_property_key(global_object));
    auto descriptor = TRY_OR_DISCARD(to_property_descriptor(global_object, vm.argument(2)));
    TRY_OR_DISCARD(vm.argument(0).as_object().define_property_or_throw(key, descriptor));
    return vm.argument(0);
}

// 20.1.2.3 Object.defineProperties ( O, Properties ), https://tc39.es/ecma262/#sec-object.defineproperties
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::define_properties)
{
    auto object = vm.argument(0);
    auto properties = vm.argument(1);

    // 1. If Type(O) is not Object, throw a TypeError exception.
    if (!object.is_object()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, "Object argument");
        return {};
    }

    // 2. Return ? ObjectDefineProperties(O, Properties).
    return TRY_OR_DISCARD(object.as_object().define_properties(properties));
}

// 20.1.2.13 Object.is ( value1, value2 ), https://tc39.es/ecma262/#sec-object.is
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::is)
{
    return Value(same_value(vm.argument(0), vm.argument(1)));
}

// 20.1.2.17 Object.keys ( O ), https://tc39.es/ecma262/#sec-object.keys
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::keys)
{
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    auto name_list = TRY_OR_DISCARD(object->enumerable_own_property_names(PropertyKind::Key));
    return Array::create_from(global_object, name_list);
}

// 20.1.2.22 Object.values ( O ), https://tc39.es/ecma262/#sec-object.values
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::values)
{
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    auto name_list = TRY_OR_DISCARD(object->enumerable_own_property_names(PropertyKind::Value));
    return Array::create_from(global_object, name_list);
}

// 20.1.2.5 Object.entries ( O ), https://tc39.es/ecma262/#sec-object.entries
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::entries)
{
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    auto name_list = TRY_OR_DISCARD(object->enumerable_own_property_names(PropertyKind::KeyAndValue));
    return Array::create_from(global_object, name_list);
}

// 20.1.2.2 Object.create ( O, Properties ), https://tc39.es/ecma262/#sec-object.create
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::create)
{
    auto proto = vm.argument(0);
    auto properties = vm.argument(1);

    // 1. If Type(O) is neither Object nor Null, throw a TypeError exception.
    if (!proto.is_object() && !proto.is_null()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::ObjectPrototypeWrongType);
        return {};
    }

    // 2. Let obj be ! OrdinaryObjectCreate(O).
    auto* object = Object::create(global_object, proto.is_null() ? nullptr : &proto.as_object());

    // 3. If Properties is not undefined, then
    if (!properties.is_undefined()) {
        // a. Return ? ObjectDefineProperties(obj, Properties).
        return TRY_OR_DISCARD(object->define_properties(properties));
    }

    // 4. Return obj.
    return object;
}

// 1 Object.hasOwn ( O, P ), https://tc39.es/proposal-accessible-object-hasownproperty/#sec-object.hasown
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::has_own)
{
    // 1. Let obj be ? ToObject(O).
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));

    // 2. Let key be ? ToPropertyKey(P).
    auto key = TRY_OR_DISCARD(vm.argument(1).to_property_key(global_object));

    // 3. Return ? HasOwnProperty(obj, key).
    return Value(TRY_OR_DISCARD(object->has_own_property(key)));
}

// 20.1.2.1 Object.assign ( target, ...sources ), https://tc39.es/ecma262/#sec-object.assign
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::assign)
{
    // 1. Let to be ? ToObject(target).
    auto* to = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));

    // 2. If only one argument was passed, return to.
    if (vm.argument_count() == 1)
        return to;

    // 3. For each element nextSource of sources, do
    for (size_t i = 1; i < vm.argument_count(); ++i) {
        auto next_source = vm.argument(i);

        // a. If nextSource is neither undefined nor null, then
        if (next_source.is_nullish())
            continue;

        // i. Let from be ! ToObject(nextSource).
        auto* from = MUST(next_source.to_object(global_object));

        // ii. Let keys be ? from.[[OwnPropertyKeys]]().
        auto keys = TRY_OR_DISCARD(from->internal_own_property_keys());

        // iii. For each element nextKey of keys, do
        for (auto& next_key : keys) {
            auto property_name = PropertyName::from_value(global_object, next_key);

            // 1. Let desc be ? from.[[GetOwnProperty]](nextKey).
            auto desc = TRY_OR_DISCARD(from->internal_get_own_property(property_name));

            // 2. If desc is not undefined and desc.[[Enumerable]] is true, then
            if (!desc.has_value() || !*desc->enumerable)
                continue;

            // a. Let propValue be ? Get(from, nextKey).
            auto prop_value = TRY_OR_DISCARD(from->get(property_name));

            // b. Perform ? Set(to, nextKey, propValue, true).
            TRY_OR_DISCARD(to->set(property_name, prop_value, Object::ShouldThrowExceptions::Yes));
        }
    }

    // 4. Return to.
    return to;
}

}