1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 09:58:11 +00:00

LibJS: Replace GlobalObject with VM in Value AOs [Part 4/19]

This is where the fun begins. :^)
This commit is contained in:
Linus Groh 2022-08-21 14:00:56 +01:00
parent f6c4a0f5d0
commit a022e548b8
129 changed files with 1230 additions and 1325 deletions

View file

@ -142,9 +142,9 @@ JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::fuzzilli)
if (!vm.argument_count()) if (!vm.argument_count())
return JS::js_undefined(); return JS::js_undefined();
auto operation = TRY(vm.argument(0).to_string(global_object)); auto operation = TRY(vm.argument(0).to_string(vm));
if (operation == "FUZZILLI_CRASH") { if (operation == "FUZZILLI_CRASH") {
auto type = TRY(vm.argument(1).to_i32(global_object)); auto type = TRY(vm.argument(1).to_i32(vm));
switch (type) { switch (type) {
case 0: case 0:
*((int*)0x41414141) = 0x1337; *((int*)0x41414141) = 0x1337;
@ -160,7 +160,7 @@ JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::fuzzilli)
fzliout = stdout; fzliout = stdout;
} }
auto string = TRY(vm.argument(1).to_string(global_object)); auto string = TRY(vm.argument(1).to_string(vm));
fprintf(fzliout, "%s\n", string.characters()); fprintf(fzliout, "%s\n", string.characters());
fflush(fzliout); fflush(fzliout);
} }

View file

@ -303,7 +303,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
@cpp_name@.ensure_capacity(vm.argument_count() - @js_suffix@); @cpp_name@.ensure_capacity(vm.argument_count() - @js_suffix@);
for (size_t i = @js_suffix@; i < vm.argument_count(); ++i) { for (size_t i = @js_suffix@; i < vm.argument_count(); ++i) {
auto to_string_result = TRY(vm.argument(i).to_string(global_object)); auto to_string_result = TRY(vm.argument(i).to_string(vm));
@cpp_name@.append(move(to_string_result)); @cpp_name@.append(move(to_string_result));
} }
)~~~"); )~~~");
@ -314,14 +314,14 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@) { if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@) {
@cpp_name@ = String::empty(); @cpp_name@ = String::empty();
} else { } else {
@cpp_name@ = TRY(@js_name@@js_suffix@.to_string(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
} }
)~~~"); )~~~");
} else { } else {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
String @cpp_name@; String @cpp_name@;
if (!@js_name@@js_suffix@.is_nullish()) if (!@js_name@@js_suffix@.is_nullish())
@cpp_name@ = TRY(@js_name@@js_suffix@.to_string(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
)~~~"); )~~~");
} }
} else { } else {
@ -331,7 +331,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@) if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@)
@cpp_name@ = String::empty(); @cpp_name@ = String::empty();
else else
@cpp_name@ = TRY(@js_name@@js_suffix@.to_string(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
})~~~"); })~~~");
if (optional_default_value.has_value() && (!parameter.type->nullable || optional_default_value.value() != "null")) { if (optional_default_value.has_value() && (!parameter.type->nullable || optional_default_value.value() != "null")) {
scoped_generator.append(R"~~~( else { scoped_generator.append(R"~~~( else {
@ -405,7 +405,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
} else if (parameter.type->name == "double" || parameter.type->name == "float") { } else if (parameter.type->name == "double" || parameter.type->name == "float") {
if (!optional) { if (!optional) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@parameter.type.name@ @cpp_name@ = TRY(@js_name@@js_suffix@.to_double(global_object)); @parameter.type.name@ @cpp_name@ = TRY(@js_name@@js_suffix@.to_double(vm));
)~~~"); )~~~");
} else { } else {
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
@ -419,7 +419,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
} }
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
if (!@js_name@@js_suffix@.is_undefined()) if (!@js_name@@js_suffix@.is_undefined())
@cpp_name@ = TRY(@js_name@@js_suffix@.to_double(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_double(vm));
)~~~"); )~~~");
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@ -471,7 +471,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
)~~~"); )~~~");
} }
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@cpp_name@ = TRY(@js_name@@js_suffix@.to_u32(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_u32(vm));
)~~~"); )~~~");
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@ -495,7 +495,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
)~~~"); )~~~");
} }
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@cpp_name@ = TRY(@js_name@@js_suffix@.to_u16(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_u16(vm));
)~~~"); )~~~");
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@ -519,7 +519,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
)~~~"); )~~~");
} }
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@cpp_name@ = TRY(@js_name@@js_suffix@.to_i32(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_i32(vm));
)~~~"); )~~~");
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@ -543,7 +543,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
)~~~"); )~~~");
} }
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@cpp_name@ = TRY(@js_name@@js_suffix@.to_bigint_int64(global_object)); @cpp_name@ = TRY(@js_name@@js_suffix@.to_bigint_int64(vm));
)~~~"); )~~~");
if (optional_default_value.has_value()) { if (optional_default_value.has_value()) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
@ -623,7 +623,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
} }
enum_generator.append(R"~~~( enum_generator.append(R"~~~(
auto @js_name.as_string@ = TRY(@js_name@@js_suffix@.to_string(global_object)); auto @js_name.as_string@ = TRY(@js_name@@js_suffix@.to_string(vm));
)~~~"); )~~~");
auto first = true; auto first = true;
for (auto& it : enumeration.translated_cpp_names) { for (auto& it : enumeration.translated_cpp_names) {
@ -777,7 +777,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (!@js_name@@js_suffix@.is_object()) if (!@js_name@@js_suffix@.is_object())
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects()); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects());
auto* iterator_method@recursion_depth@ = TRY(@js_name@@js_suffix@.get_method(global_object, *vm.well_known_symbol_iterator())); auto* iterator_method@recursion_depth@ = TRY(@js_name@@js_suffix@.get_method(vm, *vm.well_known_symbol_iterator()));
if (!iterator_method@recursion_depth@) if (!iterator_method@recursion_depth@)
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, @js_name@@js_suffix@.to_string_without_side_effects()); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, @js_name@@js_suffix@.to_string_without_side_effects());
)~~~"); )~~~");
@ -836,7 +836,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
auto record_keys@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_own_property_keys()); auto record_keys@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_own_property_keys());
for (auto& key@recursion_depth@ : record_keys@recursion_depth@) { for (auto& key@recursion_depth@ : record_keys@recursion_depth@) {
auto property_key@recursion_depth@ = MUST(JS::PropertyKey::from_value(global_object, key@recursion_depth@)); auto property_key@recursion_depth@ = MUST(JS::PropertyKey::from_value(vm, key@recursion_depth@));
auto descriptor@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_get_own_property(property_key@recursion_depth@)); auto descriptor@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_get_own_property(property_key@recursion_depth@));
@ -1045,7 +1045,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (sequence_type) { if (sequence_type) {
// 1. Let method be ? GetMethod(V, @@iterator). // 1. Let method be ? GetMethod(V, @@iterator).
union_generator.append(R"~~~( union_generator.append(R"~~~(
auto* method = TRY(@js_name@@js_suffix@.get_method(global_object, *vm.well_known_symbol_iterator())); auto* method = TRY(@js_name@@js_suffix@.get_method(vm, *vm.well_known_symbol_iterator()));
)~~~"); )~~~");
// 2. If method is not undefined, return the result of creating a sequence of that type from V and method. // 2. If method is not undefined, return the result of creating a sequence of that type from V and method.
@ -1176,7 +1176,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
// 14. If types includes a string type, then return the result of converting V to that type. // 14. If types includes a string type, then return the result of converting V to that type.
// NOTE: Currently all string types are converted to String. // NOTE: Currently all string types are converted to String.
union_generator.append(R"~~~( union_generator.append(R"~~~(
return TRY(@js_name@@js_suffix@.to_string(global_object)); return TRY(@js_name@@js_suffix@.to_string(vm));
)~~~"); )~~~");
} else if (numeric_type && includes_bigint) { } else if (numeric_type && includes_bigint) {
// 15. If types includes a numeric type and bigint, then return the result of converting V to either that numeric type or bigint. // 15. If types includes a numeric type and bigint, then return the result of converting V to either that numeric type or bigint.
@ -1195,7 +1195,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
union_numeric_type_generator.set("numeric_type", cpp_type.name); union_numeric_type_generator.set("numeric_type", cpp_type.name);
union_numeric_type_generator.append(R"~~~( union_numeric_type_generator.append(R"~~~(
auto x = TRY(@js_name@@js_suffix@.to_numeric(global_object)); auto x = TRY(@js_name@@js_suffix@.to_numeric(vm));
if (x.is_bigint()) if (x.is_bigint())
return x.as_bigint(); return x.as_bigint();
VERIFY(x.is_number()); VERIFY(x.is_number());
@ -1228,7 +1228,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
} else if (includes_bigint) { } else if (includes_bigint) {
// 18. If types includes bigint, then return the result of converting V to bigint. // 18. If types includes bigint, then return the result of converting V to bigint.
union_generator.append(R"~~~( union_generator.append(R"~~~(
return TRY(@js_name@@js_suffix@.to_bigint(global_object)); return TRY(@js_name@@js_suffix@.to_bigint(vm));
)~~~"); )~~~");
} else { } else {
// 19. Throw a TypeError. // 19. Throw a TypeError.
@ -2327,6 +2327,8 @@ JS::ThrowCompletionOr<Optional<JS::PropertyDescriptor>> @class_name@::legacy_pla
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
static JS::ThrowCompletionOr<void> invoke_named_property_setter(JS::GlobalObject& global_object, @fully_qualified_name@& impl, String const& property_name, JS::Value value) static JS::ThrowCompletionOr<void> invoke_named_property_setter(JS::GlobalObject& global_object, @fully_qualified_name@& impl, String const& property_name, JS::Value value)
{ {
auto& vm = global_object.vm();
// 1. Let creating be true if P is not a supported property name, and false otherwise. // 1. Let creating be true if P is not a supported property name, and false otherwise.
// NOTE: This is in it's own variable to enforce the type. // NOTE: This is in it's own variable to enforce the type.
// FIXME: Can this throw? // FIXME: Can this throw?
@ -3366,14 +3368,14 @@ void @prototype_class@::initialize(JS::Realm& realm)
if (!interface.attributes.is_empty() || !interface.functions.is_empty() || interface.has_stringifier) { if (!interface.attributes.is_empty() || !interface.functions.is_empty() || interface.has_stringifier) {
generator.append(R"~~~( generator.append(R"~~~(
static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm, JS::GlobalObject& global_object) static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm, JS::GlobalObject&)
{ {
auto this_value = vm.this_value(); auto this_value = vm.this_value();
JS::Object* this_object = nullptr; JS::Object* this_object = nullptr;
if (this_value.is_nullish()) if (this_value.is_nullish())
this_object = &vm.current_realm()->global_object(); this_object = &vm.current_realm()->global_object();
else else
this_object = TRY(this_value.to_object(global_object)); this_object = TRY(this_value.to_object(vm));
)~~~"); )~~~");
if (interface.name == "EventTarget") { if (interface.name == "EventTarget") {
@ -3805,9 +3807,9 @@ void @prototype_class@::initialize(JS::Realm& realm)
define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm, "Iterator"), JS::Attribute::Configurable); define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm, "Iterator"), JS::Attribute::Configurable);
} }
static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm, JS::GlobalObject& global_object) static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm, JS::GlobalObject&)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<@wrapper_class@>(this_object)) if (!is<@wrapper_class@>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@");
return &static_cast<@wrapper_class@*>(this_object)->impl(); return &static_cast<@wrapper_class@*>(this_object)->impl();

View file

@ -27,7 +27,7 @@
auto result = bytecode_interpreter.run(*executable); \ auto result = bytecode_interpreter.run(*executable); \
EXPECT(!result.is_error()); \ EXPECT(!result.is_error()); \
if (result.is_error()) \ if (result.is_error()) \
dbgln("Error: {}", MUST(result.throw_completion().value()->to_string(bytecode_interpreter.global_object()))); dbgln("Error: {}", MUST(result.throw_completion().value()->to_string(vm)));
#define EXPECT_NO_EXCEPTION_WITH_OPTIMIZATIONS(executable) \ #define EXPECT_NO_EXCEPTION_WITH_OPTIMIZATIONS(executable) \
auto& passes = JS::Bytecode::Interpreter::optimization_pipeline(); \ auto& passes = JS::Bytecode::Interpreter::optimization_pipeline(); \
@ -37,7 +37,7 @@
\ \
EXPECT(!result_with_optimizations.is_error()); \ EXPECT(!result_with_optimizations.is_error()); \
if (result_with_optimizations.is_error()) \ if (result_with_optimizations.is_error()) \
dbgln("Error: {}", MUST(result_with_optimizations.throw_completion().value()->to_string(bytecode_interpreter.global_object()))); dbgln("Error: {}", MUST(result_with_optimizations.throw_completion().value()->to_string(vm)));
#define EXPECT_NO_EXCEPTION_ALL(source) \ #define EXPECT_NO_EXCEPTION_ALL(source) \
SETUP_AND_PARSE("(() => {\n" source "\n})()") \ SETUP_AND_PARSE("(() => {\n" source "\n})()") \

View file

@ -19,7 +19,7 @@ TESTJS_GLOBAL_FUNCTION(is_strict_mode, isStrictMode, 0)
TESTJS_GLOBAL_FUNCTION(can_parse_source, canParseSource) TESTJS_GLOBAL_FUNCTION(can_parse_source, canParseSource)
{ {
auto source = TRY(vm.argument(0).to_string(global_object)); auto source = TRY(vm.argument(0).to_string(vm));
auto parser = JS::Parser(JS::Lexer(source)); auto parser = JS::Parser(JS::Lexer(source));
(void)parser.parse_program(); (void)parser.parse_program();
return JS::Value(!parser.has_errors()); return JS::Value(!parser.has_errors());
@ -33,7 +33,7 @@ TESTJS_GLOBAL_FUNCTION(run_queued_promise_jobs, runQueuedPromiseJobs)
TESTJS_GLOBAL_FUNCTION(get_weak_set_size, getWeakSetSize) TESTJS_GLOBAL_FUNCTION(get_weak_set_size, getWeakSetSize)
{ {
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
if (!is<JS::WeakSet>(object)) if (!is<JS::WeakSet>(object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WeakSet"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WeakSet");
auto* weak_set = static_cast<JS::WeakSet*>(object); auto* weak_set = static_cast<JS::WeakSet*>(object);
@ -42,7 +42,7 @@ TESTJS_GLOBAL_FUNCTION(get_weak_set_size, getWeakSetSize)
TESTJS_GLOBAL_FUNCTION(get_weak_map_size, getWeakMapSize) TESTJS_GLOBAL_FUNCTION(get_weak_map_size, getWeakMapSize)
{ {
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
if (!is<JS::WeakMap>(object)) if (!is<JS::WeakMap>(object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WeakMap"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WeakMap");
auto* weak_map = static_cast<JS::WeakMap*>(object); auto* weak_map = static_cast<JS::WeakMap*>(object);

View file

@ -15,7 +15,7 @@ TEST_ROOT("Userland/Libraries/LibWasm/Tests");
TESTJS_GLOBAL_FUNCTION(read_binary_wasm_file, readBinaryWasmFile) TESTJS_GLOBAL_FUNCTION(read_binary_wasm_file, readBinaryWasmFile)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto filename = TRY(vm.argument(0).to_string(global_object)); auto filename = TRY(vm.argument(0).to_string(vm));
auto file = Core::Stream::File::open(filename, Core::Stream::OpenMode::Read); auto file = Core::Stream::File::open(filename, Core::Stream::OpenMode::Read);
if (file.is_error()) if (file.is_error())
return vm.throw_completion<JS::TypeError>(strerror(file.error().code())); return vm.throw_completion<JS::TypeError>(strerror(file.error().code()));
@ -101,7 +101,7 @@ HashMap<Wasm::Linker::Name, Wasm::ExternValue> WebAssemblyModule::s_spec_test_na
TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule) TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
if (!is<JS::Uint8Array>(object)) if (!is<JS::Uint8Array>(object))
return vm.throw_completion<JS::TypeError>("Expected a Uint8Array argument to parse_webassembly_module"); return vm.throw_completion<JS::TypeError>("Expected a Uint8Array argument to parse_webassembly_module");
auto& array = static_cast<JS::Uint8Array&>(*object); auto& array = static_cast<JS::Uint8Array&>(*object);
@ -139,11 +139,11 @@ TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays) TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays)
{ {
auto* lhs = TRY(vm.argument(0).to_object(global_object)); auto* lhs = TRY(vm.argument(0).to_object(vm));
if (!is<JS::TypedArrayBase>(lhs)) if (!is<JS::TypedArrayBase>(lhs))
return vm.throw_completion<JS::TypeError>("Expected a TypedArray"); return vm.throw_completion<JS::TypeError>("Expected a TypedArray");
auto& lhs_array = static_cast<JS::TypedArrayBase&>(*lhs); auto& lhs_array = static_cast<JS::TypedArrayBase&>(*lhs);
auto* rhs = TRY(vm.argument(1).to_object(global_object)); auto* rhs = TRY(vm.argument(1).to_object(vm));
if (!is<JS::TypedArrayBase>(rhs)) if (!is<JS::TypedArrayBase>(rhs))
return vm.throw_completion<JS::TypeError>("Expected a TypedArray"); return vm.throw_completion<JS::TypeError>("Expected a TypedArray");
auto& rhs_array = static_cast<JS::TypedArrayBase&>(*rhs); auto& rhs_array = static_cast<JS::TypedArrayBase&>(*rhs);
@ -159,9 +159,9 @@ void WebAssemblyModule::initialize(JS::Realm& realm)
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export) JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
{ {
auto name = TRY(vm.argument(0).to_string(global_object)); auto name = TRY(vm.argument(0).to_string(vm));
auto this_value = vm.this_value(); auto this_value = vm.this_value();
auto* object = TRY(this_value.to_object(global_object)); auto* object = TRY(this_value.to_object(vm));
if (!is<WebAssemblyModule>(object)) if (!is<WebAssemblyModule>(object))
return vm.throw_completion<JS::TypeError>("Not a WebAssemblyModule"); return vm.throw_completion<JS::TypeError>("Not a WebAssemblyModule");
auto instance = static_cast<WebAssemblyModule*>(object); auto instance = static_cast<WebAssemblyModule*>(object);
@ -189,7 +189,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
{ {
auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(global_object))); auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(vm)));
Wasm::FunctionAddress function_address { address }; Wasm::FunctionAddress function_address { address };
auto function_instance = WebAssemblyModule::machine().store().get(function_address); auto function_instance = WebAssemblyModule::machine().store().get(function_address);
if (!function_instance) if (!function_instance)
@ -208,14 +208,14 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
auto argument = vm.argument(index++); auto argument = vm.argument(index++);
double double_value = 0; double double_value = 0;
if (!argument.is_bigint()) if (!argument.is_bigint())
double_value = TRY(argument.to_double(global_object)); double_value = TRY(argument.to_double(vm));
switch (param.kind()) { switch (param.kind()) {
case Wasm::ValueType::Kind::I32: case Wasm::ValueType::Kind::I32:
arguments.append(Wasm::Value(param, static_cast<u64>(double_value))); arguments.append(Wasm::Value(param, static_cast<u64>(double_value)));
break; break;
case Wasm::ValueType::Kind::I64: case Wasm::ValueType::Kind::I64:
if (argument.is_bigint()) { if (argument.is_bigint()) {
auto value = TRY(argument.to_bigint_int64(global_object)); auto value = TRY(argument.to_bigint_int64(vm));
arguments.append(Wasm::Value(param, bit_cast<u64>(value))); arguments.append(Wasm::Value(param, bit_cast<u64>(value)));
} else { } else {
arguments.append(Wasm::Value(param, static_cast<u64>(double_value))); arguments.append(Wasm::Value(param, static_cast<u64>(double_value)));

View file

@ -20,8 +20,9 @@ DateCell::DateCell()
JS::ThrowCompletionOr<String> DateCell::display(Cell& cell, CellTypeMetadata const& metadata) const JS::ThrowCompletionOr<String> DateCell::display(Cell& cell, CellTypeMetadata const& metadata) const
{ {
return propagate_failure(cell, [&]() -> JS::ThrowCompletionOr<String> { return propagate_failure(cell, [&]() -> JS::ThrowCompletionOr<String> {
auto& vm = cell.sheet().global_object().vm();
auto timestamp = TRY(js_value(cell, metadata)); auto timestamp = TRY(js_value(cell, metadata));
auto string = Core::DateTime::from_timestamp(TRY(timestamp.to_i32(cell.sheet().global_object()))).to_string(metadata.format.is_empty() ? "%Y-%m-%d %H:%M:%S"sv : metadata.format.view()); auto string = Core::DateTime::from_timestamp(TRY(timestamp.to_i32(vm))).to_string(metadata.format.is_empty() ? "%Y-%m-%d %H:%M:%S"sv : metadata.format.view());
if (metadata.length >= 0) if (metadata.length >= 0)
return string.substring(0, metadata.length); return string.substring(0, metadata.length);
@ -32,8 +33,9 @@ JS::ThrowCompletionOr<String> DateCell::display(Cell& cell, CellTypeMetadata con
JS::ThrowCompletionOr<JS::Value> DateCell::js_value(Cell& cell, CellTypeMetadata const&) const JS::ThrowCompletionOr<JS::Value> DateCell::js_value(Cell& cell, CellTypeMetadata const&) const
{ {
auto& vm = cell.sheet().global_object().vm();
auto js_data = cell.js_data(); auto js_data = cell.js_data();
auto value = TRY(js_data.to_double(cell.sheet().global_object())); auto value = TRY(js_data.to_double(vm));
return JS::Value(value / 1000); // Turn it to seconds return JS::Value(value / 1000); // Turn it to seconds
} }

View file

@ -17,11 +17,12 @@ IdentityCell::IdentityCell()
JS::ThrowCompletionOr<String> IdentityCell::display(Cell& cell, CellTypeMetadata const& metadata) const JS::ThrowCompletionOr<String> IdentityCell::display(Cell& cell, CellTypeMetadata const& metadata) const
{ {
auto& vm = cell.sheet().global_object().vm();
auto data = cell.js_data(); auto data = cell.js_data();
if (!metadata.format.is_empty()) if (!metadata.format.is_empty())
data = TRY(cell.sheet().evaluate(metadata.format, &cell)); data = TRY(cell.sheet().evaluate(metadata.format, &cell));
return data.to_string(cell.sheet().global_object()); return data.to_string(vm);
} }
JS::ThrowCompletionOr<JS::Value> IdentityCell::js_value(Cell& cell, CellTypeMetadata const&) const JS::ThrowCompletionOr<JS::Value> IdentityCell::js_value(Cell& cell, CellTypeMetadata const&) const

View file

@ -20,12 +20,13 @@ NumericCell::NumericCell()
JS::ThrowCompletionOr<String> NumericCell::display(Cell& cell, CellTypeMetadata const& metadata) const JS::ThrowCompletionOr<String> NumericCell::display(Cell& cell, CellTypeMetadata const& metadata) const
{ {
return propagate_failure(cell, [&]() -> JS::ThrowCompletionOr<String> { return propagate_failure(cell, [&]() -> JS::ThrowCompletionOr<String> {
auto& vm = cell.sheet().global_object().vm();
auto value = TRY(js_value(cell, metadata)); auto value = TRY(js_value(cell, metadata));
String string; String string;
if (metadata.format.is_empty()) if (metadata.format.is_empty())
string = TRY(value.to_string(cell.sheet().global_object())); string = TRY(value.to_string(vm));
else else
string = format_double(metadata.format.characters(), TRY(value.to_double(cell.sheet().global_object()))); string = format_double(metadata.format.characters(), TRY(value.to_double(vm)));
if (metadata.length >= 0) if (metadata.length >= 0)
return string.substring(0, min(string.length(), metadata.length)); return string.substring(0, min(string.length(), metadata.length));
@ -37,7 +38,8 @@ JS::ThrowCompletionOr<String> NumericCell::display(Cell& cell, CellTypeMetadata
JS::ThrowCompletionOr<JS::Value> NumericCell::js_value(Cell& cell, CellTypeMetadata const&) const JS::ThrowCompletionOr<JS::Value> NumericCell::js_value(Cell& cell, CellTypeMetadata const&) const
{ {
return propagate_failure(cell, [&]() { return propagate_failure(cell, [&]() {
return cell.js_data().to_number(cell.sheet().global_object()); auto& vm = cell.sheet().global_object().vm();
return cell.js_data().to_number(vm);
}); });
} }

View file

@ -17,7 +17,8 @@ StringCell::StringCell()
JS::ThrowCompletionOr<String> StringCell::display(Cell& cell, CellTypeMetadata const& metadata) const JS::ThrowCompletionOr<String> StringCell::display(Cell& cell, CellTypeMetadata const& metadata) const
{ {
auto string = TRY(cell.js_data().to_string(cell.sheet().global_object())); auto& vm = cell.sheet().global_object().vm();
auto string = TRY(cell.js_data().to_string(vm));
if (metadata.length >= 0) if (metadata.length >= 0)
return string.substring(0, metadata.length); return string.substring(0, metadata.length);

View file

@ -171,7 +171,7 @@ void SheetGlobalObject::visit_edges(Visitor& visitor)
JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_name) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_name)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -182,7 +182,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_name)
JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_real_cell_contents) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_real_cell_contents)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -211,7 +211,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_real_cell_contents)
JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::set_real_cell_contents) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::set_real_cell_contents)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -242,7 +242,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::parse_cell_name)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -272,7 +272,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::current_cell_position)
if (vm.argument_count() != 0) if (vm.argument_count() != 0)
return vm.throw_completion<JS::TypeError>("Expected no arguments to current_cell_position()"); return vm.throw_completion<JS::TypeError>("Expected no arguments to current_cell_position()");
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -302,7 +302,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_index)
auto& column_name_str = column_name.as_string().string(); auto& column_name_str = column_name.as_string().string();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -327,10 +327,10 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_arithmetic)
auto& column_name_str = column_name.as_string().string(); auto& column_name_str = column_name.as_string().string();
auto offset = TRY(vm.argument(1).to_number(global_object)); auto offset = TRY(vm.argument(1).to_number(vm));
auto offset_number = static_cast<i32>(offset.as_double()); auto offset_number = static_cast<i32>(offset.as_double());
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -354,7 +354,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_column_bound)
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "String"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "String");
auto& column_name_str = column_name.as_string().string(); auto& column_name_str = column_name.as_string().string();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<SheetGlobalObject>(this_object)) if (!is<SheetGlobalObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "SheetGlobalObject");
@ -396,7 +396,7 @@ JS_DEFINE_NATIVE_FUNCTION(WorkbookObject::sheet)
if (!name_value.is_string() && !name_value.is_number()) if (!name_value.is_string() && !name_value.is_number())
return vm.throw_completion<JS::TypeError>("Expected a String or Number argument to sheet()"); return vm.throw_completion<JS::TypeError>("Expected a String or Number argument to sheet()");
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (!is<WorkbookObject>(this_object)) if (!is<WorkbookObject>(this_object))
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WorkbookObject"); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WorkbookObject");
@ -410,7 +410,7 @@ JS_DEFINE_NATIVE_FUNCTION(WorkbookObject::sheet)
return JS::Value(&sheet.global_object()); return JS::Value(&sheet.global_object());
} }
} else { } else {
auto index = TRY(name_value.to_length(global_object)); auto index = TRY(name_value.to_length(vm));
if (index < workbook.sheets().size()) if (index < workbook.sheets().size())
return JS::Value(&workbook.sheets()[index].global_object()); return JS::Value(&workbook.sheets()[index].global_object());
} }

View file

@ -24,13 +24,14 @@ GUI::Variant SheetModel::data(const GUI::ModelIndex& index, GUI::ModelRole role)
return String::empty(); return String::empty();
Function<String(JS::Value)> to_string_as_exception = [&](JS::Value value) { Function<String(JS::Value)> to_string_as_exception = [&](JS::Value value) {
auto& vm = cell->sheet().global_object().vm();
StringBuilder builder; StringBuilder builder;
builder.append("Error: "sv); builder.append("Error: "sv);
if (value.is_object()) { if (value.is_object()) {
auto& object = value.as_object(); auto& object = value.as_object();
if (is<JS::Error>(object)) { if (is<JS::Error>(object)) {
auto message = object.get_without_side_effects("message"); auto message = object.get_without_side_effects("message");
auto error = message.to_string(cell->sheet().global_object()); auto error = message.to_string(vm);
if (error.is_throw_completion()) if (error.is_throw_completion())
builder.append(message.to_string_without_side_effects()); builder.append(message.to_string_without_side_effects());
else else
@ -38,7 +39,7 @@ GUI::Variant SheetModel::data(const GUI::ModelIndex& index, GUI::ModelRole role)
return builder.to_string(); return builder.to_string();
} }
} }
auto error_message = value.to_string(cell->sheet().global_object()); auto error_message = value.to_string(vm);
if (error_message.is_throw_completion()) if (error_message.is_throw_completion())
return to_string_as_exception(*error_message.release_error().value()); return to_string_as_exception(*error_message.release_error().value());

View file

@ -596,27 +596,28 @@ Completion WithStatement::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = global_object.vm();
// 1. Let value be the result of evaluating Expression. // 1. Let value be the result of evaluating Expression.
auto value = TRY(m_object->execute(interpreter)).release_value(); auto value = TRY(m_object->execute(interpreter)).release_value();
// 2. Let obj be ? ToObject(? GetValue(value)). // 2. Let obj be ? ToObject(? GetValue(value)).
auto* object = TRY(value.to_object(global_object)); auto* object = TRY(value.to_object(vm));
// 3. Let oldEnv be the running execution context's LexicalEnvironment. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
auto* old_environment = interpreter.vm().running_execution_context().lexical_environment; auto* old_environment = vm.running_execution_context().lexical_environment;
// 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv). // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
auto* new_environment = new_object_environment(*object, true, old_environment); auto* new_environment = new_object_environment(*object, true, old_environment);
// 5. Set the running execution context's LexicalEnvironment to newEnv. // 5. Set the running execution context's LexicalEnvironment to newEnv.
interpreter.vm().running_execution_context().lexical_environment = new_environment; vm.running_execution_context().lexical_environment = new_environment;
// 6. Let C be the result of evaluating Statement. // 6. Let C be the result of evaluating Statement.
auto result = m_body->execute(interpreter); auto result = m_body->execute(interpreter);
// 7. Set the running execution context's LexicalEnvironment to oldEnv. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
interpreter.vm().running_execution_context().lexical_environment = old_environment; vm.running_execution_context().lexical_environment = old_environment;
// 8. Return ? UpdateEmpty(C, undefined). // 8. Return ? UpdateEmpty(C, undefined).
return result.update_empty(js_undefined()); return result.update_empty(js_undefined());
@ -1033,7 +1034,7 @@ Completion ForInStatement::execute(Interpreter& interpreter) const
Completion ForInStatement::loop_evaluation(Interpreter& interpreter, Vector<FlyString> const& label_set) const Completion ForInStatement::loop_evaluation(Interpreter& interpreter, Vector<FlyString> const& label_set) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& vm = interpreter.vm();
auto for_in_head_state = TRY(for_in_of_head_execute(interpreter, m_lhs, *m_rhs)); auto for_in_head_state = TRY(for_in_of_head_execute(interpreter, m_lhs, *m_rhs));
@ -1048,14 +1049,14 @@ Completion ForInStatement::loop_evaluation(Interpreter& interpreter, Vector<FlyS
} }
// b. Let obj be ! ToObject(exprValue). // b. Let obj be ! ToObject(exprValue).
auto* object = MUST(rhs_result.to_object(global_object)); auto* object = MUST(rhs_result.to_object(vm));
// 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
// 2. Let oldEnv be the running execution context's LexicalEnvironment. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
Environment* old_environment = interpreter.lexical_environment(); Environment* old_environment = interpreter.lexical_environment();
auto restore_scope = ScopeGuard([&] { auto restore_scope = ScopeGuard([&] {
interpreter.vm().running_execution_context().lexical_environment = old_environment; vm.running_execution_context().lexical_environment = old_environment;
}); });
// 3. Let V be undefined. // 3. Let V be undefined.
@ -1068,7 +1069,7 @@ Completion ForInStatement::loop_evaluation(Interpreter& interpreter, Vector<FlyS
auto result = m_body->execute(interpreter); auto result = m_body->execute(interpreter);
// m. Set the running execution context's LexicalEnvironment to oldEnv. // m. Set the running execution context's LexicalEnvironment to oldEnv.
interpreter.vm().running_execution_context().lexical_environment = old_environment; vm.running_execution_context().lexical_environment = old_environment;
// n. If LoopContinues(result, labelSet) is false, then // n. If LoopContinues(result, labelSet) is false, then
if (!loop_continues(result, label_set)) { if (!loop_continues(result, label_set)) {
@ -1250,7 +1251,7 @@ Completion ForAwaitOfStatement::loop_evaluation(Interpreter& interpreter, Vector
Completion BinaryExpression::execute(Interpreter& interpreter) const Completion BinaryExpression::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& vm = interpreter.vm();
// Special case in which we cannot execute the lhs. RelationalExpression : PrivateIdentifier in ShiftExpression // Special case in which we cannot execute the lhs. RelationalExpression : PrivateIdentifier in ShiftExpression
// RelationalExpression : PrivateIdentifier in ShiftExpression, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation // RelationalExpression : PrivateIdentifier in ShiftExpression, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
@ -1271,49 +1272,49 @@ Completion BinaryExpression::execute(Interpreter& interpreter) const
switch (m_op) { switch (m_op) {
case BinaryOp::Addition: case BinaryOp::Addition:
return TRY(add(global_object, lhs_result, rhs_result)); return TRY(add(vm, lhs_result, rhs_result));
case BinaryOp::Subtraction: case BinaryOp::Subtraction:
return TRY(sub(global_object, lhs_result, rhs_result)); return TRY(sub(vm, lhs_result, rhs_result));
case BinaryOp::Multiplication: case BinaryOp::Multiplication:
return TRY(mul(global_object, lhs_result, rhs_result)); return TRY(mul(vm, lhs_result, rhs_result));
case BinaryOp::Division: case BinaryOp::Division:
return TRY(div(global_object, lhs_result, rhs_result)); return TRY(div(vm, lhs_result, rhs_result));
case BinaryOp::Modulo: case BinaryOp::Modulo:
return TRY(mod(global_object, lhs_result, rhs_result)); return TRY(mod(vm, lhs_result, rhs_result));
case BinaryOp::Exponentiation: case BinaryOp::Exponentiation:
return TRY(exp(global_object, lhs_result, rhs_result)); return TRY(exp(vm, lhs_result, rhs_result));
case BinaryOp::StrictlyEquals: case BinaryOp::StrictlyEquals:
return Value(is_strictly_equal(lhs_result, rhs_result)); return Value(is_strictly_equal(lhs_result, rhs_result));
case BinaryOp::StrictlyInequals: case BinaryOp::StrictlyInequals:
return Value(!is_strictly_equal(lhs_result, rhs_result)); return Value(!is_strictly_equal(lhs_result, rhs_result));
case BinaryOp::LooselyEquals: case BinaryOp::LooselyEquals:
return Value(TRY(is_loosely_equal(global_object, lhs_result, rhs_result))); return Value(TRY(is_loosely_equal(vm, lhs_result, rhs_result)));
case BinaryOp::LooselyInequals: case BinaryOp::LooselyInequals:
return Value(!TRY(is_loosely_equal(global_object, lhs_result, rhs_result))); return Value(!TRY(is_loosely_equal(vm, lhs_result, rhs_result)));
case BinaryOp::GreaterThan: case BinaryOp::GreaterThan:
return TRY(greater_than(global_object, lhs_result, rhs_result)); return TRY(greater_than(vm, lhs_result, rhs_result));
case BinaryOp::GreaterThanEquals: case BinaryOp::GreaterThanEquals:
return TRY(greater_than_equals(global_object, lhs_result, rhs_result)); return TRY(greater_than_equals(vm, lhs_result, rhs_result));
case BinaryOp::LessThan: case BinaryOp::LessThan:
return TRY(less_than(global_object, lhs_result, rhs_result)); return TRY(less_than(vm, lhs_result, rhs_result));
case BinaryOp::LessThanEquals: case BinaryOp::LessThanEquals:
return TRY(less_than_equals(global_object, lhs_result, rhs_result)); return TRY(less_than_equals(vm, lhs_result, rhs_result));
case BinaryOp::BitwiseAnd: case BinaryOp::BitwiseAnd:
return TRY(bitwise_and(global_object, lhs_result, rhs_result)); return TRY(bitwise_and(vm, lhs_result, rhs_result));
case BinaryOp::BitwiseOr: case BinaryOp::BitwiseOr:
return TRY(bitwise_or(global_object, lhs_result, rhs_result)); return TRY(bitwise_or(vm, lhs_result, rhs_result));
case BinaryOp::BitwiseXor: case BinaryOp::BitwiseXor:
return TRY(bitwise_xor(global_object, lhs_result, rhs_result)); return TRY(bitwise_xor(vm, lhs_result, rhs_result));
case BinaryOp::LeftShift: case BinaryOp::LeftShift:
return TRY(left_shift(global_object, lhs_result, rhs_result)); return TRY(left_shift(vm, lhs_result, rhs_result));
case BinaryOp::RightShift: case BinaryOp::RightShift:
return TRY(right_shift(global_object, lhs_result, rhs_result)); return TRY(right_shift(vm, lhs_result, rhs_result));
case BinaryOp::UnsignedRightShift: case BinaryOp::UnsignedRightShift:
return TRY(unsigned_right_shift(global_object, lhs_result, rhs_result)); return TRY(unsigned_right_shift(vm, lhs_result, rhs_result));
case BinaryOp::In: case BinaryOp::In:
return TRY(in(global_object, lhs_result, rhs_result)); return TRY(in(vm, lhs_result, rhs_result));
case BinaryOp::InstanceOf: case BinaryOp::InstanceOf:
return TRY(instance_of(global_object, lhs_result, rhs_result)); return TRY(instance_of(vm, lhs_result, rhs_result));
} }
VERIFY_NOT_REACHED(); VERIFY_NOT_REACHED();
@ -1395,6 +1396,7 @@ ThrowCompletionOr<Reference> Identifier::to_reference(Interpreter& interpreter)
ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter) const ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter) const
{ {
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = interpreter.vm();
// 13.3.7.1 Runtime Semantics: Evaluation // 13.3.7.1 Runtime Semantics: Evaluation
// SuperProperty : super [ Expression ] // SuperProperty : super [ Expression ]
@ -1416,7 +1418,7 @@ ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpr
auto property_name_value = TRY(m_property->execute(interpreter)).release_value(); auto property_name_value = TRY(m_property->execute(interpreter)).release_value();
// 5. Let propertyKey be ? ToPropertyKey(propertyNameValue). // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
property_key = TRY(property_name_value.to_property_key(global_object)); property_key = TRY(property_name_value.to_property_key(vm));
} else { } else {
// SuperProperty : super . IdentifierName // SuperProperty : super . IdentifierName
@ -1453,7 +1455,7 @@ ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpr
TRY(require_object_coercible(global_object, base_value)); TRY(require_object_coercible(global_object, base_value));
property_key = TRY(PropertyKey::from_value(global_object, value)); property_key = TRY(PropertyKey::from_value(vm, value));
} else if (is<PrivateIdentifier>(*m_property)) { } else if (is<PrivateIdentifier>(*m_property)) {
auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property); auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property);
return make_private_reference(interpreter.vm(), base_value, private_identifier.string()); return make_private_reference(interpreter.vm(), base_value, private_identifier.string());
@ -1502,13 +1504,13 @@ Completion UnaryExpression::execute(Interpreter& interpreter) const
switch (m_op) { switch (m_op) {
case UnaryOp::BitwiseNot: case UnaryOp::BitwiseNot:
return TRY(bitwise_not(global_object, lhs_result)); return TRY(bitwise_not(vm, lhs_result));
case UnaryOp::Not: case UnaryOp::Not:
return Value(!lhs_result.to_boolean()); return Value(!lhs_result.to_boolean());
case UnaryOp::Plus: case UnaryOp::Plus:
return TRY(unary_plus(global_object, lhs_result)); return TRY(unary_plus(vm, lhs_result));
case UnaryOp::Minus: case UnaryOp::Minus:
return TRY(unary_minus(global_object, lhs_result)); return TRY(unary_minus(vm, lhs_result));
case UnaryOp::Typeof: case UnaryOp::Typeof:
return Value { js_string(vm, lhs_result.typeof()) }; return Value { js_string(vm, lhs_result.typeof()) };
case UnaryOp::Void: case UnaryOp::Void:
@ -1534,7 +1536,7 @@ Completion ClassElement::execute(Interpreter&) const
static ThrowCompletionOr<ClassElementName> class_key_to_property_name(Interpreter& interpreter, Expression const& key) static ThrowCompletionOr<ClassElementName> class_key_to_property_name(Interpreter& interpreter, Expression const& key)
{ {
auto& global_object = interpreter.global_object(); auto& vm = interpreter.vm();
if (is<PrivateIdentifier>(key)) { if (is<PrivateIdentifier>(key)) {
auto& private_identifier = static_cast<PrivateIdentifier const&>(key); auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
@ -1546,9 +1548,9 @@ static ThrowCompletionOr<ClassElementName> class_key_to_property_name(Interprete
auto prop_key = TRY(key.execute(interpreter)).release_value(); auto prop_key = TRY(key.execute(interpreter)).release_value();
if (prop_key.is_object()) if (prop_key.is_object())
prop_key = TRY(prop_key.to_primitive(global_object, Value::PreferredType::String)); prop_key = TRY(prop_key.to_primitive(vm, Value::PreferredType::String));
auto property_key = TRY(PropertyKey::from_value(global_object, prop_key)); auto property_key = TRY(PropertyKey::from_value(vm, prop_key));
return ClassElementName { property_key }; return ClassElementName { property_key };
} }
@ -1857,7 +1859,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> ClassExpression::class_definition_e
} else if (!super_class.is_constructor()) { } else if (!super_class.is_constructor()) {
return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects());
} else { } else {
auto super_class_prototype = TRY(super_class.get(global_object, vm.names.prototype)); auto super_class_prototype = TRY(super_class.get(vm, vm.names.prototype));
if (!super_class_prototype.is_null() && !super_class_prototype.is_object()) if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects());
@ -2597,6 +2599,7 @@ Completion AssignmentExpression::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = interpreter.vm();
if (m_op == AssignmentOp::Assignment) { if (m_op == AssignmentOp::Assignment) {
// AssignmentExpression : LeftHandSideExpression = AssignmentExpression // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
@ -2713,40 +2716,40 @@ Completion AssignmentExpression::execute(Interpreter& interpreter) const
// 7. Let r be ? ApplyStringOrNumericBinaryOperator(lval, opText, rval). // 7. Let r be ? ApplyStringOrNumericBinaryOperator(lval, opText, rval).
switch (m_op) { switch (m_op) {
case AssignmentOp::AdditionAssignment: case AssignmentOp::AdditionAssignment:
rhs_result = TRY(add(global_object, lhs_result, rhs_result)); rhs_result = TRY(add(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::SubtractionAssignment: case AssignmentOp::SubtractionAssignment:
rhs_result = TRY(sub(global_object, lhs_result, rhs_result)); rhs_result = TRY(sub(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::MultiplicationAssignment: case AssignmentOp::MultiplicationAssignment:
rhs_result = TRY(mul(global_object, lhs_result, rhs_result)); rhs_result = TRY(mul(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::DivisionAssignment: case AssignmentOp::DivisionAssignment:
rhs_result = TRY(div(global_object, lhs_result, rhs_result)); rhs_result = TRY(div(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::ModuloAssignment: case AssignmentOp::ModuloAssignment:
rhs_result = TRY(mod(global_object, lhs_result, rhs_result)); rhs_result = TRY(mod(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::ExponentiationAssignment: case AssignmentOp::ExponentiationAssignment:
rhs_result = TRY(exp(global_object, lhs_result, rhs_result)); rhs_result = TRY(exp(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::BitwiseAndAssignment: case AssignmentOp::BitwiseAndAssignment:
rhs_result = TRY(bitwise_and(global_object, lhs_result, rhs_result)); rhs_result = TRY(bitwise_and(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::BitwiseOrAssignment: case AssignmentOp::BitwiseOrAssignment:
rhs_result = TRY(bitwise_or(global_object, lhs_result, rhs_result)); rhs_result = TRY(bitwise_or(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::BitwiseXorAssignment: case AssignmentOp::BitwiseXorAssignment:
rhs_result = TRY(bitwise_xor(global_object, lhs_result, rhs_result)); rhs_result = TRY(bitwise_xor(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::LeftShiftAssignment: case AssignmentOp::LeftShiftAssignment:
rhs_result = TRY(left_shift(global_object, lhs_result, rhs_result)); rhs_result = TRY(left_shift(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::RightShiftAssignment: case AssignmentOp::RightShiftAssignment:
rhs_result = TRY(right_shift(global_object, lhs_result, rhs_result)); rhs_result = TRY(right_shift(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::UnsignedRightShiftAssignment: case AssignmentOp::UnsignedRightShiftAssignment:
rhs_result = TRY(unsigned_right_shift(global_object, lhs_result, rhs_result)); rhs_result = TRY(unsigned_right_shift(vm, lhs_result, rhs_result));
break; break;
case AssignmentOp::Assignment: case AssignmentOp::Assignment:
case AssignmentOp::AndAssignment: case AssignmentOp::AndAssignment:
@ -2770,13 +2773,14 @@ Completion UpdateExpression::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = interpreter.vm();
// 1. Let expr be the result of evaluating <Expression>. // 1. Let expr be the result of evaluating <Expression>.
auto reference = TRY(m_argument->to_reference(interpreter)); auto reference = TRY(m_argument->to_reference(interpreter));
// 2. Let oldValue be ? ToNumeric(? GetValue(expr)). // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
auto old_value = TRY(reference.get_value(global_object)); auto old_value = TRY(reference.get_value(global_object));
old_value = TRY(old_value.to_numeric(global_object)); old_value = TRY(old_value.to_numeric(vm));
Value new_value; Value new_value;
switch (m_op) { switch (m_op) {
@ -3037,6 +3041,7 @@ Completion ObjectExpression::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = interpreter.vm();
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 1. Let obj be OrdinaryObjectCreate(%Object.prototype%). // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
@ -3049,7 +3054,7 @@ Completion ObjectExpression::execute(Interpreter& interpreter) const
// PropertyDefinition : ... AssignmentExpression // PropertyDefinition : ... AssignmentExpression
if (property.type() == ObjectProperty::Type::Spread) { if (property.type() == ObjectProperty::Type::Spread) {
// 4. Perform ? CopyDataProperties(object, fromValue, excludedNames). // 4. Perform ? CopyDataProperties(object, fromValue, excludedNames).
TRY(object->copy_data_properties(key, {}, global_object)); TRY(object->copy_data_properties(vm, key, {}));
// 5. Return unused. // 5. Return unused.
continue; continue;
@ -3071,7 +3076,7 @@ Completion ObjectExpression::execute(Interpreter& interpreter) const
if (value.is_function() && property.is_method()) if (value.is_function() && property.is_method())
static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object); static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
auto property_key = TRY(PropertyKey::from_value(global_object, key)); auto property_key = TRY(PropertyKey::from_value(vm, key));
auto name = TRY(get_function_property_name(property_key)); auto name = TRY(get_function_property_name(property_key));
if (property.type() == ObjectProperty::Type::Getter) { if (property.type() == ObjectProperty::Type::Getter) {
name = String::formatted("get {}", name); name = String::formatted("get {}", name);
@ -3328,11 +3333,12 @@ Completion ImportCall::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto& vm = interpreter.vm();
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 2.1.1.1 EvaluateImportCall ( specifierExpression [ , optionsExpression ] ), https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call // 2.1.1.1 EvaluateImportCall ( specifierExpression [ , optionsExpression ] ), https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
// 1. Let referencingScriptOrModule be GetActiveScriptOrModule(). // 1. Let referencingScriptOrModule be GetActiveScriptOrModule().
auto referencing_script_or_module = interpreter.vm().get_active_script_or_module(); auto referencing_script_or_module = vm.get_active_script_or_module();
// 2. Let specifierRef be the result of evaluating specifierExpression. // 2. Let specifierRef be the result of evaluating specifierExpression.
// 3. Let specifier be ? GetValue(specifierRef). // 3. Let specifier be ? GetValue(specifierRef).
@ -3354,7 +3360,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const
// 7. Let specifierString be Completion(ToString(specifier)). // 7. Let specifierString be Completion(ToString(specifier)).
// 8. IfAbruptRejectPromise(specifierString, promiseCapability). // 8. IfAbruptRejectPromise(specifierString, promiseCapability).
auto specifier_string = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, specifier->to_string(global_object)); auto specifier_string = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, specifier->to_string(vm));
// 9. Let assertions be a new empty List. // 9. Let assertions be a new empty List.
Vector<ModuleRequest::Assertion> assertions; Vector<ModuleRequest::Assertion> assertions;
@ -3373,7 +3379,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const
// b. Let assertionsObj be Get(options, "assert"). // b. Let assertionsObj be Get(options, "assert").
// c. IfAbruptRejectPromise(assertionsObj, promiseCapability). // c. IfAbruptRejectPromise(assertionsObj, promiseCapability).
auto assertion_object = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, options_value.get(global_object, interpreter.vm().names.assert)); auto assertion_object = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, options_value.get(vm, vm.names.assert));
// d. If assertionsObj is not undefined, // d. If assertionsObj is not undefined,
if (!assertion_object.is_undefined()) { if (!assertion_object.is_undefined()) {
@ -3396,11 +3402,11 @@ Completion ImportCall::execute(Interpreter& interpreter) const
// v. For each String key of keys, // v. For each String key of keys,
for (auto const& key : keys) { for (auto const& key : keys) {
auto property_key = MUST(key.to_property_key(global_object)); auto property_key = MUST(key.to_property_key(vm));
// 1. Let value be Get(assertionsObj, key). // 1. Let value be Get(assertionsObj, key).
// 2. IfAbruptRejectPromise(value, promiseCapability). // 2. IfAbruptRejectPromise(value, promiseCapability).
auto value = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.get(global_object, property_key)); auto value = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.get(vm, property_key));
// 3. If Type(value) is not String, then // 3. If Type(value) is not String, then
if (!value.is_string()) { if (!value.is_string()) {
@ -3571,7 +3577,7 @@ void TemplateLiteral::dump(int indent) const
Completion TemplateLiteral::execute(Interpreter& interpreter) const Completion TemplateLiteral::execute(Interpreter& interpreter) const
{ {
InterpreterNodeScope node_scope { interpreter, *this }; InterpreterNodeScope node_scope { interpreter, *this };
auto& global_object = interpreter.global_object(); auto& vm = interpreter.vm();
StringBuilder string_builder; StringBuilder string_builder;
@ -3583,7 +3589,7 @@ Completion TemplateLiteral::execute(Interpreter& interpreter) const
auto sub = TRY(expression.execute(interpreter)).release_value(); auto sub = TRY(expression.execute(interpreter)).release_value();
// 4. Let middle be ? ToString(sub). // 4. Let middle be ? ToString(sub).
auto string = TRY(sub.to_string(global_object)); auto string = TRY(sub.to_string(vm));
string_builder.append(string); string_builder.append(string);
// 5. Let tail be the result of evaluating TemplateSpans. // 5. Let tail be the result of evaluating TemplateSpans.

View file

@ -47,6 +47,8 @@ namespace JS::Bytecode::Op {
static ThrowCompletionOr<void> put_by_property_key(Object* object, Value value, PropertyKey name, Bytecode::Interpreter& interpreter, PropertyKind kind) static ThrowCompletionOr<void> put_by_property_key(Object* object, Value value, PropertyKey name, Bytecode::Interpreter& interpreter, PropertyKind kind)
{ {
auto& vm = interpreter.vm();
if (kind == PropertyKind::Getter || kind == PropertyKind::Setter) { if (kind == PropertyKind::Getter || kind == PropertyKind::Setter) {
// The generator should only pass us functions for getters and setters. // The generator should only pass us functions for getters and setters.
VERIFY(value.is_function()); VERIFY(value.is_function());
@ -68,12 +70,12 @@ static ThrowCompletionOr<void> put_by_property_key(Object* object, Value value,
} }
case PropertyKind::KeyValue: { case PropertyKind::KeyValue: {
bool succeeded = TRY(object->internal_set(name, interpreter.accumulator(), object)); bool succeeded = TRY(object->internal_set(name, interpreter.accumulator(), object));
if (!succeeded && interpreter.vm().in_strict_mode()) if (!succeeded && vm.in_strict_mode())
return interpreter.vm().throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, interpreter.accumulator().to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, interpreter.accumulator().to_string_without_side_effects());
break; break;
} }
case PropertyKind::Spread: case PropertyKind::Spread:
TRY(object->copy_data_properties(value, {}, interpreter.global_object())); TRY(object->copy_data_properties(vm, value, {}));
break; break;
case PropertyKind::ProtoSetter: case PropertyKind::ProtoSetter:
if (value.is_object() || value.is_null()) if (value.is_object() || value.is_null())
@ -102,22 +104,22 @@ ThrowCompletionOr<void> Store::execute_impl(Bytecode::Interpreter& interpreter)
return {}; return {};
} }
static ThrowCompletionOr<Value> abstract_inequals(GlobalObject& global_object, Value src1, Value src2) static ThrowCompletionOr<Value> abstract_inequals(VM& vm, Value src1, Value src2)
{ {
return Value(!TRY(is_loosely_equal(global_object, src1, src2))); return Value(!TRY(is_loosely_equal(vm, src1, src2)));
} }
static ThrowCompletionOr<Value> abstract_equals(GlobalObject& global_object, Value src1, Value src2) static ThrowCompletionOr<Value> abstract_equals(VM& vm, Value src1, Value src2)
{ {
return Value(TRY(is_loosely_equal(global_object, src1, src2))); return Value(TRY(is_loosely_equal(vm, src1, src2)));
} }
static ThrowCompletionOr<Value> typed_inequals(GlobalObject&, Value src1, Value src2) static ThrowCompletionOr<Value> typed_inequals(VM&, Value src1, Value src2)
{ {
return Value(!is_strictly_equal(src1, src2)); return Value(!is_strictly_equal(src1, src2));
} }
static ThrowCompletionOr<Value> typed_equals(GlobalObject&, Value src1, Value src2) static ThrowCompletionOr<Value> typed_equals(VM&, Value src1, Value src2)
{ {
return Value(is_strictly_equal(src1, src2)); return Value(is_strictly_equal(src1, src2));
} }
@ -125,9 +127,10 @@ static ThrowCompletionOr<Value> typed_equals(GlobalObject&, Value src1, Value sr
#define JS_DEFINE_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \ #define JS_DEFINE_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \
ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \ ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
{ \ { \
auto& vm = interpreter.vm(); \
auto lhs = interpreter.reg(m_lhs_reg); \ auto lhs = interpreter.reg(m_lhs_reg); \
auto rhs = interpreter.accumulator(); \ auto rhs = interpreter.accumulator(); \
interpreter.accumulator() = TRY(op_snake_case(interpreter.global_object(), lhs, rhs)); \ interpreter.accumulator() = TRY(op_snake_case(vm, lhs, rhs)); \
return {}; \ return {}; \
} \ } \
String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \ String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \
@ -137,25 +140,26 @@ static ThrowCompletionOr<Value> typed_equals(GlobalObject&, Value src1, Value sr
JS_ENUMERATE_COMMON_BINARY_OPS(JS_DEFINE_COMMON_BINARY_OP) JS_ENUMERATE_COMMON_BINARY_OPS(JS_DEFINE_COMMON_BINARY_OP)
static ThrowCompletionOr<Value> not_(GlobalObject&, Value value) static ThrowCompletionOr<Value> not_(VM&, Value value)
{ {
return Value(!value.to_boolean()); return Value(!value.to_boolean());
} }
static ThrowCompletionOr<Value> typeof_(GlobalObject& global_object, Value value) static ThrowCompletionOr<Value> typeof_(VM& vm, Value value)
{ {
return Value(js_string(global_object.vm(), value.typeof())); return Value(js_string(vm, value.typeof()));
} }
#define JS_DEFINE_COMMON_UNARY_OP(OpTitleCase, op_snake_case) \ #define JS_DEFINE_COMMON_UNARY_OP(OpTitleCase, op_snake_case) \
ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \ ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
{ \ { \
interpreter.accumulator() = TRY(op_snake_case(interpreter.global_object(), interpreter.accumulator())); \ auto& vm = interpreter.vm(); \
return {}; \ interpreter.accumulator() = TRY(op_snake_case(vm, interpreter.accumulator())); \
} \ return {}; \
String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \ } \
{ \ String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \
return #OpTitleCase; \ { \
return #OpTitleCase; \
} }
JS_ENUMERATE_COMMON_UNARY_OPS(JS_DEFINE_COMMON_UNARY_OP) JS_ENUMERATE_COMMON_UNARY_OPS(JS_DEFINE_COMMON_UNARY_OP)
@ -203,7 +207,8 @@ static Iterator object_to_iterator(GlobalObject& global_object, Object& object)
ThrowCompletionOr<void> IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto& global_object = interpreter.global_object(); auto& global_object = interpreter.global_object();
auto iterator_object = TRY(interpreter.accumulator().to_object(global_object)); auto& vm = interpreter.vm();
auto iterator_object = TRY(interpreter.accumulator().to_object(vm));
auto iterator = object_to_iterator(global_object, *iterator_object); auto iterator = object_to_iterator(global_object, *iterator_object);
auto* array = MUST(Array::create(interpreter.realm(), 0)); auto* array = MUST(Array::create(interpreter.realm(), 0));
@ -250,7 +255,8 @@ ThrowCompletionOr<void> NewRegExp::execute_impl(Bytecode::Interpreter& interpret
ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* from_object = TRY(interpreter.reg(m_from_object).to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* from_object = TRY(interpreter.reg(m_from_object).to_object(vm));
auto* to_object = Object::create(interpreter.realm(), interpreter.global_object().object_prototype()); auto* to_object = Object::create(interpreter.realm(), interpreter.global_object().object_prototype());
@ -262,7 +268,7 @@ ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::In
for (auto& key : own_keys) { for (auto& key : own_keys) {
if (!excluded_names.contains(key)) { if (!excluded_names.contains(key)) {
auto property_key = TRY(key.to_property_key(interpreter.global_object())); auto property_key = TRY(key.to_property_key(vm));
auto property_value = TRY(from_object->get(property_key)); auto property_value = TRY(from_object->get(property_key));
to_object->define_direct_property(property_key, property_value, JS::default_attributes); to_object->define_direct_property(property_key, property_value, JS::default_attributes);
} }
@ -274,7 +280,8 @@ ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::In
ThrowCompletionOr<void> ConcatString::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> ConcatString::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
interpreter.reg(m_lhs) = TRY(add(interpreter.global_object(), interpreter.reg(m_lhs), interpreter.accumulator())); auto& vm = interpreter.vm();
interpreter.reg(m_lhs) = TRY(add(vm, interpreter.reg(m_lhs), interpreter.accumulator()));
return {}; return {};
} }
@ -328,10 +335,11 @@ ThrowCompletionOr<void> CreateEnvironment::execute_impl(Bytecode::Interpreter& i
ThrowCompletionOr<void> EnterObjectEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> EnterObjectEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto& old_environment = interpreter.vm().running_execution_context().lexical_environment; auto& vm = interpreter.vm();
auto& old_environment = vm.running_execution_context().lexical_environment;
interpreter.saved_lexical_environment_stack().append(old_environment); interpreter.saved_lexical_environment_stack().append(old_environment);
auto object = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto object = TRY(interpreter.accumulator().to_object(vm));
interpreter.vm().running_execution_context().lexical_environment = new_object_environment(*object, true, old_environment); vm.running_execution_context().lexical_environment = new_object_environment(*object, true, old_environment);
return {}; return {};
} }
@ -391,14 +399,16 @@ ThrowCompletionOr<void> SetVariable::execute_impl(Bytecode::Interpreter& interpr
ThrowCompletionOr<void> GetById::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> GetById::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.accumulator().to_object(vm));
interpreter.accumulator() = TRY(object->get(interpreter.current_executable().get_identifier(m_property))); interpreter.accumulator() = TRY(object->get(interpreter.current_executable().get_identifier(m_property)));
return {}; return {};
} }
ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.reg(m_base).to_object(vm));
PropertyKey name = interpreter.current_executable().get_identifier(m_property); PropertyKey name = interpreter.current_executable().get_identifier(m_property);
auto value = interpreter.accumulator(); auto value = interpreter.accumulator();
return put_by_property_key(object, value, name, interpreter, m_kind); return put_by_property_key(object, value, name, interpreter, m_kind);
@ -406,9 +416,10 @@ ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter
ThrowCompletionOr<void> DeleteById::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> DeleteById::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.accumulator().to_object(vm));
auto const& identifier = interpreter.current_executable().get_identifier(m_property); auto const& identifier = interpreter.current_executable().get_identifier(m_property);
bool strict = interpreter.vm().in_strict_mode(); bool strict = vm.in_strict_mode();
auto reference = Reference { object, identifier, {}, strict }; auto reference = Reference { object, identifier, {}, strict };
interpreter.accumulator() = Value(TRY(reference.delete_(interpreter.global_object()))); interpreter.accumulator() = Value(TRY(reference.delete_(interpreter.global_object())));
return {}; return {};
@ -519,23 +530,25 @@ ThrowCompletionOr<void> Return::execute_impl(Bytecode::Interpreter& interpreter)
ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object())); auto& vm = interpreter.vm();
auto old_value = TRY(interpreter.accumulator().to_numeric(vm));
if (old_value.is_number()) if (old_value.is_number())
interpreter.accumulator() = Value(old_value.as_double() + 1); interpreter.accumulator() = Value(old_value.as_double() + 1);
else else
interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 })); interpreter.accumulator() = js_bigint(vm, old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
return {}; return {};
} }
ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object())); auto& vm = interpreter.vm();
auto old_value = TRY(interpreter.accumulator().to_numeric(vm));
if (old_value.is_number()) if (old_value.is_number())
interpreter.accumulator() = Value(old_value.as_double() - 1); interpreter.accumulator() = Value(old_value.as_double() - 1);
else else
interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 })); interpreter.accumulator() = js_bigint(vm, old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
return {}; return {};
} }
@ -629,9 +642,10 @@ void Yield::replace_references_impl(BasicBlock const& from, BasicBlock const& to
ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.reg(m_base).to_object(vm));
auto property_key = TRY(interpreter.accumulator().to_property_key(interpreter.global_object())); auto property_key = TRY(interpreter.accumulator().to_property_key(vm));
interpreter.accumulator() = TRY(object->get(property_key)); interpreter.accumulator() = TRY(object->get(property_key));
return {}; return {};
@ -639,17 +653,19 @@ ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpre
ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.reg(m_base).to_object(vm));
auto property_key = TRY(interpreter.reg(m_property).to_property_key(interpreter.global_object())); auto property_key = TRY(interpreter.reg(m_property).to_property_key(vm));
return put_by_property_key(object, interpreter.accumulator(), property_key, interpreter, m_kind); return put_by_property_key(object, interpreter.accumulator(), property_key, interpreter, m_kind);
} }
ThrowCompletionOr<void> DeleteByValue::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> DeleteByValue::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto property_key = TRY(interpreter.accumulator().to_property_key(interpreter.global_object())); auto* object = TRY(interpreter.reg(m_base).to_object(vm));
bool strict = interpreter.vm().in_strict_mode(); auto property_key = TRY(interpreter.accumulator().to_property_key(vm));
bool strict = vm.in_strict_mode();
auto reference = Reference { object, property_key, {}, strict }; auto reference = Reference { object, property_key, {}, strict };
interpreter.accumulator() = Value(TRY(reference.delete_(interpreter.global_object()))); interpreter.accumulator() = Value(TRY(reference.delete_(interpreter.global_object())));
return {}; return {};
@ -679,7 +695,8 @@ ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interp
// Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations). // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
// Invariants 1 and 6 through 9 are implemented in `enumerable_own_property_names`, which implements the EnumerableOwnPropertyNames AO. // Invariants 1 and 6 through 9 are implemented in `enumerable_own_property_names`, which implements the EnumerableOwnPropertyNames AO.
auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* object = TRY(interpreter.accumulator().to_object(vm));
// Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys, // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
// so we just keep the order consistent anyway. // so we just keep the order consistent anyway.
OrderedHashTable<PropertyKey> properties; OrderedHashTable<PropertyKey> properties;
@ -688,7 +705,7 @@ ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interp
for (auto* object_to_check = object; object_to_check && !seen_objects.contains(object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) { for (auto* object_to_check = object; object_to_check && !seen_objects.contains(object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) {
seen_objects.set(object_to_check); seen_objects.set(object_to_check);
for (auto& key : TRY(object_to_check->enumerable_own_property_names(Object::PropertyKind::Key))) { for (auto& key : TRY(object_to_check->enumerable_own_property_names(Object::PropertyKind::Key))) {
properties.set(TRY(PropertyKey::from_value(interpreter.global_object(), key))); properties.set(TRY(PropertyKey::from_value(vm, key)));
} }
} }
Iterator iterator { Iterator iterator {
@ -744,7 +761,8 @@ ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interp
ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* iterator_object = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* iterator_object = TRY(interpreter.accumulator().to_object(vm));
auto iterator = object_to_iterator(interpreter.global_object(), *iterator_object); auto iterator = object_to_iterator(interpreter.global_object(), *iterator_object);
interpreter.accumulator() = TRY(iterator_next(interpreter.global_object(), iterator)); interpreter.accumulator() = TRY(iterator_next(interpreter.global_object(), iterator));
@ -753,7 +771,8 @@ ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interp
ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* iterator_result = TRY(interpreter.accumulator().to_object(vm));
auto complete = TRY(iterator_complete(interpreter.global_object(), *iterator_result)); auto complete = TRY(iterator_complete(interpreter.global_object(), *iterator_result));
interpreter.accumulator() = Value(complete); interpreter.accumulator() = Value(complete);
@ -762,7 +781,8 @@ ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter&
ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object())); auto& vm = interpreter.vm();
auto* iterator_result = TRY(interpreter.accumulator().to_object(vm));
interpreter.accumulator() = TRY(iterator_value(interpreter.global_object(), *iterator_result)); interpreter.accumulator() = TRY(iterator_value(interpreter.global_object(), *iterator_result));
return {}; return {};
@ -781,14 +801,16 @@ ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interprete
// 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
ThrowCompletionOr<void> TypeofVariable::execute_impl(Bytecode::Interpreter& interpreter) const ThrowCompletionOr<void> TypeofVariable::execute_impl(Bytecode::Interpreter& interpreter) const
{ {
auto& vm = interpreter.vm();
// 1. Let val be the result of evaluating UnaryExpression. // 1. Let val be the result of evaluating UnaryExpression.
auto const& string = interpreter.current_executable().get_identifier(m_identifier); auto const& string = interpreter.current_executable().get_identifier(m_identifier);
auto reference = TRY(interpreter.vm().resolve_binding(string)); auto reference = TRY(vm.resolve_binding(string));
// 2. If val is a Reference Record, then // 2. If val is a Reference Record, then
// a. If IsUnresolvableReference(val) is true, return "undefined". // a. If IsUnresolvableReference(val) is true, return "undefined".
if (reference.is_unresolvable()) { if (reference.is_unresolvable()) {
interpreter.accumulator() = js_string(interpreter.vm(), "undefined"sv); interpreter.accumulator() = js_string(vm, "undefined"sv);
return {}; return {};
} }
@ -797,7 +819,7 @@ ThrowCompletionOr<void> TypeofVariable::execute_impl(Bytecode::Interpreter& inte
// 4. NOTE: This step is replaced in section B.3.6.3. // 4. NOTE: This step is replaced in section B.3.6.3.
// 5. Return a String according to Table 41. // 5. Return a String according to Table 41.
interpreter.accumulator() = js_string(interpreter.vm(), value.typeof()); interpreter.accumulator() = js_string(vm, value.typeof());
return {}; return {};
} }

View file

@ -119,8 +119,10 @@ ThrowCompletionOr<Value> Console::trace()
// 1.2.1. count(label), https://console.spec.whatwg.org/#count // 1.2.1. count(label), https://console.spec.whatwg.org/#count
ThrowCompletionOr<Value> Console::count() ThrowCompletionOr<Value> Console::count()
{ {
auto& vm = this->vm();
// NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-count // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-count
auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default"; auto label = vm.argument_count() ? TRY(vm.argument(0).to_string(vm)) : "default";
// 1. Let map be the associated count map. // 1. Let map be the associated count map.
auto& map = m_counters; auto& map = m_counters;
@ -139,7 +141,7 @@ ThrowCompletionOr<Value> Console::count()
// 5. Perform Logger("count", « concat »). // 5. Perform Logger("count", « concat »).
MarkedVector<Value> concat_as_vector { global_object().heap() }; MarkedVector<Value> concat_as_vector { global_object().heap() };
concat_as_vector.append(js_string(vm(), concat)); concat_as_vector.append(js_string(vm, concat));
if (m_client) if (m_client)
TRY(m_client->logger(LogLevel::Count, concat_as_vector)); TRY(m_client->logger(LogLevel::Count, concat_as_vector));
return js_undefined(); return js_undefined();
@ -148,8 +150,10 @@ ThrowCompletionOr<Value> Console::count()
// 1.2.2. countReset(label), https://console.spec.whatwg.org/#countreset // 1.2.2. countReset(label), https://console.spec.whatwg.org/#countreset
ThrowCompletionOr<Value> Console::count_reset() ThrowCompletionOr<Value> Console::count_reset()
{ {
auto& vm = this->vm();
// NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-countreset // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-countreset
auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default"; auto label = vm.argument_count() ? TRY(vm.argument(0).to_string(vm)) : "default";
// 1. Let map be the associated count map. // 1. Let map be the associated count map.
auto& map = m_counters; auto& map = m_counters;
@ -165,7 +169,7 @@ ThrowCompletionOr<Value> Console::count_reset()
auto message = String::formatted("\"{}\" doesn't have a count", label); auto message = String::formatted("\"{}\" doesn't have a count", label);
// 2. Perform Logger("countReset", « message »); // 2. Perform Logger("countReset", « message »);
MarkedVector<Value> message_as_vector { global_object().heap() }; MarkedVector<Value> message_as_vector { global_object().heap() };
message_as_vector.append(js_string(vm(), message)); message_as_vector.append(js_string(vm, message));
if (m_client) if (m_client)
TRY(m_client->logger(LogLevel::CountReset, message_as_vector)); TRY(m_client->logger(LogLevel::CountReset, message_as_vector));
} }
@ -176,20 +180,22 @@ ThrowCompletionOr<Value> Console::count_reset()
// 1.1.1. assert(condition, ...data), https://console.spec.whatwg.org/#assert // 1.1.1. assert(condition, ...data), https://console.spec.whatwg.org/#assert
ThrowCompletionOr<Value> Console::assert_() ThrowCompletionOr<Value> Console::assert_()
{ {
auto& vm = this->vm();
// 1. If condition is true, return. // 1. If condition is true, return.
auto condition = vm().argument(0).to_boolean(); auto condition = vm.argument(0).to_boolean();
if (condition) if (condition)
return js_undefined(); return js_undefined();
// 2. Let message be a string without any formatting specifiers indicating generically an assertion failure (such as "Assertion failed"). // 2. Let message be a string without any formatting specifiers indicating generically an assertion failure (such as "Assertion failed").
auto message = js_string(vm(), "Assertion failed"); auto message = js_string(vm, "Assertion failed");
// NOTE: Assemble `data` from the function arguments. // NOTE: Assemble `data` from the function arguments.
MarkedVector<Value> data { global_object().heap() }; MarkedVector<Value> data { global_object().heap() };
if (vm().argument_count() > 1) { if (vm.argument_count() > 1) {
data.ensure_capacity(vm().argument_count() - 1); data.ensure_capacity(vm.argument_count() - 1);
for (size_t i = 1; i < vm().argument_count(); ++i) { for (size_t i = 1; i < vm.argument_count(); ++i) {
data.append(vm().argument(i)); data.append(vm.argument(i));
} }
} }
@ -208,7 +214,7 @@ ThrowCompletionOr<Value> Console::assert_()
// 3. Otherwise: // 3. Otherwise:
else { else {
// 1. Let concat be the concatenation of message, U+003A (:), U+0020 SPACE, and first. // 1. Let concat be the concatenation of message, U+003A (:), U+0020 SPACE, and first.
auto concat = js_string(vm(), String::formatted("{}: {}", message->string(), first.to_string(global_object()).value())); auto concat = js_string(vm, String::formatted("{}: {}", message->string(), first.to_string(vm).value()));
// 2. Set data[0] to concat. // 2. Set data[0] to concat.
data[0] = concat; data[0] = concat;
} }
@ -305,15 +311,17 @@ ThrowCompletionOr<Value> Console::group_end()
// 1.4.1. time(label), https://console.spec.whatwg.org/#time // 1.4.1. time(label), https://console.spec.whatwg.org/#time
ThrowCompletionOr<Value> Console::time() ThrowCompletionOr<Value> Console::time()
{ {
auto& vm = this->vm();
// NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-time // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-time
auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default"; auto label = vm.argument_count() ? TRY(vm.argument(0).to_string(vm)) : "default";
// 1. If the associated timer table contains an entry with key label, return, optionally reporting // 1. If the associated timer table contains an entry with key label, return, optionally reporting
// a warning to the console indicating that a timer with label `label` has already been started. // a warning to the console indicating that a timer with label `label` has already been started.
if (m_timer_table.contains(label)) { if (m_timer_table.contains(label)) {
if (m_client) { if (m_client) {
MarkedVector<Value> timer_already_exists_warning_message_as_vector { global_object().heap() }; MarkedVector<Value> timer_already_exists_warning_message_as_vector { global_object().heap() };
timer_already_exists_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' already exists.", label))); timer_already_exists_warning_message_as_vector.append(js_string(vm, String::formatted("Timer '{}' already exists.", label)));
TRY(m_client->printer(LogLevel::Warn, move(timer_already_exists_warning_message_as_vector))); TRY(m_client->printer(LogLevel::Warn, move(timer_already_exists_warning_message_as_vector)));
} }
return js_undefined(); return js_undefined();
@ -327,8 +335,10 @@ ThrowCompletionOr<Value> Console::time()
// 1.4.2. timeLog(label, ...data), https://console.spec.whatwg.org/#timelog // 1.4.2. timeLog(label, ...data), https://console.spec.whatwg.org/#timelog
ThrowCompletionOr<Value> Console::time_log() ThrowCompletionOr<Value> Console::time_log()
{ {
auto& vm = this->vm();
// NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timelog // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timelog
auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default"; auto label = vm.argument_count() ? TRY(vm.argument(0).to_string(vm)) : "default";
// 1. Let timerTable be the associated timer table. // 1. Let timerTable be the associated timer table.
@ -339,7 +349,7 @@ ThrowCompletionOr<Value> Console::time_log()
if (maybe_start_time == m_timer_table.end()) { if (maybe_start_time == m_timer_table.end()) {
if (m_client) { if (m_client) {
MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() }; MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() };
timer_does_not_exist_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' does not exist.", label))); timer_does_not_exist_warning_message_as_vector.append(js_string(vm, String::formatted("Timer '{}' does not exist.", label)));
TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector))); TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
} }
return js_undefined(); return js_undefined();
@ -354,10 +364,10 @@ ThrowCompletionOr<Value> Console::time_log()
// 5. Prepend concat to data. // 5. Prepend concat to data.
MarkedVector<Value> data { global_object().heap() }; MarkedVector<Value> data { global_object().heap() };
data.ensure_capacity(vm().argument_count()); data.ensure_capacity(vm.argument_count());
data.append(js_string(vm(), concat)); data.append(js_string(vm, concat));
for (size_t i = 1; i < vm().argument_count(); ++i) for (size_t i = 1; i < vm.argument_count(); ++i)
data.append(vm().argument(i)); data.append(vm.argument(i));
// 6. Perform Printer("timeLog", data). // 6. Perform Printer("timeLog", data).
if (m_client) if (m_client)
@ -368,8 +378,10 @@ ThrowCompletionOr<Value> Console::time_log()
// 1.4.3. timeEnd(label), https://console.spec.whatwg.org/#timeend // 1.4.3. timeEnd(label), https://console.spec.whatwg.org/#timeend
ThrowCompletionOr<Value> Console::time_end() ThrowCompletionOr<Value> Console::time_end()
{ {
auto& vm = this->vm();
// NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timeend // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timeend
auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default"; auto label = vm.argument_count() ? TRY(vm.argument(0).to_string(vm)) : "default";
// 1. Let timerTable be the associated timer table. // 1. Let timerTable be the associated timer table.
@ -380,7 +392,7 @@ ThrowCompletionOr<Value> Console::time_end()
if (maybe_start_time == m_timer_table.end()) { if (maybe_start_time == m_timer_table.end()) {
if (m_client) { if (m_client) {
MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() }; MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() };
timer_does_not_exist_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' does not exist.", label))); timer_does_not_exist_warning_message_as_vector.append(js_string(vm, String::formatted("Timer '{}' does not exist.", label)));
TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector))); TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
} }
return js_undefined(); return js_undefined();
@ -399,7 +411,7 @@ ThrowCompletionOr<Value> Console::time_end()
// 6. Perform Printer("timeEnd", « concat »). // 6. Perform Printer("timeEnd", « concat »).
if (m_client) { if (m_client) {
MarkedVector<Value> concat_as_vector { global_object().heap() }; MarkedVector<Value> concat_as_vector { global_object().heap() };
concat_as_vector.append(js_string(vm(), concat)); concat_as_vector.append(js_string(vm, concat));
TRY(m_client->printer(LogLevel::TimeEnd, move(concat_as_vector))); TRY(m_client->printer(LogLevel::TimeEnd, move(concat_as_vector)));
} }
return js_undefined(); return js_undefined();
@ -443,11 +455,12 @@ void Console::output_debug_message([[maybe_unused]] LogLevel log_level, [[maybe_
ThrowCompletionOr<String> Console::value_vector_to_string(MarkedVector<Value> const& values) ThrowCompletionOr<String> Console::value_vector_to_string(MarkedVector<Value> const& values)
{ {
auto& vm = this->vm();
StringBuilder builder; StringBuilder builder;
for (auto const& item : values) { for (auto const& item : values) {
if (!builder.is_empty()) if (!builder.is_empty())
builder.append(' '); builder.append(' ');
builder.append(TRY(item.to_string(global_object()))); builder.append(TRY(item.to_string(vm)));
} }
return builder.to_string(); return builder.to_string();
} }
@ -488,6 +501,7 @@ VM& ConsoleClient::vm()
ThrowCompletionOr<Value> ConsoleClient::logger(Console::LogLevel log_level, MarkedVector<Value> const& args) ThrowCompletionOr<Value> ConsoleClient::logger(Console::LogLevel log_level, MarkedVector<Value> const& args)
{ {
auto& global_object = this->global_object(); auto& global_object = this->global_object();
auto& vm = this->vm();
// 1. If args is empty, return. // 1. If args is empty, return.
if (args.is_empty()) if (args.is_empty())
@ -507,7 +521,7 @@ ThrowCompletionOr<Value> ConsoleClient::logger(Console::LogLevel log_level, Mark
} }
// 5. If first does not contain any format specifiers, perform Printer(logLevel, args). // 5. If first does not contain any format specifiers, perform Printer(logLevel, args).
if (!TRY(first.to_string(global_object)).contains('%')) { if (!TRY(first.to_string(vm)).contains('%')) {
TRY(printer(log_level, args)); TRY(printer(log_level, args));
} else { } else {
// 6. Otherwise, perform Printer(logLevel, Formatter(args)). // 6. Otherwise, perform Printer(logLevel, Formatter(args)).

View file

@ -80,7 +80,7 @@ JS_DEFINE_NATIVE_FUNCTION($262Object::detach_array_buffer)
JS_DEFINE_NATIVE_FUNCTION($262Object::eval_script) JS_DEFINE_NATIVE_FUNCTION($262Object::eval_script)
{ {
auto source = TRY(vm.argument(0).to_string(global_object)); auto source = TRY(vm.argument(0).to_string(vm));
auto script_or_error = Script::parse(source, *vm.current_realm()); auto script_or_error = Script::parse(source, *vm.current_realm());
if (script_or_error.is_error()) if (script_or_error.is_error())
return vm.throw_completion<SyntaxError>(script_or_error.error()[0].to_string()); return vm.throw_completion<SyntaxError>(script_or_error.error()[0].to_string());

View file

@ -38,7 +38,7 @@ JS_DEFINE_NATIVE_FUNCTION(AgentObject::monotonic_now)
JS_DEFINE_NATIVE_FUNCTION(AgentObject::sleep) JS_DEFINE_NATIVE_FUNCTION(AgentObject::sleep)
{ {
auto milliseconds = TRY(vm.argument(0).to_i32(global_object)); auto milliseconds = TRY(vm.argument(0).to_i32(vm));
::usleep(milliseconds * 1000); ::usleep(milliseconds * 1000);
return js_undefined(); return js_undefined();
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -35,7 +35,7 @@ void GlobalObject::visit_edges(Cell::Visitor& visitor)
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::print) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::print)
{ {
auto string = TRY(vm.argument(0).to_string(global_object)); auto string = TRY(vm.argument(0).to_string(vm));
outln("{}", string); outln("{}", string);
return js_undefined(); return js_undefined();
} }

View file

@ -92,7 +92,7 @@ ThrowCompletionOr<size_t> length_of_array_like(GlobalObject& global_object, Obje
{ {
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto result = TRY(object.get(vm.names.length)); auto result = TRY(object.get(vm.names.length));
return result.to_length(global_object); return result.to_length(vm);
} }
// 7.3.20 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike // 7.3.20 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike
@ -1220,7 +1220,8 @@ CanonicalIndex canonical_numeric_index_string(PropertyKey const& property_key, C
// 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https://tc39.es/ecma262/#sec-getsubstitution // 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https://tc39.es/ecma262/#sec-getsubstitution
ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement) ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement)
{ {
auto replace_string = TRY(replacement.to_utf16_string(global_object)); auto& vm = global_object.vm();
auto replace_string = TRY(replacement.to_utf16_string(vm));
auto replace_view = replace_string.view(); auto replace_view = replace_string.view();
StringBuilder result; StringBuilder result;
@ -1262,7 +1263,7 @@ ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16Vie
auto& value = captures[*capture_position - 1]; auto& value = captures[*capture_position - 1];
if (!value.is_undefined()) { if (!value.is_undefined()) {
auto value_string = TRY(value.to_string(global_object)); auto value_string = TRY(value.to_string(vm));
result.append(value_string); result.append(value_string);
} }
@ -1290,7 +1291,7 @@ ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16Vie
auto capture = TRY(named_captures.as_object().get(group_name)); auto capture = TRY(named_captures.as_object().get(group_name));
if (!capture.is_undefined()) { if (!capture.is_undefined()) {
auto capture_string = TRY(capture.to_string(global_object)); auto capture_string = TRY(capture.to_string(vm));
result.append(capture_string); result.append(capture_string);
} }

View file

@ -46,7 +46,7 @@ ThrowCompletionOr<Object*> AggregateErrorConstructor::construct(FunctionObject&
auto* aggregate_error = TRY(ordinary_create_from_constructor<AggregateError>(global_object, new_target, &GlobalObject::aggregate_error_prototype)); auto* aggregate_error = TRY(ordinary_create_from_constructor<AggregateError>(global_object, new_target, &GlobalObject::aggregate_error_prototype));
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
auto message = TRY(vm.argument(1).to_string(global_object)); auto message = TRY(vm.argument(1).to_string(vm));
aggregate_error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, message)); aggregate_error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, message));
} }

View file

@ -68,7 +68,6 @@ Array::Array(Object& prototype)
// 10.4.2.4 ArraySetLength ( A, Desc ), https://tc39.es/ecma262/#sec-arraysetlength // 10.4.2.4 ArraySetLength ( A, Desc ), https://tc39.es/ecma262/#sec-arraysetlength
ThrowCompletionOr<bool> Array::set_length(PropertyDescriptor const& property_descriptor) ThrowCompletionOr<bool> Array::set_length(PropertyDescriptor const& property_descriptor)
{ {
auto& global_object = this->global_object();
auto& vm = this->vm(); auto& vm = this->vm();
// 1. If Desc does not have a [[Value]] field, then // 1. If Desc does not have a [[Value]] field, then
@ -79,9 +78,9 @@ ThrowCompletionOr<bool> Array::set_length(PropertyDescriptor const& property_des
size_t new_length = indexed_properties().array_like_size(); size_t new_length = indexed_properties().array_like_size();
if (property_descriptor.value.has_value()) { if (property_descriptor.value.has_value()) {
// 3. Let newLen be ? ToUint32(Desc.[[Value]]). // 3. Let newLen be ? ToUint32(Desc.[[Value]]).
new_length = TRY(property_descriptor.value->to_u32(global_object)); new_length = TRY(property_descriptor.value->to_u32(vm));
// 4. Let numberLen be ? ToNumber(Desc.[[Value]]). // 4. Let numberLen be ? ToNumber(Desc.[[Value]]).
auto number_length = TRY(property_descriptor.value->to_number(global_object)); auto number_length = TRY(property_descriptor.value->to_number(vm));
// 5. If newLen is not the same value as numberLen, throw a RangeError exception. // 5. If newLen is not the same value as numberLen, throw a RangeError exception.
if (new_length != number_length.as_double()) if (new_length != number_length.as_double())
return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array"); return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array");
@ -178,7 +177,7 @@ ThrowCompletionOr<double> compare_array_elements(GlobalObject& global_object, Va
if (comparefn != nullptr) { if (comparefn != nullptr) {
// a. Let v be ? ToNumber(? Call(comparefn, undefined, « x, y »)). // a. Let v be ? ToNumber(? Call(comparefn, undefined, « x, y »)).
auto value = TRY(call(global_object, comparefn, js_undefined(), x, y)); auto value = TRY(call(global_object, comparefn, js_undefined(), x, y));
auto value_number = TRY(value.to_number(global_object)); auto value_number = TRY(value.to_number(vm));
// b. If v is NaN, return +0𝔽. // b. If v is NaN, return +0𝔽.
if (value_number.is_nan()) if (value_number.is_nan())
@ -189,20 +188,20 @@ ThrowCompletionOr<double> compare_array_elements(GlobalObject& global_object, Va
} }
// 5. Let xString be ? ToString(x). // 5. Let xString be ? ToString(x).
auto* x_string = js_string(vm, TRY(x.to_string(global_object))); auto* x_string = js_string(vm, TRY(x.to_string(vm)));
// 6. Let yString be ? ToString(y). // 6. Let yString be ? ToString(y).
auto* y_string = js_string(vm, TRY(y.to_string(global_object))); auto* y_string = js_string(vm, TRY(y.to_string(vm)));
// 7. Let xSmaller be ! IsLessThan(xString, yString, true). // 7. Let xSmaller be ! IsLessThan(xString, yString, true).
auto x_smaller = MUST(is_less_than(global_object, x_string, y_string, true)); auto x_smaller = MUST(is_less_than(vm, x_string, y_string, true));
// 8. If xSmaller is true, return -1𝔽. // 8. If xSmaller is true, return -1𝔽.
if (x_smaller == TriState::True) if (x_smaller == TriState::True)
return -1; return -1;
// 9. Let ySmaller be ! IsLessThan(yString, xString, true). // 9. Let ySmaller be ! IsLessThan(yString, xString, true).
auto y_smaller = MUST(is_less_than(global_object, y_string, x_string, true)); auto y_smaller = MUST(is_less_than(vm, y_string, x_string, true));
// 10. If ySmaller is true, return 1𝔽. // 10. If ySmaller is true, return 1𝔽.
if (y_smaller == TriState::True) if (y_smaller == TriState::True)

View file

@ -135,6 +135,7 @@ template<typename T>
static ByteBuffer numeric_to_raw_bytes(GlobalObject& global_object, Value value, bool is_little_endian) static ByteBuffer numeric_to_raw_bytes(GlobalObject& global_object, Value value, bool is_little_endian)
{ {
VERIFY(value.is_number() || value.is_bigint()); VERIFY(value.is_number() || value.is_bigint());
auto& vm = global_object.vm();
using UnderlyingBufferDataType = Conditional<IsSame<ClampedU8, T>, u8, T>; using UnderlyingBufferDataType = Conditional<IsSame<ClampedU8, T>, u8, T>;
ByteBuffer raw_bytes = ByteBuffer::create_uninitialized(sizeof(UnderlyingBufferDataType)).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation. ByteBuffer raw_bytes = ByteBuffer::create_uninitialized(sizeof(UnderlyingBufferDataType)).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation.
auto flip_if_needed = [&]() { auto flip_if_needed = [&]() {
@ -145,13 +146,13 @@ static ByteBuffer numeric_to_raw_bytes(GlobalObject& global_object, Value value,
swap(raw_bytes[i], raw_bytes[sizeof(UnderlyingBufferDataType) - 1 - i]); swap(raw_bytes[i], raw_bytes[sizeof(UnderlyingBufferDataType) - 1 - i]);
}; };
if constexpr (IsSame<UnderlyingBufferDataType, float>) { if constexpr (IsSame<UnderlyingBufferDataType, float>) {
float raw_value = MUST(value.to_double(global_object)); float raw_value = MUST(value.to_double(vm));
ReadonlyBytes { &raw_value, sizeof(float) }.copy_to(raw_bytes); ReadonlyBytes { &raw_value, sizeof(float) }.copy_to(raw_bytes);
flip_if_needed(); flip_if_needed();
return raw_bytes; return raw_bytes;
} }
if constexpr (IsSame<UnderlyingBufferDataType, double>) { if constexpr (IsSame<UnderlyingBufferDataType, double>) {
double raw_value = MUST(value.to_double(global_object)); double raw_value = MUST(value.to_double(vm));
ReadonlyBytes { &raw_value, sizeof(double) }.copy_to(raw_bytes); ReadonlyBytes { &raw_value, sizeof(double) }.copy_to(raw_bytes);
flip_if_needed(); flip_if_needed();
return raw_bytes; return raw_bytes;
@ -162,9 +163,9 @@ static ByteBuffer numeric_to_raw_bytes(GlobalObject& global_object, Value value,
UnderlyingBufferDataType int_value; UnderlyingBufferDataType int_value;
if constexpr (IsSigned<UnderlyingBufferDataType>) if constexpr (IsSigned<UnderlyingBufferDataType>)
int_value = MUST(value.to_bigint_int64(global_object)); int_value = MUST(value.to_bigint_int64(vm));
else else
int_value = MUST(value.to_bigint_uint64(global_object)); int_value = MUST(value.to_bigint_uint64(vm));
ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes); ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes);
flip_if_needed(); flip_if_needed();
@ -173,20 +174,20 @@ static ByteBuffer numeric_to_raw_bytes(GlobalObject& global_object, Value value,
UnderlyingBufferDataType int_value; UnderlyingBufferDataType int_value;
if constexpr (IsSigned<UnderlyingBufferDataType>) { if constexpr (IsSigned<UnderlyingBufferDataType>) {
if constexpr (sizeof(UnderlyingBufferDataType) == 4) if constexpr (sizeof(UnderlyingBufferDataType) == 4)
int_value = MUST(value.to_i32(global_object)); int_value = MUST(value.to_i32(vm));
else if constexpr (sizeof(UnderlyingBufferDataType) == 2) else if constexpr (sizeof(UnderlyingBufferDataType) == 2)
int_value = MUST(value.to_i16(global_object)); int_value = MUST(value.to_i16(vm));
else else
int_value = MUST(value.to_i8(global_object)); int_value = MUST(value.to_i8(vm));
} else { } else {
if constexpr (sizeof(UnderlyingBufferDataType) == 4) if constexpr (sizeof(UnderlyingBufferDataType) == 4)
int_value = MUST(value.to_u32(global_object)); int_value = MUST(value.to_u32(vm));
else if constexpr (sizeof(UnderlyingBufferDataType) == 2) else if constexpr (sizeof(UnderlyingBufferDataType) == 2)
int_value = MUST(value.to_u16(global_object)); int_value = MUST(value.to_u16(vm));
else if constexpr (!IsSame<T, ClampedU8>) else if constexpr (!IsSame<T, ClampedU8>)
int_value = MUST(value.to_u8(global_object)); int_value = MUST(value.to_u8(vm));
else else
int_value = MUST(value.to_u8_clamp(global_object)); int_value = MUST(value.to_u8_clamp(vm));
} }
ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes); ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes);
if constexpr (sizeof(UnderlyingBufferDataType) % 2 == 0) if constexpr (sizeof(UnderlyingBufferDataType) % 2 == 0)

View file

@ -46,7 +46,7 @@ ThrowCompletionOr<Value> ArrayBufferConstructor::call()
ThrowCompletionOr<Object*> ArrayBufferConstructor::construct(FunctionObject& new_target) ThrowCompletionOr<Object*> ArrayBufferConstructor::construct(FunctionObject& new_target)
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto byte_length_or_error = vm.argument(0).to_index(global_object()); auto byte_length_or_error = vm.argument(0).to_index(vm);
if (byte_length_or_error.is_error()) { if (byte_length_or_error.is_error()) {
auto error = byte_length_or_error.release_error(); auto error = byte_length_or_error.release_error();

View file

@ -49,7 +49,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayBufferPrototype::slice)
auto length = array_buffer_object->byte_length(); auto length = array_buffer_object->byte_length();
// 6. Let relativeStart be ? ToIntegerOrInfinity(start). // 6. Let relativeStart be ? ToIntegerOrInfinity(start).
auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(vm));
double first; double first;
// 7. If relativeStart is -∞, let first be 0. // 7. If relativeStart is -∞, let first be 0.
@ -63,7 +63,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayBufferPrototype::slice)
first = min(relative_start, (double)length); first = min(relative_start, (double)length);
// 10. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end). // 10. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end).
auto relative_end = vm.argument(1).is_undefined() ? length : TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto relative_end = vm.argument(1).is_undefined() ? length : TRY(vm.argument(1).to_integer_or_infinity(vm));
double final; double final;
// 11. If relativeEnd is -∞, let final be 0. // 11. If relativeEnd is -∞, let final be 0.

View file

@ -66,7 +66,7 @@ ThrowCompletionOr<Object*> ArrayConstructor::construct(FunctionObject& new_targe
MUST(array->create_data_property_or_throw(0, length)); MUST(array->create_data_property_or_throw(0, length));
int_length = 1; int_length = 1;
} else { } else {
int_length = MUST(length.to_u32(global_object)); int_length = MUST(length.to_u32(vm));
if (int_length != length.as_double()) if (int_length != length.as_double())
return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array"); return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array");
} }
@ -99,7 +99,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
auto this_arg = vm.argument(2); auto this_arg = vm.argument(2);
auto items = vm.argument(0); auto items = vm.argument(0);
auto using_iterator = TRY(items.get_method(global_object, *vm.well_known_symbol_iterator())); auto using_iterator = TRY(items.get_method(vm, *vm.well_known_symbol_iterator()));
if (using_iterator) { if (using_iterator) {
Object* array; Object* array;
if (constructor.is_constructor()) if (constructor.is_constructor())
@ -142,7 +142,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
} }
} }
auto* array_like = MUST(items.to_object(global_object)); auto* array_like = MUST(items.to_object(vm));
auto length = TRY(length_of_array_like(global_object, *array_like)); auto length = TRY(length_of_array_like(global_object, *array_like));
@ -171,7 +171,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::is_array) JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::is_array)
{ {
auto value = vm.argument(0); auto value = vm.argument(0);
return Value(TRY(value.is_array(global_object))); return Value(TRY(value.is_array(vm)));
} }
// 23.1.2.3 Array.of ( ...items ), https://tc39.es/ecma262/#sec-array.of // 23.1.2.3 Array.of ( ...items ), https://tc39.es/ecma262/#sec-array.of

View file

@ -118,7 +118,7 @@ static ThrowCompletionOr<Object*> array_species_create(GlobalObject& global_obje
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto is_array = TRY(Value(&original_array).is_array(global_object)); auto is_array = TRY(Value(&original_array).is_array(vm));
if (!is_array) if (!is_array)
return TRY(Array::create(realm, length)); return TRY(Array::create(realm, length));
@ -152,9 +152,9 @@ static ThrowCompletionOr<Object*> array_species_create(GlobalObject& global_obje
// 23.1.3.1 Array.prototype.at ( index ), https://tc39.es/ecma262/#sec-array.prototype.at // 23.1.3.1 Array.prototype.at ( index ), https://tc39.es/ecma262/#sec-array.prototype.at
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::at) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::at)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
auto relative_index = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_index = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (Value(relative_index).is_infinity()) if (Value(relative_index).is_infinity())
return js_undefined(); return js_undefined();
Checked<size_t> index { 0 }; Checked<size_t> index { 0 };
@ -172,7 +172,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::at)
// 23.1.3.2 Array.prototype.concat ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.concat // 23.1.3.2 Array.prototype.concat ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.concat
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::concat) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::concat)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto* new_array = TRY(array_species_create(global_object, *this_object, 0)); auto* new_array = TRY(array_species_create(global_object, *this_object, 0));
@ -187,7 +187,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::concat)
if (!spreadable.is_undefined()) if (!spreadable.is_undefined())
return spreadable.to_boolean(); return spreadable.to_boolean();
return TRY(val.is_array(global_object)); return TRY(val.is_array(vm));
}; };
auto append_to_new_array = [&vm, &is_concat_spreadable, &new_array, &global_object, &n](Value arg) -> ThrowCompletionOr<void> { auto append_to_new_array = [&vm, &is_concat_spreadable, &new_array, &global_object, &n](Value arg) -> ThrowCompletionOr<void> {
@ -230,10 +230,10 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::concat)
// 23.1.3.4 Array.prototype.copyWithin ( target, start [ , end ] ), https://tc39.es/ecma262/#sec-array.prototype.copywithin // 23.1.3.4 Array.prototype.copyWithin ( target, start [ , end ] ), https://tc39.es/ecma262/#sec-array.prototype.copywithin
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::copy_within) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::copy_within)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
auto relative_target = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_target = TRY(vm.argument(0).to_integer_or_infinity(vm));
double to; double to;
if (relative_target < 0) if (relative_target < 0)
@ -241,7 +241,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::copy_within)
else else
to = min(relative_target, (double)length); to = min(relative_target, (double)length);
auto relative_start = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto relative_start = TRY(vm.argument(1).to_integer_or_infinity(vm));
double from; double from;
if (relative_start < 0) if (relative_start < 0)
@ -249,7 +249,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::copy_within)
else else
from = min(relative_start, (double)length); from = min(relative_start, (double)length);
auto relative_end = vm.argument(2).is_undefined() ? length : TRY(vm.argument(2).to_integer_or_infinity(global_object)); auto relative_end = vm.argument(2).is_undefined() ? length : TRY(vm.argument(2).to_integer_or_infinity(vm));
double final; double final;
if (relative_end < 0) if (relative_end < 0)
@ -298,7 +298,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::entries)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
return ArrayIterator::create(realm, this_object, Object::PropertyKind::KeyAndValue); return ArrayIterator::create(realm, this_object, Object::PropertyKind::KeyAndValue);
} }
@ -310,7 +310,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::every)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -351,7 +351,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::every)
// 23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] ), https://tc39.es/ecma262/#sec-array.prototype.fill // 23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] ), https://tc39.es/ecma262/#sec-array.prototype.fill
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::fill) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::fill)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
@ -359,14 +359,14 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::fill)
double relative_end = length; double relative_end = length;
if (vm.argument_count() >= 2) { if (vm.argument_count() >= 2) {
relative_start = TRY(vm.argument(1).to_integer_or_infinity(global_object)); relative_start = TRY(vm.argument(1).to_integer_or_infinity(vm));
if (Value(relative_start).is_negative_infinity()) if (Value(relative_start).is_negative_infinity())
relative_start = 0; relative_start = 0;
} }
// If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end). // If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end).
if (vm.argument_count() >= 3 && !vm.argument(2).is_undefined()) { if (vm.argument_count() >= 3 && !vm.argument(2).is_undefined()) {
relative_end = TRY(vm.argument(2).to_integer_or_infinity(global_object)); relative_end = TRY(vm.argument(2).to_integer_or_infinity(vm));
if (Value(relative_end).is_negative_infinity()) if (Value(relative_end).is_negative_infinity())
relative_end = 0; relative_end = 0;
} }
@ -396,7 +396,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::filter)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -454,7 +454,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::find)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -493,7 +493,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::find_index)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -532,7 +532,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::find_last)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -571,7 +571,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::find_last_index)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -619,7 +619,7 @@ static ThrowCompletionOr<size_t> flatten_into_array(GlobalObject& global_object,
if (mapper_func) if (mapper_func)
value = TRY(call(global_object, *mapper_func, this_arg, value, Value(j), &array)); value = TRY(call(global_object, *mapper_func, this_arg, value, Value(j), &array));
if (depth > 0 && TRY(value.is_array(global_object))) { if (depth > 0 && TRY(value.is_array(vm))) {
if (vm.did_reach_stack_space_limit()) if (vm.did_reach_stack_space_limit())
return vm.throw_completion<InternalError>(ErrorType::CallStackSizeExceeded); return vm.throw_completion<InternalError>(ErrorType::CallStackSizeExceeded);
@ -641,13 +641,13 @@ static ThrowCompletionOr<size_t> flatten_into_array(GlobalObject& global_object,
// 23.1.3.13 Array.prototype.flat ( [ depth ] ), https://tc39.es/ecma262/#sec-array.prototype.flat // 23.1.3.13 Array.prototype.flat ( [ depth ] ), https://tc39.es/ecma262/#sec-array.prototype.flat
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::flat) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::flat)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
double depth = 1; double depth = 1;
if (!vm.argument(0).is_undefined()) { if (!vm.argument(0).is_undefined()) {
auto depth_num = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto depth_num = TRY(vm.argument(0).to_integer_or_infinity(vm));
depth = max(depth_num, 0.0); depth = max(depth_num, 0.0);
} }
@ -664,7 +664,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::flat_map)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let sourceLen be ? LengthOfArrayLike(O). // 2. Let sourceLen be ? LengthOfArrayLike(O).
auto source_length = TRY(length_of_array_like(global_object, *object)); auto source_length = TRY(length_of_array_like(global_object, *object));
@ -690,7 +690,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::for_each)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -761,7 +761,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::group)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
@ -784,7 +784,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::group)
// c. Let propertyKey be ? ToPropertyKey(? Call(callbackfn, thisArg, « kValue, 𝔽(k), O »)). // c. Let propertyKey be ? ToPropertyKey(? Call(callbackfn, thisArg, « kValue, 𝔽(k), O »)).
auto property_key_value = TRY(call(global_object, callback_function.as_function(), this_arg, k_value, Value(index), this_object)); auto property_key_value = TRY(call(global_object, callback_function.as_function(), this_arg, k_value, Value(index), this_object));
auto property_key = TRY(property_key_value.to_property_key(global_object)); auto property_key = TRY(property_key_value.to_property_key(vm));
// d. Perform AddValueToKeyedGroup(groups, propertyKey, kValue). // d. Perform AddValueToKeyedGroup(groups, propertyKey, kValue).
add_value_to_keyed_group(global_object, groups, property_key, k_value); add_value_to_keyed_group(global_object, groups, property_key, k_value);
@ -817,7 +817,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::group_to_map)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
@ -884,13 +884,13 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::group_to_map)
// 23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] ), https://tc39.es/ecma262/#sec-array.prototype.includes // 23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] ), https://tc39.es/ecma262/#sec-array.prototype.includes
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::includes) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::includes)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
if (length == 0) if (length == 0)
return Value(false); return Value(false);
u64 from_index = 0; u64 from_index = 0;
if (vm.argument_count() >= 2) { if (vm.argument_count() >= 2) {
auto from_argument = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto from_argument = TRY(vm.argument(1).to_integer_or_infinity(vm));
if (Value(from_argument).is_positive_infinity() || from_argument >= length) if (Value(from_argument).is_positive_infinity() || from_argument >= length)
return Value(false); return Value(false);
@ -919,7 +919,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::index_of)
auto from_index = vm.argument(1); auto from_index = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -929,7 +929,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::index_of)
return Value(-1); return Value(-1);
// 4. Let n be ? ToIntegerOrInfinity(fromIndex). // 4. Let n be ? ToIntegerOrInfinity(fromIndex).
auto n = TRY(from_index.to_integer_or_infinity(global_object)); auto n = TRY(from_index.to_integer_or_infinity(vm));
// 5. Assert: If fromIndex is undefined, then n is 0. // 5. Assert: If fromIndex is undefined, then n is 0.
if (from_index.is_undefined()) if (from_index.is_undefined())
@ -987,7 +987,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::index_of)
// 23.1.3.18 Array.prototype.join ( separator ), https://tc39.es/ecma262/#sec-array.prototype.join // 23.1.3.18 Array.prototype.join ( separator ), https://tc39.es/ecma262/#sec-array.prototype.join
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
// This is not part of the spec, but all major engines do some kind of circular reference checks. // This is not part of the spec, but all major engines do some kind of circular reference checks.
// FWIW: engine262, a "100% spec compliant" ECMA-262 impl, aborts with "too much recursion". // FWIW: engine262, a "100% spec compliant" ECMA-262 impl, aborts with "too much recursion".
@ -1002,7 +1002,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join)
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
String separator = ","; String separator = ",";
if (!vm.argument(0).is_undefined()) if (!vm.argument(0).is_undefined())
separator = TRY(vm.argument(0).to_string(global_object)); separator = TRY(vm.argument(0).to_string(vm));
StringBuilder builder; StringBuilder builder;
for (size_t i = 0; i < length; ++i) { for (size_t i = 0; i < length; ++i) {
if (i > 0) if (i > 0)
@ -1010,7 +1010,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join)
auto value = TRY(this_object->get(i)); auto value = TRY(this_object->get(i));
if (value.is_nullish()) if (value.is_nullish())
continue; continue;
auto string = TRY(value.to_string(global_object)); auto string = TRY(value.to_string(vm));
builder.append(string); builder.append(string);
} }
@ -1022,7 +1022,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::keys)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
return ArrayIterator::create(realm, this_object, Object::PropertyKind::Key); return ArrayIterator::create(realm, this_object, Object::PropertyKind::Key);
} }
@ -1034,7 +1034,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::last_index_of)
auto from_index = vm.argument(1); auto from_index = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1047,7 +1047,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::last_index_of)
// 4. If fromIndex is present, let n be ? ToIntegerOrInfinity(fromIndex); else let n be len - 1. // 4. If fromIndex is present, let n be ? ToIntegerOrInfinity(fromIndex); else let n be len - 1.
if (vm.argument_count() >= 2) if (vm.argument_count() >= 2)
n = TRY(from_index.to_integer_or_infinity(global_object)); n = TRY(from_index.to_integer_or_infinity(vm));
else else
n = (double)length - 1; n = (double)length - 1;
@ -1102,7 +1102,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::map)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1145,7 +1145,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::map)
// 23.1.3.22 Array.prototype.pop ( ), https://tc39.es/ecma262/#sec-array.prototype.pop // 23.1.3.22 Array.prototype.pop ( ), https://tc39.es/ecma262/#sec-array.prototype.pop
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::pop) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::pop)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
if (length == 0) { if (length == 0) {
TRY(this_object->set(vm.names.length, Value(0), Object::ShouldThrowExceptions::Yes)); TRY(this_object->set(vm.names.length, Value(0), Object::ShouldThrowExceptions::Yes));
@ -1161,7 +1161,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::pop)
// 23.1.3.23 Array.prototype.push ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.push // 23.1.3.23 Array.prototype.push ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.push
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::push) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::push)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
auto argument_count = vm.argument_count(); auto argument_count = vm.argument_count();
auto new_length = length + argument_count; auto new_length = length + argument_count;
@ -1181,7 +1181,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reduce)
auto initial_value = vm.argument(1); auto initial_value = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1263,7 +1263,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reduce_right)
auto initial_value = vm.argument(1); auto initial_value = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1341,7 +1341,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reduce_right)
// 23.1.3.26 Array.prototype.reverse ( ), https://tc39.es/ecma262/#sec-array.prototype.reverse // 23.1.3.26 Array.prototype.reverse ( ), https://tc39.es/ecma262/#sec-array.prototype.reverse
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reverse) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reverse)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
auto middle = length / 2; auto middle = length / 2;
@ -1376,7 +1376,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::reverse)
// 23.1.3.27 Array.prototype.shift ( ), https://tc39.es/ecma262/#sec-array.prototype.shift // 23.1.3.27 Array.prototype.shift ( ), https://tc39.es/ecma262/#sec-array.prototype.shift
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::shift) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::shift)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
if (length == 0) { if (length == 0) {
TRY(this_object->set(vm.names.length, Value(0), Object::ShouldThrowExceptions::Yes)); TRY(this_object->set(vm.names.length, Value(0), Object::ShouldThrowExceptions::Yes));
@ -1403,11 +1403,11 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::shift)
// 23.1.3.28 Array.prototype.slice ( start, end ), https://tc39.es/ecma262/#sec-array.prototype.slice // 23.1.3.28 Array.prototype.slice ( start, end ), https://tc39.es/ecma262/#sec-array.prototype.slice
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::slice) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::slice)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto initial_length = TRY(length_of_array_like(global_object, *this_object)); auto initial_length = TRY(length_of_array_like(global_object, *this_object));
auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(vm));
double actual_start; double actual_start;
@ -1423,7 +1423,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::slice)
if (vm.argument(1).is_undefined() || vm.argument(1).is_empty()) if (vm.argument(1).is_undefined() || vm.argument(1).is_empty())
relative_end = (double)initial_length; relative_end = (double)initial_length;
else else
relative_end = TRY(vm.argument(1).to_integer_or_infinity(global_object)); relative_end = TRY(vm.argument(1).to_integer_or_infinity(vm));
double final; double final;
@ -1463,7 +1463,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::some)
auto this_arg = vm.argument(1); auto this_arg = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1569,7 +1569,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::sort)
return vm.throw_completion<TypeError>(ErrorType::NotAFunction, comparefn.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAFunction, comparefn.to_string_without_side_effects());
// 2. Let obj be ? ToObject(this value). // 2. Let obj be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 3. Let len be ? LengthOfArrayLike(obj). // 3. Let len be ? LengthOfArrayLike(obj).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1611,11 +1611,11 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::sort)
// 23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items ), https://tc39.es/ecma262/#sec-array.prototype.splice // 23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items ), https://tc39.es/ecma262/#sec-array.prototype.splice
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::splice) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::splice)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto initial_length = TRY(length_of_array_like(global_object, *this_object)); auto initial_length = TRY(length_of_array_like(global_object, *this_object));
auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_start = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (Value(relative_start).is_negative_infinity()) if (Value(relative_start).is_negative_infinity())
relative_start = 0; relative_start = 0;
@ -1634,7 +1634,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::splice)
actual_delete_count = initial_length - actual_start; actual_delete_count = initial_length - actual_start;
} else if (vm.argument_count() >= 2) { } else if (vm.argument_count() >= 2) {
insert_count = vm.argument_count() - 2; insert_count = vm.argument_count() - 2;
auto delete_count = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto delete_count = TRY(vm.argument(1).to_integer_or_infinity(vm));
auto temp = max(delete_count, 0); auto temp = max(delete_count, 0);
actual_delete_count = min(temp, initial_length - actual_start); actual_delete_count = min(temp, initial_length - actual_start);
} }
@ -1703,7 +1703,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_locale_string)
auto options = vm.argument(1); auto options = vm.argument(1);
// 1. Let array be ? ToObject(this value). // 1. Let array be ? ToObject(this value).
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
if (s_array_join_seen_objects.contains(this_object)) if (s_array_join_seen_objects.contains(this_object))
return js_string(vm, ""); return js_string(vm, "");
@ -1736,10 +1736,10 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_locale_string)
// c. If nextElement is not undefined or null, then // c. If nextElement is not undefined or null, then
if (!value.is_nullish()) { if (!value.is_nullish()) {
// i. Let S be ? ToString(? Invoke(nextElement, "toLocaleString", « locales, options »)). // i. Let S be ? ToString(? Invoke(nextElement, "toLocaleString", « locales, options »)).
auto locale_string_result = TRY(value.invoke(global_object, vm.names.toLocaleString, locales, options)); auto locale_string_result = TRY(value.invoke(vm, vm.names.toLocaleString, locales, options));
// ii. Set R to the string-concatenation of R and S. // ii. Set R to the string-concatenation of R and S.
auto string = TRY(locale_string_result.to_string(global_object)); auto string = TRY(locale_string_result.to_string(vm));
builder.append(string); builder.append(string);
} }
@ -1756,7 +1756,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_reversed)
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1798,7 +1798,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_sorted)
return vm.throw_completion<TypeError>(ErrorType::NotAFunction, comparefn); return vm.throw_completion<TypeError>(ErrorType::NotAFunction, comparefn);
// 2. Let O be ? ToObject(this value). // 2. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 3. Let len be ? LengthOfArrayLike(O). // 3. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
@ -1837,13 +1837,13 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_spliced)
auto delete_count = vm.argument(1); auto delete_count = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
// 3. Let relativeStart be ? ToIntegerOrInfinity(start). // 3. Let relativeStart be ? ToIntegerOrInfinity(start).
auto relative_start = TRY(start.to_integer_or_infinity(global_object)); auto relative_start = TRY(start.to_integer_or_infinity(vm));
size_t actual_start; size_t actual_start;
@ -1878,7 +1878,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_spliced)
// 10. Else, // 10. Else,
else { else {
// a. Let dc be ? ToIntegerOrInfinity(deleteCount). // a. Let dc be ? ToIntegerOrInfinity(deleteCount).
auto dc = TRY(delete_count.to_integer_or_infinity(global_object)); auto dc = TRY(delete_count.to_integer_or_infinity(vm));
// b. Let actualDeleteCount be the result of clamping dc between 0 and len - actualStart. // b. Let actualDeleteCount be the result of clamping dc between 0 and len - actualStart.
actual_delete_count = static_cast<size_t>(clamp(dc, 0, static_cast<double>(length - actual_start))); actual_delete_count = static_cast<size_t>(clamp(dc, 0, static_cast<double>(length - actual_start)));
@ -1963,7 +1963,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_spliced)
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_string) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_string)
{ {
// 1. Let array be ? ToObject(this value). // 1. Let array be ? ToObject(this value).
auto* array = TRY(vm.this_value().to_object(global_object)); auto* array = TRY(vm.this_value().to_object(vm));
// 2. Let func be ? Get(array, "join"). // 2. Let func be ? Get(array, "join").
auto func = TRY(array->get(vm.names.join)); auto func = TRY(array->get(vm.names.join));
@ -1979,7 +1979,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_string)
// 23.1.3.34 Array.prototype.unshift ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.unshift // 23.1.3.34 Array.prototype.unshift ( ...items ), https://tc39.es/ecma262/#sec-array.prototype.unshift
JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::unshift) JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::unshift)
{ {
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
auto length = TRY(length_of_array_like(global_object, *this_object)); auto length = TRY(length_of_array_like(global_object, *this_object));
auto arg_count = vm.argument_count(); auto arg_count = vm.argument_count();
size_t new_length = length + arg_count; size_t new_length = length + arg_count;
@ -2013,7 +2013,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::values)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
return ArrayIterator::create(realm, this_object, Object::PropertyKind::Value); return ArrayIterator::create(realm, this_object, Object::PropertyKind::Value);
} }
@ -2027,13 +2027,13 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::with)
auto value = vm.argument(1); auto value = vm.argument(1);
// 1. Let O be ? ToObject(this value). // 1. Let O be ? ToObject(this value).
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
// 2. Let len be ? LengthOfArrayLike(O). // 2. Let len be ? LengthOfArrayLike(O).
auto length = TRY(length_of_array_like(global_object, *object)); auto length = TRY(length_of_array_like(global_object, *object));
// 3. Let relativeIndex be ? ToIntegerOrInfinity(index). // 3. Let relativeIndex be ? ToIntegerOrInfinity(index).
auto relative_index = TRY(index.to_integer_or_infinity(global_object)); auto relative_index = TRY(index.to_integer_or_infinity(vm));
double actual_index; double actual_index;

View file

@ -108,7 +108,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::return_)
// 5. Let return be Completion(GetMethod(syncIterator, "return")). // 5. Let return be Completion(GetMethod(syncIterator, "return")).
// 6. IfAbruptRejectPromise(return, promiseCapability). // 6. IfAbruptRejectPromise(return, promiseCapability).
auto* return_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(global_object, vm.names.return_)); auto* return_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(vm, vm.names.return_));
// 7. If return is undefined, then // 7. If return is undefined, then
if (return_method == nullptr) { if (return_method == nullptr) {
@ -161,7 +161,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::throw_)
// 5. Let throw be Completion(GetMethod(syncIterator, "throw")). // 5. Let throw be Completion(GetMethod(syncIterator, "throw")).
// 6. IfAbruptRejectPromise(throw, promiseCapability). // 6. IfAbruptRejectPromise(throw, promiseCapability).
auto* throw_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(global_object, vm.names.throw_)); auto* throw_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(vm, vm.names.throw_));
// 7. If throw is undefined, then // 7. If throw is undefined, then
if (throw_method == nullptr) { if (throw_method == nullptr) {

View file

@ -48,7 +48,7 @@ ThrowCompletionOr<Value> AsyncFunctionDriverWrapper::react_to_async_task_complet
auto result = generator_result.release_value(); auto result = generator_result.release_value();
VERIFY(result.is_object()); VERIFY(result.is_object());
auto promise_value = TRY(result.get(global_object, vm.names.value)); auto promise_value = TRY(result.get(vm, vm.names.value));
if (!promise_value.is_object() || !is<Promise>(promise_value.as_object())) { if (!promise_value.is_object() || !is<Promise>(promise_value.as_object())) {
auto promise = Promise::create(realm); auto promise = Promise::create(realm);
promise->fulfill(promise_value); promise->fulfill(promise_value);
@ -56,7 +56,7 @@ ThrowCompletionOr<Value> AsyncFunctionDriverWrapper::react_to_async_task_complet
} }
auto* promise = static_cast<Promise*>(&promise_value.as_object()); auto* promise = static_cast<Promise*>(&promise_value.as_object());
if (TRY(result.get(global_object, vm.names.done)).to_boolean()) if (TRY(result.get(vm, vm.names.done)).to_boolean())
return promise; return promise;
return promise->perform_then(m_on_fulfillment, m_on_rejection, PromiseCapability { promise, m_on_fulfillment, m_on_rejection }); return promise->perform_then(m_on_fulfillment, m_on_rejection, PromiseCapability { promise, m_on_fulfillment, m_on_rejection });

View file

@ -56,7 +56,7 @@ static ThrowCompletionOr<size_t> validate_atomic_access(GlobalObject& global_obj
auto length = typed_array.array_length(); auto length = typed_array.array_length();
// 2. Let accessIndex be ? ToIndex(requestIndex). // 2. Let accessIndex be ? ToIndex(requestIndex).
auto access_index = TRY(request_index.to_index(global_object)); auto access_index = TRY(request_index.to_index(vm));
// 3. Assert: accessIndex ≥ 0. // 3. Assert: accessIndex ≥ 0.
@ -89,10 +89,10 @@ static ThrowCompletionOr<Value> atomic_read_modify_write(GlobalObject& global_ob
// 3. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value). // 3. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value).
if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt) if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt)
value_to_set = TRY(value.to_bigint(global_object)); value_to_set = TRY(value.to_bigint(vm));
// 4. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)). // 4. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
else else
value_to_set = Value(TRY(value.to_integer_or_infinity(global_object))); value_to_set = Value(TRY(value.to_integer_or_infinity(vm)));
// 5. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. // 5. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
if (buffer->is_detached()) if (buffer->is_detached())
@ -208,18 +208,18 @@ static ThrowCompletionOr<Value> atomic_compare_exchange_impl(GlobalObject& globa
// 4. If typedArray.[[ContentType]] is BigInt, then // 4. If typedArray.[[ContentType]] is BigInt, then
if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt) { if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt) {
// a. Let expected be ? ToBigInt(expectedValue). // a. Let expected be ? ToBigInt(expectedValue).
expected = TRY(vm.argument(2).to_bigint(global_object)); expected = TRY(vm.argument(2).to_bigint(vm));
// b. Let replacement be ? ToBigInt(replacementValue). // b. Let replacement be ? ToBigInt(replacementValue).
replacement = TRY(vm.argument(3).to_bigint(global_object)); replacement = TRY(vm.argument(3).to_bigint(vm));
} }
// 5. Else, // 5. Else,
else { else {
// a. Let expected be 𝔽(? ToIntegerOrInfinity(expectedValue)). // a. Let expected be 𝔽(? ToIntegerOrInfinity(expectedValue)).
expected = Value(TRY(vm.argument(2).to_integer_or_infinity(global_object))); expected = Value(TRY(vm.argument(2).to_integer_or_infinity(vm)));
// b. Let replacement be 𝔽(? ToIntegerOrInfinity(replacementValue)). // b. Let replacement be 𝔽(? ToIntegerOrInfinity(replacementValue)).
replacement = Value(TRY(vm.argument(3).to_integer_or_infinity(global_object))); replacement = Value(TRY(vm.argument(3).to_integer_or_infinity(vm)));
} }
// 6. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. // 6. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
@ -299,7 +299,7 @@ JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::exchange)
// 25.4.7 Atomics.isLockFree ( size ), https://tc39.es/ecma262/#sec-atomics.islockfree // 25.4.7 Atomics.isLockFree ( size ), https://tc39.es/ecma262/#sec-atomics.islockfree
JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::is_lock_free) JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::is_lock_free)
{ {
auto size = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto size = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (size == 1) if (size == 1)
return Value(AK::atomic_is_lock_free<u8>()); return Value(AK::atomic_is_lock_free<u8>());
if (size == 2) if (size == 2)
@ -363,10 +363,10 @@ JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::store)
// 3. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value). // 3. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value).
if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt) if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt)
value_to_set = TRY(value.to_bigint(global_object)); value_to_set = TRY(value.to_bigint(vm));
// 4. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)). // 4. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
else else
value_to_set = Value(TRY(value.to_integer_or_infinity(global_object))); value_to_set = Value(TRY(value.to_integer_or_infinity(vm)));
// 5. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. // 5. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
if (typed_array->viewed_array_buffer()->is_detached()) if (typed_array->viewed_array_buffer()->is_detached())

View file

@ -46,14 +46,14 @@ ThrowCompletionOr<Value> BigIntConstructor::call()
auto value = vm.argument(0); auto value = vm.argument(0);
// 2. Let prim be ? ToPrimitive(value, number). // 2. Let prim be ? ToPrimitive(value, number).
auto primitive = TRY(value.to_primitive(global_object, Value::PreferredType::Number)); auto primitive = TRY(value.to_primitive(vm, Value::PreferredType::Number));
// 3. If Type(prim) is Number, return ? NumberToBigInt(prim). // 3. If Type(prim) is Number, return ? NumberToBigInt(prim).
if (primitive.is_number()) if (primitive.is_number())
return TRY(number_to_bigint(global_object, primitive)); return TRY(number_to_bigint(global_object, primitive));
// 4. Otherwise, return ? ToBigInt(prim). // 4. Otherwise, return ? ToBigInt(prim).
return TRY(primitive.to_bigint(global_object)); return TRY(primitive.to_bigint(vm));
} }
// 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value
@ -66,10 +66,10 @@ ThrowCompletionOr<Object*> BigIntConstructor::construct(FunctionObject&)
JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n) JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n)
{ {
// 1. Set bits to ? ToIndex(bits). // 1. Set bits to ? ToIndex(bits).
auto bits = TRY(vm.argument(0).to_index(global_object)); auto bits = TRY(vm.argument(0).to_index(vm));
// 2. Set bigint to ? ToBigInt(bigint). // 2. Set bigint to ? ToBigInt(bigint).
auto* bigint = TRY(vm.argument(1).to_bigint(global_object)); auto* bigint = TRY(vm.argument(1).to_bigint(vm));
// 3. Let mod be (bigint) modulo 2^bits. // 3. Let mod be (bigint) modulo 2^bits.
// FIXME: For large values of `bits`, this can likely be improved with a SignedBigInteger API to // FIXME: For large values of `bits`, this can likely be improved with a SignedBigInteger API to
@ -92,10 +92,10 @@ JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n)
JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_uint_n) JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_uint_n)
{ {
// 1. Set bits to ? ToIndex(bits). // 1. Set bits to ? ToIndex(bits).
auto bits = TRY(vm.argument(0).to_index(global_object)); auto bits = TRY(vm.argument(0).to_index(vm));
// 2. Set bigint to ? ToBigInt(bigint). // 2. Set bigint to ? ToBigInt(bigint).
auto* bigint = TRY(vm.argument(1).to_bigint(global_object)); auto* bigint = TRY(vm.argument(1).to_bigint(vm));
// 3. Return the BigInt value that represents (bigint) modulo 2bits. // 3. Return the BigInt value that represents (bigint) modulo 2bits.
// FIXME: For large values of `bits`, this can likely be improved with a SignedBigInteger API to // FIXME: For large values of `bits`, this can likely be improved with a SignedBigInteger API to

View file

@ -52,7 +52,7 @@ JS_DEFINE_NATIVE_FUNCTION(BigIntPrototype::to_string)
auto* bigint = TRY(this_bigint_value(global_object, vm.this_value())); auto* bigint = TRY(this_bigint_value(global_object, vm.this_value()));
double radix = 10; double radix = 10;
if (!vm.argument(0).is_undefined()) { if (!vm.argument(0).is_undefined()) {
radix = TRY(vm.argument(0).to_integer_or_infinity(global_object)); radix = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (radix < 2 || radix > 36) if (radix < 2 || radix > 36)
return vm.throw_completion<RangeError>(ErrorType::InvalidRadix); return vm.throw_completion<RangeError>(ErrorType::InvalidRadix);
} }

View file

@ -48,7 +48,7 @@ ThrowCompletionOr<Object*> DataViewConstructor::construct(FunctionObject& new_ta
auto& array_buffer = static_cast<ArrayBuffer&>(buffer.as_object()); auto& array_buffer = static_cast<ArrayBuffer&>(buffer.as_object());
auto offset = TRY(vm.argument(1).to_index(global_object)); auto offset = TRY(vm.argument(1).to_index(vm));
if (array_buffer.is_detached()) if (array_buffer.is_detached())
return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer); return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
@ -61,7 +61,7 @@ ThrowCompletionOr<Object*> DataViewConstructor::construct(FunctionObject& new_ta
if (vm.argument(2).is_undefined()) { if (vm.argument(2).is_undefined()) {
view_byte_length = buffer_byte_length - offset; view_byte_length = buffer_byte_length - offset;
} else { } else {
view_byte_length = TRY(vm.argument(2).to_index(global_object)); view_byte_length = TRY(vm.argument(2).to_index(vm));
auto const checked_add = AK::make_checked(view_byte_length) + AK::make_checked(offset); auto const checked_add = AK::make_checked(view_byte_length) + AK::make_checked(offset);
if (checked_add.has_overflow() || checked_add.value() > buffer_byte_length) if (checked_add.has_overflow() || checked_add.value() > buffer_byte_length)
return vm.throw_completion<RangeError>(ErrorType::InvalidLength, vm.names.DataView); return vm.throw_completion<RangeError>(ErrorType::InvalidLength, vm.names.DataView);

View file

@ -56,7 +56,7 @@ static ThrowCompletionOr<Value> get_view_value(GlobalObject& global_object, Valu
{ {
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto* view = TRY(DataViewPrototype::typed_this_value(vm)); auto* view = TRY(DataViewPrototype::typed_this_value(vm));
auto get_index = TRY(request_index.to_index(global_object)); auto get_index = TRY(request_index.to_index(vm));
auto little_endian = is_little_endian.to_boolean(); auto little_endian = is_little_endian.to_boolean();
auto buffer = view->viewed_array_buffer(); auto buffer = view->viewed_array_buffer();
@ -86,13 +86,13 @@ static ThrowCompletionOr<Value> set_view_value(GlobalObject& global_object, Valu
{ {
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto* view = TRY(DataViewPrototype::typed_this_value(vm)); auto* view = TRY(DataViewPrototype::typed_this_value(vm));
auto get_index = TRY(request_index.to_index(global_object)); auto get_index = TRY(request_index.to_index(vm));
Value number_value; Value number_value;
if constexpr (IsIntegral<T> && sizeof(T) == 8) if constexpr (IsIntegral<T> && sizeof(T) == 8)
number_value = TRY(value.to_bigint(global_object)); number_value = TRY(value.to_bigint(vm));
else else
number_value = TRY(value.to_number(global_object)); number_value = TRY(value.to_number(vm));
auto little_endian = is_little_endian.to_boolean(); auto little_endian = is_little_endian.to_boolean();

View file

@ -223,7 +223,7 @@ ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target
// c. Else, // c. Else,
else { else {
// i. Let v be ? ToPrimitive(value). // i. Let v be ? ToPrimitive(value).
auto primitive = TRY(value.to_primitive(global_object)); auto primitive = TRY(value.to_primitive(vm));
// ii. If Type(v) is String, then // ii. If Type(v) is String, then
if (primitive.is_string()) { if (primitive.is_string()) {
@ -234,7 +234,7 @@ ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target
// iii. Else, // iii. Else,
else { else {
// 1. Let tv be ? ToNumber(v). // 1. Let tv be ? ToNumber(v).
time_value = TRY(primitive.to_number(global_object)).as_double(); time_value = TRY(primitive.to_number(vm)).as_double();
} }
} }
@ -245,12 +245,12 @@ ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target
else { else {
// a. Assert: numberOfArgs ≥ 2. // a. Assert: numberOfArgs ≥ 2.
// b. Let y be ? ToNumber(values[0]). // b. Let y be ? ToNumber(values[0]).
auto year = TRY(vm.argument(0).to_number(global_object)).as_double(); auto year = TRY(vm.argument(0).to_number(vm)).as_double();
// c. Let m be ? ToNumber(values[1]). // c. Let m be ? ToNumber(values[1]).
auto month = TRY(vm.argument(1).to_number(global_object)).as_double(); auto month = TRY(vm.argument(1).to_number(vm)).as_double();
auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> { auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> {
return vm.argument_count() > i ? TRY(vm.argument(i).to_number(global_object)).as_double() : fallback; return vm.argument_count() > i ? TRY(vm.argument(i).to_number(vm)).as_double() : fallback;
}; };
// d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽. // d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
@ -304,7 +304,7 @@ JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
if (!vm.argument_count()) if (!vm.argument_count())
return js_nan(); return js_nan();
auto date_string = TRY(vm.argument(0).to_string(global_object)); auto date_string = TRY(vm.argument(0).to_string(vm));
return Value(parse_date_string(date_string)); return Value(parse_date_string(date_string));
} }
@ -313,11 +313,11 @@ JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc) JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
{ {
auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> { auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> {
return vm.argument_count() > i ? TRY(vm.argument(i).to_number(global_object)).as_double() : fallback; return vm.argument_count() > i ? TRY(vm.argument(i).to_number(vm)).as_double() : fallback;
}; };
// 1. Let y be ? ToNumber(year). // 1. Let y be ? ToNumber(year).
auto year = TRY(vm.argument(0).to_number(global_object)).as_double(); auto year = TRY(vm.argument(0).to_number(vm)).as_double();
// 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽. // 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
auto month = TRY(arg_or(1, 0)); auto month = TRY(arg_or(1, 0));
// 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽. // 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.

View file

@ -362,7 +362,7 @@ static ThrowCompletionOr<double> argument_or_number(GlobalObject& global_object,
auto& vm = global_object.vm(); auto& vm = global_object.vm();
if (vm.argument_count() > index) if (vm.argument_count() > index)
return TRY(vm.argument(index).to_number(global_object)).as_double(); return TRY(vm.argument(index).to_number(vm)).as_double();
return fallback; return fallback;
} }
@ -372,7 +372,7 @@ static ThrowCompletionOr<Optional<double>> argument_or_empty(GlobalObject& globa
auto& vm = global_object.vm(); auto& vm = global_object.vm();
if (vm.argument_count() > index) if (vm.argument_count() > index)
return TRY(vm.argument(index).to_number(global_object)).as_double(); return TRY(vm.argument(index).to_number(vm)).as_double();
return Optional<double> {}; return Optional<double> {};
} }
@ -384,7 +384,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_date)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let dt be ? ToNumber(date). // 2. Let dt be ? ToNumber(date).
auto date = TRY(vm.argument(0).to_number(global_object)).as_double(); auto date = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If t is NaN, return NaN. // 3. If t is NaN, return NaN.
if (isnan(this_time)) if (isnan(this_time))
@ -418,7 +418,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_full_year)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let y be ? ToNumber(year). // 2. Let y be ? ToNumber(year).
auto year = TRY(vm.argument(0).to_number(global_object)).as_double(); auto year = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t). // 3. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
double time = 0; double time = 0;
@ -453,7 +453,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_hours)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let h be ? ToNumber(hour). // 2. Let h be ? ToNumber(hour).
auto hour = TRY(vm.argument(0).to_number(global_object)).as_double(); auto hour = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If min is present, let m be ? ToNumber(min). // 3. If min is present, let m be ? ToNumber(min).
auto minute = TRY(argument_or_empty(global_object, 1)); auto minute = TRY(argument_or_empty(global_object, 1));
@ -505,7 +505,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_milliseconds)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Set ms to ? ToNumber(ms). // 2. Set ms to ? ToNumber(ms).
auto millisecond = TRY(vm.argument(0).to_number(global_object)).as_double(); auto millisecond = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If t is NaN, return NaN. // 3. If t is NaN, return NaN.
if (isnan(this_time)) if (isnan(this_time))
@ -540,7 +540,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_minutes)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let m be ? ToNumber(min). // 2. Let m be ? ToNumber(min).
auto minute = TRY(vm.argument(0).to_number(global_object)).as_double(); auto minute = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If sec is present, let s be ? ToNumber(sec). // 3. If sec is present, let s be ? ToNumber(sec).
auto second = TRY(argument_or_empty(global_object, 1)); auto second = TRY(argument_or_empty(global_object, 1));
@ -587,7 +587,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_month)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let m be ? ToNumber(month). // 2. Let m be ? ToNumber(month).
auto month = TRY(vm.argument(0).to_number(global_object)).as_double(); auto month = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If date is present, let dt be ? ToNumber(date). // 3. If date is present, let dt be ? ToNumber(date).
auto date = TRY(argument_or_empty(global_object, 1)); auto date = TRY(argument_or_empty(global_object, 1));
@ -627,7 +627,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_seconds)
auto this_time = TRY(this_time_value(global_object, vm.this_value())); auto this_time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let s be ? ToNumber(sec). // 2. Let s be ? ToNumber(sec).
auto second = TRY(vm.argument(0).to_number(global_object)).as_double(); auto second = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If ms is present, let milli be ? ToNumber(ms). // 3. If ms is present, let milli be ? ToNumber(ms).
auto millisecond = TRY(argument_or_empty(global_object, 1)); auto millisecond = TRY(argument_or_empty(global_object, 1));
@ -668,7 +668,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_time)
TRY(this_time_value(global_object, vm.this_value())); TRY(this_time_value(global_object, vm.this_value()));
// 2. Let t be ? ToNumber(time). // 2. Let t be ? ToNumber(time).
auto time = TRY(vm.argument(0).to_number(global_object)).as_double(); auto time = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. Let v be TimeClip(t). // 3. Let v be TimeClip(t).
time = time_clip(time); time = time_clip(time);
@ -688,7 +688,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_date)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let dt be ? ToNumber(date). // 2. Let dt be ? ToNumber(date).
auto date = TRY(vm.argument(0).to_number(global_object)).as_double(); auto date = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If t is NaN, return NaN. // 3. If t is NaN, return NaN.
if (isnan(time)) if (isnan(time))
@ -724,7 +724,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_full_year)
time = this_time; time = this_time;
// 3. Let y be ? ToNumber(year). // 3. Let y be ? ToNumber(year).
auto year = TRY(vm.argument(0).to_number(global_object)).as_double(); auto year = TRY(vm.argument(0).to_number(vm)).as_double();
// 4. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month). // 4. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month).
auto month = TRY(argument_or_number(global_object, 1, month_from_time(time))); auto month = TRY(argument_or_number(global_object, 1, month_from_time(time)));
@ -754,7 +754,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_hours)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let h be ? ToNumber(hour). // 2. Let h be ? ToNumber(hour).
auto hour = TRY(vm.argument(0).to_number(global_object)).as_double(); auto hour = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If min is present, let m be ? ToNumber(min). // 3. If min is present, let m be ? ToNumber(min).
auto minute = TRY(argument_or_empty(global_object, 1)); auto minute = TRY(argument_or_empty(global_object, 1));
@ -803,7 +803,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_milliseconds)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Set ms to ? ToNumber(ms). // 2. Set ms to ? ToNumber(ms).
auto millisecond = TRY(vm.argument(0).to_number(global_object)).as_double(); auto millisecond = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If t is NaN, return NaN. // 3. If t is NaN, return NaN.
if (isnan(time)) if (isnan(time))
@ -835,7 +835,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_minutes)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let m be ? ToNumber(min). // 2. Let m be ? ToNumber(min).
auto minute = TRY(vm.argument(0).to_number(global_object)).as_double(); auto minute = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If sec is present, let s be ? ToNumber(sec). // 3. If sec is present, let s be ? ToNumber(sec).
auto second = TRY(argument_or_empty(global_object, 1)); auto second = TRY(argument_or_empty(global_object, 1));
@ -879,7 +879,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_month)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let m be ? ToNumber(month). // 2. Let m be ? ToNumber(month).
auto month = TRY(vm.argument(0).to_number(global_object)).as_double(); auto month = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If date is present, let dt be ? ToNumber(date). // 3. If date is present, let dt be ? ToNumber(date).
auto date = TRY(argument_or_empty(global_object, 1)); auto date = TRY(argument_or_empty(global_object, 1));
@ -916,7 +916,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_seconds)
auto time = TRY(this_time_value(global_object, vm.this_value())); auto time = TRY(this_time_value(global_object, vm.this_value()));
// 2. Let s be ? ToNumber(sec). // 2. Let s be ? ToNumber(sec).
auto second = TRY(vm.argument(0).to_number(global_object)).as_double(); auto second = TRY(vm.argument(0).to_number(vm)).as_double();
// 3. If ms is present, let milli be ? ToNumber(ms). // 3. If ms is present, let milli be ? ToNumber(ms).
auto millisecond = TRY(argument_or_empty(global_object, 1)); auto millisecond = TRY(argument_or_empty(global_object, 1));
@ -980,12 +980,12 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::to_json)
{ {
auto this_value = vm.this_value(); auto this_value = vm.this_value();
auto time_value = TRY(this_value.to_primitive(global_object, Value::PreferredType::Number)); auto time_value = TRY(this_value.to_primitive(vm, Value::PreferredType::Number));
if (time_value.is_number() && !time_value.is_finite_number()) if (time_value.is_number() && !time_value.is_finite_number())
return js_null(); return js_null();
return TRY(this_value.invoke(global_object, vm.names.toISOString)); return TRY(this_value.invoke(vm, vm.names.toISOString));
} }
static ThrowCompletionOr<Intl::DateTimeFormat*> construct_date_time_format(GlobalObject& global_object, Value locales, Value options) static ThrowCompletionOr<Intl::DateTimeFormat*> construct_date_time_format(GlobalObject& global_object, Value locales, Value options)
@ -1282,7 +1282,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_year)
time = local_time(this_time); time = local_time(this_time);
// 3. Let y be ? ToNumber(year). // 3. Let y be ? ToNumber(year).
auto year = TRY(vm.argument(0).to_number(global_object)).as_double(); auto year = TRY(vm.argument(0).to_number(vm)).as_double();
auto* this_object = MUST(typed_this_object(vm)); auto* this_object = MUST(typed_this_object(vm));

View file

@ -682,10 +682,10 @@ void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_
// b. Else, // b. Else,
else { else {
// i. Let thisValue be ! ToObject(thisArgument). // i. Let thisValue be ! ToObject(thisArgument).
this_value = MUST(this_argument.to_object(global_object())); this_value = MUST(this_argument.to_object(vm));
// ii. NOTE: ToObject produces wrapper objects using calleeRealm. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
// FIXME: It currently doesn't, as we pass the function's global object. VERIFY(vm.current_realm() == callee_realm);
} }
} }

View file

@ -49,7 +49,7 @@ ThrowCompletionOr<Object*> ErrorConstructor::construct(FunctionObject& new_targe
// 3. If message is not undefined, then // 3. If message is not undefined, then
if (!message.is_undefined()) { if (!message.is_undefined()) {
// a. Let msg be ? ToString(message). // a. Let msg be ? ToString(message).
auto msg = TRY(message.to_string(global_object)); auto msg = TRY(message.to_string(vm));
// b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg). // b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg).
error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, move(msg))); error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, move(msg)));
@ -103,7 +103,7 @@ ThrowCompletionOr<Object*> ErrorConstructor::construct(FunctionObject& new_targe
/* 3. If message is not undefined, then */ \ /* 3. If message is not undefined, then */ \
if (!message.is_undefined()) { \ if (!message.is_undefined()) { \
/* a. Let msg be ? ToString(message). */ \ /* a. Let msg be ? ToString(message). */ \
auto msg = TRY(message.to_string(global_object)); \ auto msg = TRY(message.to_string(vm)); \
\ \
/* b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg). */ \ /* b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg). */ \
error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, move(msg))); \ error->create_non_enumerable_data_property_or_throw(vm.names.message, js_string(vm, move(msg))); \

View file

@ -47,7 +47,7 @@ JS_DEFINE_NATIVE_FUNCTION(ErrorPrototype::to_string)
// 4. If name is undefined, set name to "Error"; otherwise set name to ? ToString(name). // 4. If name is undefined, set name to "Error"; otherwise set name to ? ToString(name).
auto name = name_property.is_undefined() auto name = name_property.is_undefined()
? String { "Error"sv } ? String { "Error"sv }
: TRY(name_property.to_string(global_object)); : TRY(name_property.to_string(vm));
// 5. Let msg be ? Get(O, "message"). // 5. Let msg be ? Get(O, "message").
auto message_property = TRY(this_object->get(vm.names.message)); auto message_property = TRY(this_object->get(vm.names.message));
@ -55,7 +55,7 @@ JS_DEFINE_NATIVE_FUNCTION(ErrorPrototype::to_string)
// 6. If msg is undefined, set msg to the empty String; otherwise set msg to ? ToString(msg). // 6. If msg is undefined, set msg to the empty String; otherwise set msg to ? ToString(msg).
auto message = message_property.is_undefined() auto message = message_property.is_undefined()
? String::empty() ? String::empty()
: TRY(message_property.to_string(global_object)); : TRY(message_property.to_string(vm));
// 7. If name is the empty String, return msg. // 7. If name is the empty String, return msg.
if (name.is_empty()) if (name.is_empty())
@ -88,12 +88,12 @@ JS_DEFINE_NATIVE_FUNCTION(ErrorPrototype::stack_getter)
String name = "Error"; String name = "Error";
auto name_property = TRY(error.get(vm.names.name)); auto name_property = TRY(error.get(vm.names.name));
if (!name_property.is_undefined()) if (!name_property.is_undefined())
name = TRY(name_property.to_string(global_object)); name = TRY(name_property.to_string(vm));
String message = ""; String message = "";
auto message_property = TRY(error.get(vm.names.message)); auto message_property = TRY(error.get(vm.names.message));
if (!message_property.is_undefined()) if (!message_property.is_undefined())
message = TRY(message_property.to_string(global_object)); message = TRY(message_property.to_string(vm));
String header = name; String header = name;
if (!message.is_empty()) if (!message.is_empty())

View file

@ -148,7 +148,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic
// ii. Let nextArgString be ? ToString(nextArg). // ii. Let nextArgString be ? ToString(nextArg).
// iii. Set P to the string-concatenation of P, "," (a comma), and nextArgString. // iii. Set P to the string-concatenation of P, "," (a comma), and nextArgString.
parameters.append(TRY(next_arg.to_string(global_object))); parameters.append(TRY(next_arg.to_string(vm)));
// iv. Set k to k + 1. // iv. Set k to k + 1.
} }
@ -159,7 +159,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic
} }
// 13. Let bodyString be the string-concatenation of 0x000A (LINE FEED), ? ToString(bodyArg), and 0x000A (LINE FEED). // 13. Let bodyString be the string-concatenation of 0x000A (LINE FEED), ? ToString(bodyArg), and 0x000A (LINE FEED).
auto body_string = String::formatted("\n{}\n", body_arg.has_value() ? TRY(body_arg->to_string(global_object)) : ""); auto body_string = String::formatted("\n{}\n", body_arg.has_value() ? TRY(body_arg->to_string(vm)) : "");
// 14. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyString, and "}". // 14. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyString, and "}".
// 15. Let sourceText be StringToCodePoints(sourceString). // 15. Let sourceText be StringToCodePoints(sourceString).

View file

@ -175,7 +175,7 @@ JS_DEFINE_NATIVE_FUNCTION(FunctionPrototype::to_string)
// 20.2.3.6 Function.prototype [ @@hasInstance ] ( V ), https://tc39.es/ecma262/#sec-function.prototype-@@hasinstance // 20.2.3.6 Function.prototype [ @@hasInstance ] ( V ), https://tc39.es/ecma262/#sec-function.prototype-@@hasinstance
JS_DEFINE_NATIVE_FUNCTION(FunctionPrototype::symbol_has_instance) JS_DEFINE_NATIVE_FUNCTION(FunctionPrototype::symbol_has_instance)
{ {
return TRY(ordinary_has_instance(global_object, vm.argument(0), vm.this_value())); return TRY(ordinary_has_instance(vm, vm.argument(0), vm.this_value()));
} }
} }

View file

@ -26,7 +26,7 @@ ThrowCompletionOr<GeneratorObject*> GeneratorObject::create(Realm& realm, Value
} else { } else {
generating_function_prototype = TRY(generating_function->get(vm.names.prototype)); generating_function_prototype = TRY(generating_function->get(vm.names.prototype));
} }
auto* generating_function_prototype_object = TRY(generating_function_prototype.to_object(realm.global_object())); auto* generating_function_prototype_object = TRY(generating_function_prototype.to_object(vm));
auto object = realm.heap().allocate<GeneratorObject>(realm, realm, *generating_function_prototype_object, move(execution_context)); auto object = realm.heap().allocate<GeneratorObject>(realm, realm, *generating_function_prototype_object, move(execution_context));
object->m_generating_function = generating_function; object->m_generating_function = generating_function;
object->m_frame = move(frame); object->m_frame = move(frame);
@ -66,7 +66,7 @@ ThrowCompletionOr<Value> GeneratorObject::next_impl(VM& vm, GlobalObject& global
auto generated_continuation = [&](Value value) -> ThrowCompletionOr<Bytecode::BasicBlock const*> { auto generated_continuation = [&](Value value) -> ThrowCompletionOr<Bytecode::BasicBlock const*> {
if (value.is_object()) { if (value.is_object()) {
auto number_value = TRY(value.as_object().get("continuation")); auto number_value = TRY(value.as_object().get("continuation"));
return reinterpret_cast<Bytecode::BasicBlock const*>(static_cast<u64>(TRY(number_value.to_double(global_object)))); return reinterpret_cast<Bytecode::BasicBlock const*>(static_cast<u64>(TRY(number_value.to_double(vm))));
} }
return nullptr; return nullptr;
}; };

View file

@ -379,13 +379,13 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
// 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number // 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
{ {
return Value(TRY(vm.argument(0).to_number(global_object)).is_nan()); return Value(TRY(vm.argument(0).to_number(vm)).is_nan());
} }
// 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number // 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
{ {
return Value(TRY(vm.argument(0).to_number(global_object)).is_finite_number()); return Value(TRY(vm.argument(0).to_number(vm)).is_finite_number());
} }
// 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string // 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string
@ -393,10 +393,10 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
{ {
if (vm.argument(0).is_number()) if (vm.argument(0).is_number())
return vm.argument(0); return vm.argument(0);
auto input_string = TRY(vm.argument(0).to_string(global_object)); auto input_string = TRY(vm.argument(0).to_string(vm));
auto trimmed_string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left)); auto trimmed_string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left));
for (size_t length = trimmed_string.length(); length > 0; --length) { for (size_t length = trimmed_string.length(); length > 0; --length) {
auto number = MUST(Value(js_string(vm, trimmed_string.substring(0, length))).to_number(global_object)); auto number = MUST(Value(js_string(vm, trimmed_string.substring(0, length))).to_number(vm));
if (!number.is_nan()) if (!number.is_nan())
return number; return number;
} }
@ -407,7 +407,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
{ {
// 1. Let inputString be ? ToString(string). // 1. Let inputString be ? ToString(string).
auto input_string = TRY(vm.argument(0).to_string(global_object)); auto input_string = TRY(vm.argument(0).to_string(vm));
// 2. Let S be ! TrimString(inputString, start). // 2. Let S be ! TrimString(inputString, start).
auto string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left)); auto string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left));
@ -424,7 +424,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
trimmed_view = trimmed_view.substring_view(1); trimmed_view = trimmed_view.substring_view(1);
// 6. Let R be (? ToInt32(radix)). // 6. Let R be (? ToInt32(radix)).
auto radix = TRY(vm.argument(1).to_i32(global_object)); auto radix = TRY(vm.argument(1).to_i32(vm));
// 7. Let stripPrefix be true. // 7. Let stripPrefix be true.
auto strip_prefix = true; auto strip_prefix = true;
@ -614,7 +614,7 @@ static ThrowCompletionOr<String> decode(GlobalObject& global_object, String cons
// 19.2.6.4 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri // 19.2.6.4 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
{ {
auto uri_string = TRY(vm.argument(0).to_string(global_object)); auto uri_string = TRY(vm.argument(0).to_string(vm));
auto encoded = TRY(encode(global_object, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv)); auto encoded = TRY(encode(global_object, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv));
return js_string(vm, move(encoded)); return js_string(vm, move(encoded));
} }
@ -622,7 +622,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
// 19.2.6.2 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri // 19.2.6.2 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
{ {
auto uri_string = TRY(vm.argument(0).to_string(global_object)); auto uri_string = TRY(vm.argument(0).to_string(vm));
auto decoded = TRY(decode(global_object, uri_string, ";/?:@&=+$,#"sv)); auto decoded = TRY(decode(global_object, uri_string, ";/?:@&=+$,#"sv));
return js_string(vm, move(decoded)); return js_string(vm, move(decoded));
} }
@ -630,7 +630,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
// 19.2.6.5 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent // 19.2.6.5 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
{ {
auto uri_string = TRY(vm.argument(0).to_string(global_object)); auto uri_string = TRY(vm.argument(0).to_string(vm));
auto encoded = TRY(encode(global_object, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv)); auto encoded = TRY(encode(global_object, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv));
return js_string(vm, move(encoded)); return js_string(vm, move(encoded));
} }
@ -638,7 +638,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
// 19.2.6.3 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent // 19.2.6.3 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
{ {
auto uri_string = TRY(vm.argument(0).to_string(global_object)); auto uri_string = TRY(vm.argument(0).to_string(vm));
auto decoded = TRY(decode(global_object, uri_string, ""sv)); auto decoded = TRY(decode(global_object, uri_string, ""sv));
return js_string(vm, move(decoded)); return js_string(vm, move(decoded));
} }
@ -646,7 +646,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
// B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string // B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
{ {
auto string = TRY(vm.argument(0).to_string(global_object)); auto string = TRY(vm.argument(0).to_string(vm));
StringBuilder escaped; StringBuilder escaped;
for (auto code_point : utf8_to_utf16(string)) { for (auto code_point : utf8_to_utf16(string)) {
if (code_point < 256) { if (code_point < 256) {
@ -664,7 +664,7 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
// B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string // B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape) JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
{ {
auto string = TRY(vm.argument(0).to_string(global_object)); auto string = TRY(vm.argument(0).to_string(vm));
ssize_t length = string.length(); ssize_t length = string.length();
StringBuilder unescaped(length); StringBuilder unescaped(length);
for (auto k = 0; k < length; ++k) { for (auto k = 0; k < length; ++k) {

View file

@ -202,15 +202,15 @@ template<>
inline bool Object::fast_is<GlobalObject>() const { return is_global_object(); } inline bool Object::fast_is<GlobalObject>() const { return is_global_object(); }
template<typename... Args> template<typename... Args>
[[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> Value::invoke(GlobalObject& global_object, PropertyKey const& property_key, Args... args) [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> Value::invoke(VM& vm, PropertyKey const& property_key, Args... args)
{ {
if constexpr (sizeof...(Args) > 0) { if constexpr (sizeof...(Args) > 0) {
MarkedVector<Value> arglist { global_object.vm().heap() }; MarkedVector<Value> arglist { vm.heap() };
(..., arglist.append(move(args))); (..., arglist.append(move(args)));
return invoke_internal(global_object, property_key, move(arglist)); return invoke_internal(vm, property_key, move(arglist));
} }
return invoke_internal(global_object, property_key, Optional<MarkedVector<Value>> {}); return invoke_internal(vm, property_key, Optional<MarkedVector<Value>> {});
} }
} }

View file

@ -186,7 +186,6 @@ bool is_well_formed_unit_identifier(StringView unit_identifier)
ThrowCompletionOr<Vector<String>> canonicalize_locale_list(VM& vm, Value locales) ThrowCompletionOr<Vector<String>> canonicalize_locale_list(VM& vm, Value locales)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If locales is undefined, then // 1. If locales is undefined, then
if (locales.is_undefined()) { if (locales.is_undefined()) {
@ -206,12 +205,12 @@ ThrowCompletionOr<Vector<String>> canonicalize_locale_list(VM& vm, Value locales
// 4. Else, // 4. Else,
else { else {
// a. Let O be ? ToObject(locales). // a. Let O be ? ToObject(locales).
object = TRY(locales.to_object(global_object)); object = TRY(locales.to_object(vm));
} }
// 5. Let len be ? ToLength(? Get(O, "length")). // 5. Let len be ? ToLength(? Get(O, "length")).
auto length_value = TRY(object->get(vm.names.length)); auto length_value = TRY(object->get(vm.names.length));
auto length = TRY(length_value.to_length(global_object)); auto length = TRY(length_value.to_length(vm));
// 6. Let k be 0. // 6. Let k be 0.
// 7. Repeat, while k < len, // 7. Repeat, while k < len,
@ -241,7 +240,7 @@ ThrowCompletionOr<Vector<String>> canonicalize_locale_list(VM& vm, Value locales
// iv. Else, // iv. Else,
else { else {
// 1. Let tag be ? ToString(kValue). // 1. Let tag be ? ToString(kValue).
tag = TRY(key_value.to_string(global_object)); tag = TRY(key_value.to_string(vm));
} }
// v. If ! IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception. // v. If ! IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
@ -597,7 +596,6 @@ ThrowCompletionOr<Array*> supported_locales(VM& vm, Vector<String> const& reques
ThrowCompletionOr<Object*> coerce_options_to_object(VM& vm, Value options) ThrowCompletionOr<Object*> coerce_options_to_object(VM& vm, Value options)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is undefined, then // 1. If options is undefined, then
if (options.is_undefined()) { if (options.is_undefined()) {
@ -606,7 +604,7 @@ ThrowCompletionOr<Object*> coerce_options_to_object(VM& vm, Value options)
} }
// 2. Return ? ToObject(options). // 2. Return ? ToObject(options).
return TRY(options.to_object(global_object)); return TRY(options.to_object(vm));
} }
// NOTE: 9.2.13 GetOption has been removed and is being pulled in from ECMA-262 in the Temporal proposal. // NOTE: 9.2.13 GetOption has been removed and is being pulled in from ECMA-262 in the Temporal proposal.
@ -614,9 +612,6 @@ ThrowCompletionOr<Object*> coerce_options_to_object(VM& vm, Value options)
// 1.2.12 GetStringOrBooleanOption ( options, property, values, trueValue, falsyValue, fallback ), https://tc39.es/proposal-intl-numberformat-v3/out/negotiation/proposed.html#sec-getstringorbooleanoption // 1.2.12 GetStringOrBooleanOption ( options, property, values, trueValue, falsyValue, fallback ), https://tc39.es/proposal-intl-numberformat-v3/out/negotiation/proposed.html#sec-getstringorbooleanoption
ThrowCompletionOr<StringOrBoolean> get_string_or_boolean_option(VM& vm, Object const& options, PropertyKey const& property, Span<StringView const> values, StringOrBoolean true_value, StringOrBoolean falsy_value, StringOrBoolean fallback) ThrowCompletionOr<StringOrBoolean> get_string_or_boolean_option(VM& vm, Object const& options, PropertyKey const& property, Span<StringView const> values, StringOrBoolean true_value, StringOrBoolean falsy_value, StringOrBoolean fallback)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let value be ? Get(options, property). // 1. Let value be ? Get(options, property).
auto value = TRY(options.get(property)); auto value = TRY(options.get(property));
@ -636,7 +631,7 @@ ThrowCompletionOr<StringOrBoolean> get_string_or_boolean_option(VM& vm, Object c
return falsy_value; return falsy_value;
// 6. Let value be ? ToString(value). // 6. Let value be ? ToString(value).
auto value_string = TRY(value.to_string(global_object)); auto value_string = TRY(value.to_string(vm));
// 7. If values does not contain an element equal to value, return fallback. // 7. If values does not contain an element equal to value, return fallback.
auto it = find(values.begin(), values.end(), value_string); auto it = find(values.begin(), values.end(), value_string);
@ -650,15 +645,12 @@ ThrowCompletionOr<StringOrBoolean> get_string_or_boolean_option(VM& vm, Object c
// 9.2.14 DefaultNumberOption ( value, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-defaultnumberoption // 9.2.14 DefaultNumberOption ( value, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-defaultnumberoption
ThrowCompletionOr<Optional<int>> default_number_option(VM& vm, Value value, int minimum, int maximum, Optional<int> fallback) ThrowCompletionOr<Optional<int>> default_number_option(VM& vm, Value value, int minimum, int maximum, Optional<int> fallback)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If value is undefined, return fallback. // 1. If value is undefined, return fallback.
if (value.is_undefined()) if (value.is_undefined())
return fallback; return fallback;
// 2. Set value to ? ToNumber(value). // 2. Set value to ? ToNumber(value).
value = TRY(value.to_number(global_object)); value = TRY(value.to_number(vm));
// 3. If value is NaN or less than minimum or greater than maximum, throw a RangeError exception. // 3. If value is NaN or less than minimum or greater than maximum, throw a RangeError exception.
if (value.is_nan() || (value.as_double() < minimum) || (value.as_double() > maximum)) if (value.is_nan() || (value.as_double() < minimum) || (value.as_double() > maximum))

View file

@ -51,7 +51,6 @@ double compare_strings(Collator& collator, Utf8View const& x, Utf8View const& y)
ThrowCompletionOr<Value> CollatorCompareFunction::call() ThrowCompletionOr<Value> CollatorCompareFunction::call()
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto& global_object = this->global_object();
// 1. Let collator be F.[[Collator]]. // 1. Let collator be F.[[Collator]].
// 2. Assert: Type(collator) is Object and collator has an [[InitializedCollator]] internal slot. // 2. Assert: Type(collator) is Object and collator has an [[InitializedCollator]] internal slot.
@ -59,9 +58,9 @@ ThrowCompletionOr<Value> CollatorCompareFunction::call()
// 4. If y is not provided, let y be undefined. // 4. If y is not provided, let y be undefined.
// 5. Let X be ? ToString(x). // 5. Let X be ? ToString(x).
auto x = TRY(vm.argument(0).to_string(global_object)); auto x = TRY(vm.argument(0).to_string(vm));
// 6. Let Y be ? ToString(y). // 6. Let Y be ? ToString(y).
auto y = TRY(vm.argument(1).to_string(global_object)); auto y = TRY(vm.argument(1).to_string(vm));
// 7. Return CompareStrings(collator, X, Y). // 7. Return CompareStrings(collator, X, Y).
return compare_strings(m_collator, Utf8View(x), Utf8View(y)); return compare_strings(m_collator, Utf8View(x), Utf8View(y));

View file

@ -17,9 +17,6 @@ namespace JS::Intl {
// 10.1.2 InitializeCollator ( collator, locales, options ), https://tc39.es/ecma402/#sec-initializecollator // 10.1.2 InitializeCollator ( collator, locales, options ), https://tc39.es/ecma402/#sec-initializecollator
static ThrowCompletionOr<Collator*> initialize_collator(VM& vm, Collator& collator, Value locales_value, Value options_value) static ThrowCompletionOr<Collator*> initialize_collator(VM& vm, Collator& collator, Value locales_value, Value options_value)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let requestedLocales be ? CanonicalizeLocaleList(locales). // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value)); auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value));
@ -66,7 +63,7 @@ static ThrowCompletionOr<Collator*> initialize_collator(VM& vm, Collator& collat
// a. Let numeric be ! ToString(numeric). // a. Let numeric be ! ToString(numeric).
// 15. Set opt.[[kn]] to numeric. // 15. Set opt.[[kn]] to numeric.
if (!numeric.is_undefined()) if (!numeric.is_undefined())
opt.kn = MUST(numeric.to_string(global_object)); opt.kn = MUST(numeric.to_string(vm));
// 16. Let caseFirst be ? GetOption(options, "caseFirst", "string", « "upper", "lower", "false" », undefined). // 16. Let caseFirst be ? GetOption(options, "caseFirst", "string", « "upper", "lower", "false" », undefined).
// 17. Set opt.[[kf]] to caseFirst. // 17. Set opt.[[kf]] to caseFirst.

View file

@ -67,12 +67,11 @@ StringView DateTimeFormat::style_to_string(Style style)
ThrowCompletionOr<Object*> to_date_time_options(VM& vm, Value options_value, OptionRequired required, OptionDefaults defaults) ThrowCompletionOr<Object*> to_date_time_options(VM& vm, Value options_value, OptionRequired required, OptionDefaults defaults)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options). // 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options).
Object* options = nullptr; Object* options = nullptr;
if (!options_value.is_undefined()) if (!options_value.is_undefined())
options = TRY(options_value.to_object(global_object)); options = TRY(options_value.to_object(vm));
// 2. Let options be OrdinaryObjectCreate(options). // 2. Let options be OrdinaryObjectCreate(options).
options = Object::create(realm, options); options = Object::create(realm, options);

View file

@ -85,9 +85,6 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatConstructor::supported_locales_of)
// 11.1.2 InitializeDateTimeFormat ( dateTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-initializedatetimeformat // 11.1.2 InitializeDateTimeFormat ( dateTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-initializedatetimeformat
ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(VM& vm, DateTimeFormat& date_time_format, Value locales_value, Value options_value) ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(VM& vm, DateTimeFormat& date_time_format, Value locales_value, Value options_value)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let requestedLocales be ? CanonicalizeLocaleList(locales). // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value)); auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value));
@ -225,7 +222,7 @@ ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(VM& vm, DateTimeF
// 31. Else, // 31. Else,
else { else {
// a. Set timeZone to ? ToString(timeZone). // a. Set timeZone to ? ToString(timeZone).
time_zone = TRY(time_zone_value.to_string(global_object)); time_zone = TRY(time_zone_value.to_string(vm));
// b. If the result of IsValidTimeZoneName(timeZone) is false, then // b. If the result of IsValidTimeZoneName(timeZone) is false, then
if (!Temporal::is_valid_time_zone_name(time_zone)) { if (!Temporal::is_valid_time_zone_name(time_zone)) {

View file

@ -54,7 +54,7 @@ ThrowCompletionOr<Value> DateTimeFormatFunction::call()
// 4. Else, // 4. Else,
else { else {
// a. Let x be ? ToNumber(date). // a. Let x be ? ToNumber(date).
date_value = TRY(date.to_number(global_object)).as_double(); date_value = TRY(date.to_number(vm)).as_double();
} }
// 5. Return ? FormatDateTime(dtf, x). // 5. Return ? FormatDateTime(dtf, x).

View file

@ -81,7 +81,7 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format_to_parts)
// 4. Else, // 4. Else,
else { else {
// a. Let x be ? ToNumber(date). // a. Let x be ? ToNumber(date).
date_value = TRY(date.to_number(global_object)).as_double(); date_value = TRY(date.to_number(vm)).as_double();
} }
// 5. Return ? FormatDateTimeToParts(dtf, x). // 5. Return ? FormatDateTimeToParts(dtf, x).
@ -105,10 +105,10 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format_range)
return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "endDate"sv); return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "endDate"sv);
// 4. Let x be ? ToNumber(startDate). // 4. Let x be ? ToNumber(startDate).
auto start_date_number = TRY(start_date.to_number(global_object)).as_double(); auto start_date_number = TRY(start_date.to_number(vm)).as_double();
// 5. Let y be ? ToNumber(endDate). // 5. Let y be ? ToNumber(endDate).
auto end_date_number = TRY(end_date.to_number(global_object)).as_double(); auto end_date_number = TRY(end_date.to_number(vm)).as_double();
// 6. Return ? FormatDateTimeRange(dtf, x, y). // 6. Return ? FormatDateTimeRange(dtf, x, y).
auto formatted = TRY(format_date_time_range(vm, *date_time_format, start_date_number, end_date_number)); auto formatted = TRY(format_date_time_range(vm, *date_time_format, start_date_number, end_date_number));
@ -132,10 +132,10 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format_range_to_parts)
return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "endDate"sv); return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "endDate"sv);
// 4. Let x be ? ToNumber(startDate). // 4. Let x be ? ToNumber(startDate).
auto start_date_number = TRY(start_date.to_number(global_object)).as_double(); auto start_date_number = TRY(start_date.to_number(vm)).as_double();
// 5. Let y be ? ToNumber(endDate). // 5. Let y be ? ToNumber(endDate).
auto end_date_number = TRY(end_date.to_number(global_object)).as_double(); auto end_date_number = TRY(end_date.to_number(vm)).as_double();
// 6. Return ? FormatDateTimeRangeToParts(dtf, x, y). // 6. Return ? FormatDateTimeRangeToParts(dtf, x, y).
return TRY(format_date_time_range_to_parts(vm, *date_time_format, start_date_number, end_date_number)); return TRY(format_date_time_range_to_parts(vm, *date_time_format, start_date_number, end_date_number));

View file

@ -43,7 +43,7 @@ JS_DEFINE_NATIVE_FUNCTION(DisplayNamesPrototype::of)
auto* display_names = TRY(typed_this_object(vm)); auto* display_names = TRY(typed_this_object(vm));
// 3. Let code be ? ToString(code). // 3. Let code be ? ToString(code).
auto code_string = TRY(code.to_string(global_object)); auto code_string = TRY(code.to_string(vm));
code = js_string(vm, move(code_string)); code = js_string(vm, move(code_string));
// 4. Let code be ? CanonicalCodeForDisplayNames(displayNames.[[Type]], code). // 4. Let code be ? CanonicalCodeForDisplayNames(displayNames.[[Type]], code).

View file

@ -112,7 +112,7 @@ JS_DEFINE_NATIVE_FUNCTION(Intl::supported_values_of)
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 1. Let key be ? ToString(key). // 1. Let key be ? ToString(key).
auto key = TRY(vm.argument(0).to_string(global_object)); auto key = TRY(vm.argument(0).to_string(vm));
Span<StringView const> list; Span<StringView const> list;

View file

@ -275,7 +275,7 @@ ThrowCompletionOr<Object*> LocaleConstructor::construct(FunctionObject& new_targ
// 9. Else, // 9. Else,
else { else {
// a. Let tag be ? ToString(tag). // a. Let tag be ? ToString(tag).
tag = TRY(tag_value.to_string(global_object)); tag = TRY(tag_value.to_string(vm));
} }
// 10. Set options to ? CoerceOptionsToObject(options). // 10. Set options to ? CoerceOptionsToObject(options).
@ -313,7 +313,7 @@ ThrowCompletionOr<Object*> LocaleConstructor::construct(FunctionObject& new_targ
// 24. If kn is not undefined, set kn to ! ToString(kn). // 24. If kn is not undefined, set kn to ! ToString(kn).
// 25. Set opt.[[kn]] to kn. // 25. Set opt.[[kn]] to kn.
if (!kn.is_undefined()) if (!kn.is_undefined())
opt.kn = TRY(kn.to_string(global_object)); opt.kn = TRY(kn.to_string(vm));
// 26. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined). // 26. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
// 27. If numberingSystem is not undefined, then // 27. If numberingSystem is not undefined, then

View file

@ -1580,11 +1580,9 @@ int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
// 1.1.18 ToIntlMathematicalValue ( value ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-tointlmathematicalvalue // 1.1.18 ToIntlMathematicalValue ( value ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-tointlmathematicalvalue
ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value) ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let primValue be ? ToPrimitive(value, number). // 1. Let primValue be ? ToPrimitive(value, number).
auto primitive_value = TRY(value.to_primitive(global_object, Value::PreferredType::Number)); auto primitive_value = TRY(value.to_primitive(vm, Value::PreferredType::Number));
// 2. If Type(primValue) is BigInt, return the mathematical value of primValue. // 2. If Type(primValue) is BigInt, return the mathematical value of primValue.
if (primitive_value.is_bigint()) if (primitive_value.is_bigint())
@ -1594,7 +1592,7 @@ ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value va
// We short-circuit some of these steps to avoid known pitfalls. // We short-circuit some of these steps to avoid known pitfalls.
// See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82 // See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82
if (!primitive_value.is_string()) { if (!primitive_value.is_string()) {
auto number = TRY(primitive_value.to_number(global_object)); auto number = TRY(primitive_value.to_number(vm));
return number.as_double(); return number.as_double();
} }
@ -1606,7 +1604,7 @@ ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value va
// 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number. // 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number.
// 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1. // 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1.
auto mathematical_value = TRY(primitive_value.to_number(global_object)).as_double(); auto mathematical_value = TRY(primitive_value.to_number(vm)).as_double();
// 7. If mv is 0 and the first non white space code point in str is -, return negative-zero. // 7. If mv is 0 and the first non white space code point in str is -, return negative-zero.
if (mathematical_value == 0.0 && string.view().trim_whitespace(TrimMode::Left).starts_with('-')) if (mathematical_value == 0.0 && string.view().trim_whitespace(TrimMode::Left).starts_with('-'))

View file

@ -41,7 +41,7 @@ JS_DEFINE_NATIVE_FUNCTION(PluralRulesPrototype::select)
auto* plural_rules = TRY(typed_this_object(vm)); auto* plural_rules = TRY(typed_this_object(vm));
// 3. Let n be ? ToNumber(value). // 3. Let n be ? ToNumber(value).
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
// 4. Return ! ResolvePlural(pr, n). // 4. Return ! ResolvePlural(pr, n).
auto plurality = resolve_plural(*plural_rules, number); auto plurality = resolve_plural(*plural_rules, number);
@ -65,10 +65,10 @@ JS_DEFINE_NATIVE_FUNCTION(PluralRulesPrototype::select_range)
return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "end"sv); return vm.throw_completion<TypeError>(ErrorType::IsUndefined, "end"sv);
// 4. Let x be ? ToNumber(start). // 4. Let x be ? ToNumber(start).
auto x = TRY(start.to_number(global_object)); auto x = TRY(start.to_number(vm));
// 5. Let y be ? ToNumber(end). // 5. Let y be ? ToNumber(end).
auto y = TRY(end.to_number(global_object)); auto y = TRY(end.to_number(vm));
// 6. Return ? ResolvePluralRange(pr, x, y). // 6. Return ? ResolvePluralRange(pr, x, y).
auto plurality = TRY(resolve_plural_range(vm, *plural_rules, x, y)); auto plurality = TRY(resolve_plural_range(vm, *plural_rules, x, y));

View file

@ -93,9 +93,6 @@ ThrowCompletionOr<Unicode::TimeUnit> singular_relative_time_unit(VM& vm, StringV
// 17.5.2 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern // 17.5.2 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern
ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(VM& vm, RelativeTimeFormat& relative_time_format, double value, StringView unit) ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(VM& vm, RelativeTimeFormat& relative_time_format, double value, StringView unit)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: relativeTimeFormat has an [[InitializedRelativeTimeFormat]] internal slot. // 1. Assert: relativeTimeFormat has an [[InitializedRelativeTimeFormat]] internal slot.
// 2. Assert: Type(value) is Number. // 2. Assert: Type(value) is Number.
// 3. Assert: Type(unit) is String. // 3. Assert: Type(unit) is String.
@ -144,7 +141,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_patt
// 16. If numeric is equal to "auto", then // 16. If numeric is equal to "auto", then
if (relative_time_format.numeric() == RelativeTimeFormat::Numeric::Auto) { if (relative_time_format.numeric() == RelativeTimeFormat::Numeric::Auto) {
// a. Let valueString be ToString(value). // a. Let valueString be ToString(value).
auto value_string = MUST(Value(value).to_string(global_object)); auto value_string = MUST(Value(value).to_string(vm));
// b. If patterns has a field [[<valueString>]], then // b. If patterns has a field [[<valueString>]], then
if (auto patterns = find_patterns_for_tense_or_number(value_string); !patterns.is_empty()) { if (auto patterns = find_patterns_for_tense_or_number(value_string); !patterns.is_empty()) {

View file

@ -39,10 +39,10 @@ JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format)
auto* relative_time_format = TRY(typed_this_object(vm)); auto* relative_time_format = TRY(typed_this_object(vm));
// 3. Let value be ? ToNumber(value). // 3. Let value be ? ToNumber(value).
auto value = TRY(vm.argument(0).to_number(global_object)); auto value = TRY(vm.argument(0).to_number(vm));
// 4. Let unit be ? ToString(unit). // 4. Let unit be ? ToString(unit).
auto unit = TRY(vm.argument(1).to_string(global_object)); auto unit = TRY(vm.argument(1).to_string(vm));
// 5. Return ? FormatRelativeTime(relativeTimeFormat, value, unit). // 5. Return ? FormatRelativeTime(relativeTimeFormat, value, unit).
auto formatted = TRY(format_relative_time(vm, *relative_time_format, value.as_double(), unit)); auto formatted = TRY(format_relative_time(vm, *relative_time_format, value.as_double(), unit));
@ -57,10 +57,10 @@ JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format_to_parts)
auto* relative_time_format = TRY(typed_this_object(vm)); auto* relative_time_format = TRY(typed_this_object(vm));
// 3. Let value be ? ToNumber(value). // 3. Let value be ? ToNumber(value).
auto value = TRY(vm.argument(0).to_number(global_object)); auto value = TRY(vm.argument(0).to_number(vm));
// 4. Let unit be ? ToString(unit). // 4. Let unit be ? ToString(unit).
auto unit = TRY(vm.argument(1).to_string(global_object)); auto unit = TRY(vm.argument(1).to_string(vm));
// 5. Return ? FormatRelativeTimeToParts(relativeTimeFormat, value, unit). // 5. Return ? FormatRelativeTimeToParts(relativeTimeFormat, value, unit).
return TRY(format_relative_time_to_parts(vm, *relative_time_format, value.as_double(), unit)); return TRY(format_relative_time_to_parts(vm, *relative_time_format, value.as_double(), unit));

View file

@ -65,7 +65,7 @@ JS_DEFINE_NATIVE_FUNCTION(SegmenterPrototype::segment)
auto* segmenter = TRY(typed_this_object(vm)); auto* segmenter = TRY(typed_this_object(vm));
// 3. Let string be ? ToString(string). // 3. Let string be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Return ! CreateSegmentsObject(segmenter, string). // 4. Return ! CreateSegmentsObject(segmenter, string).
return Segments::create(realm, *segmenter, move(string)); return Segments::create(realm, *segmenter, move(string));

View file

@ -45,7 +45,7 @@ JS_DEFINE_NATIVE_FUNCTION(SegmentsPrototype::containing)
auto length = string.length_in_code_units(); auto length = string.length_in_code_units();
// 6. Let n be ? ToIntegerOrInfinity(index). // 6. Let n be ? ToIntegerOrInfinity(index).
auto n = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto n = TRY(vm.argument(0).to_integer_or_infinity(vm));
// 7. If n < 0 or n ≥ len, return undefined. // 7. If n < 0 or n ≥ len, return undefined.
if (n < 0 || n >= length) if (n < 0 || n >= length)

View file

@ -26,12 +26,12 @@ ThrowCompletionOr<Iterator> get_iterator(GlobalObject& global_object, Value valu
// a. If hint is async, then // a. If hint is async, then
if (hint == IteratorHint::Async) { if (hint == IteratorHint::Async) {
// i. Set method to ? GetMethod(obj, @@asyncIterator). // i. Set method to ? GetMethod(obj, @@asyncIterator).
auto* async_method = TRY(value.get_method(global_object, *vm.well_known_symbol_async_iterator())); auto* async_method = TRY(value.get_method(vm, *vm.well_known_symbol_async_iterator()));
// ii. If method is undefined, then // ii. If method is undefined, then
if (async_method == nullptr) { if (async_method == nullptr) {
// 1. Let syncMethod be ? GetMethod(obj, @@iterator). // 1. Let syncMethod be ? GetMethod(obj, @@iterator).
auto* sync_method = TRY(value.get_method(global_object, *vm.well_known_symbol_iterator())); auto* sync_method = TRY(value.get_method(vm, *vm.well_known_symbol_iterator()));
// 2. Let syncIteratorRecord be ? GetIterator(obj, sync, syncMethod). // 2. Let syncIteratorRecord be ? GetIterator(obj, sync, syncMethod).
auto sync_iterator_record = TRY(get_iterator(global_object, value, IteratorHint::Sync, sync_method)); auto sync_iterator_record = TRY(get_iterator(global_object, value, IteratorHint::Sync, sync_method));
@ -44,7 +44,7 @@ ThrowCompletionOr<Iterator> get_iterator(GlobalObject& global_object, Value valu
} }
// b. Otherwise, set method to ? GetMethod(obj, @@iterator). // b. Otherwise, set method to ? GetMethod(obj, @@iterator).
else { else {
method = TRY(value.get_method(global_object, *vm.well_known_symbol_iterator())); method = TRY(value.get_method(vm, *vm.well_known_symbol_iterator()));
} }
} }
@ -60,7 +60,7 @@ ThrowCompletionOr<Iterator> get_iterator(GlobalObject& global_object, Value valu
return vm.throw_completion<TypeError>(ErrorType::NotIterable, value.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotIterable, value.to_string_without_side_effects());
// 5. Let nextMethod be ? GetV(iterator, "next"). // 5. Let nextMethod be ? GetV(iterator, "next").
auto next_method = TRY(iterator.get(global_object, vm.names.next)); auto next_method = TRY(iterator.get(vm, vm.names.next));
// 6. Let iteratorRecord be the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }. // 6. Let iteratorRecord be the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
auto iterator_record = Iterator { .iterator = &iterator.as_object(), .next_method = next_method, .done = false }; auto iterator_record = Iterator { .iterator = &iterator.as_object(), .next_method = next_method, .done = false };
@ -142,7 +142,7 @@ static Completion iterator_close_impl(GlobalObject& global_object, Iterator cons
// 3. Let innerResult be Completion(GetMethod(iterator, "return")). // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
auto inner_result = ThrowCompletionOr<Value> { js_undefined() }; auto inner_result = ThrowCompletionOr<Value> { js_undefined() };
auto get_method_result = Value(iterator).get_method(global_object, vm.names.return_); auto get_method_result = Value(iterator).get_method(vm, vm.names.return_);
if (get_method_result.is_error()) if (get_method_result.is_error())
inner_result = get_method_result.release_error(); inner_result = get_method_result.release_error();

View file

@ -45,6 +45,7 @@ void JSONObject::initialize(Realm& realm)
// 25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] ), https://tc39.es/ecma262/#sec-json.stringify // 25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] ), https://tc39.es/ecma262/#sec-json.stringify
ThrowCompletionOr<String> JSONObject::stringify_impl(GlobalObject& global_object, Value value, Value replacer, Value space) ThrowCompletionOr<String> JSONObject::stringify_impl(GlobalObject& global_object, Value value, Value replacer, Value space)
{ {
auto& vm = global_object.vm();
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
StringifyState state; StringifyState state;
@ -53,7 +54,7 @@ ThrowCompletionOr<String> JSONObject::stringify_impl(GlobalObject& global_object
if (replacer.as_object().is_function()) { if (replacer.as_object().is_function()) {
state.replacer_function = &replacer.as_function(); state.replacer_function = &replacer.as_function();
} else { } else {
auto is_array = TRY(replacer.is_array(global_object)); auto is_array = TRY(replacer.is_array(vm));
if (is_array) { if (is_array) {
auto& replacer_object = replacer.as_object(); auto& replacer_object = replacer.as_object();
auto replacer_length = TRY(length_of_array_like(global_object, replacer_object)); auto replacer_length = TRY(length_of_array_like(global_object, replacer_object));
@ -64,11 +65,11 @@ ThrowCompletionOr<String> JSONObject::stringify_impl(GlobalObject& global_object
if (replacer_value.is_string()) { if (replacer_value.is_string()) {
item = replacer_value.as_string().string(); item = replacer_value.as_string().string();
} else if (replacer_value.is_number()) { } else if (replacer_value.is_number()) {
item = MUST(replacer_value.to_string(global_object)); item = MUST(replacer_value.to_string(vm));
} else if (replacer_value.is_object()) { } else if (replacer_value.is_object()) {
auto& value_object = replacer_value.as_object(); auto& value_object = replacer_value.as_object();
if (is<StringObject>(value_object) || is<NumberObject>(value_object)) if (is<StringObject>(value_object) || is<NumberObject>(value_object))
item = TRY(replacer_value.to_string(global_object)); item = TRY(replacer_value.to_string(vm));
} }
if (!item.is_null() && !list.contains_slow(item)) { if (!item.is_null() && !list.contains_slow(item)) {
list.append(item); list.append(item);
@ -82,13 +83,13 @@ ThrowCompletionOr<String> JSONObject::stringify_impl(GlobalObject& global_object
if (space.is_object()) { if (space.is_object()) {
auto& space_object = space.as_object(); auto& space_object = space.as_object();
if (is<NumberObject>(space_object)) if (is<NumberObject>(space_object))
space = TRY(space.to_number(global_object)); space = TRY(space.to_number(vm));
else if (is<StringObject>(space_object)) else if (is<StringObject>(space_object))
space = TRY(space.to_primitive_string(global_object)); space = TRY(space.to_primitive_string(vm));
} }
if (space.is_number()) { if (space.is_number()) {
auto space_mv = MUST(space.to_integer_or_infinity(global_object)); auto space_mv = MUST(space.to_integer_or_infinity(vm));
space_mv = min(10, space_mv); space_mv = min(10, space_mv);
state.gap = space_mv < 1 ? String::empty() : String::repeated(' ', space_mv); state.gap = space_mv < 1 ? String::empty() : String::repeated(' ', space_mv);
} else if (space.is_string()) { } else if (space.is_string()) {
@ -134,7 +135,7 @@ ThrowCompletionOr<String> JSONObject::serialize_json_property(GlobalObject& glob
// 2. If Type(value) is Object or BigInt, then // 2. If Type(value) is Object or BigInt, then
if (value.is_object() || value.is_bigint()) { if (value.is_object() || value.is_bigint()) {
// a. Let toJSON be ? GetV(value, "toJSON"). // a. Let toJSON be ? GetV(value, "toJSON").
auto to_json = TRY(value.get(global_object, vm.names.toJSON)); auto to_json = TRY(value.get(vm, vm.names.toJSON));
// b. If IsCallable(toJSON) is true, then // b. If IsCallable(toJSON) is true, then
if (to_json.is_function()) { if (to_json.is_function()) {
@ -156,12 +157,12 @@ ThrowCompletionOr<String> JSONObject::serialize_json_property(GlobalObject& glob
// a. If value has a [[NumberData]] internal slot, then // a. If value has a [[NumberData]] internal slot, then
if (is<NumberObject>(value_object)) { if (is<NumberObject>(value_object)) {
// i. Set value to ? ToNumber(value). // i. Set value to ? ToNumber(value).
value = TRY(value.to_number(global_object)); value = TRY(value.to_number(vm));
} }
// b. Else if value has a [[StringData]] internal slot, then // b. Else if value has a [[StringData]] internal slot, then
else if (is<StringObject>(value_object)) { else if (is<StringObject>(value_object)) {
// i. Set value to ? ToString(value). // i. Set value to ? ToString(value).
value = TRY(value.to_primitive_string(global_object)); value = TRY(value.to_primitive_string(vm));
} }
// c. Else if value has a [[BooleanData]] internal slot, then // c. Else if value has a [[BooleanData]] internal slot, then
else if (is<BooleanObject>(value_object)) { else if (is<BooleanObject>(value_object)) {
@ -192,7 +193,7 @@ ThrowCompletionOr<String> JSONObject::serialize_json_property(GlobalObject& glob
if (value.is_number()) { if (value.is_number()) {
// a. If value is finite, return ! ToString(value). // a. If value is finite, return ! ToString(value).
if (value.is_finite_number()) if (value.is_finite_number())
return MUST(value.to_string(global_object)); return MUST(value.to_string(vm));
// b. Return "null". // b. Return "null".
return "null"sv; return "null"sv;
@ -205,7 +206,7 @@ ThrowCompletionOr<String> JSONObject::serialize_json_property(GlobalObject& glob
// 11. If Type(value) is Object and IsCallable(value) is false, then // 11. If Type(value) is Object and IsCallable(value) is false, then
if (value.is_object() && !value.is_function()) { if (value.is_object() && !value.is_function()) {
// a. Let isArray be ? IsArray(value). // a. Let isArray be ? IsArray(value).
auto is_array = TRY(value.is_array(global_object)); auto is_array = TRY(value.is_array(vm));
// b. If isArray is true, return ? SerializeJSONArray(state, value). // b. If isArray is true, return ? SerializeJSONArray(state, value).
if (is_array) if (is_array)
@ -396,7 +397,7 @@ JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto string = TRY(vm.argument(0).to_string(global_object)); auto string = TRY(vm.argument(0).to_string(vm));
auto reviver = vm.argument(1); auto reviver = vm.argument(1);
auto json = JsonValue::from_string(string); auto json = JsonValue::from_string(string);
@ -458,7 +459,7 @@ ThrowCompletionOr<Value> JSONObject::internalize_json_property(GlobalObject& glo
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto value = TRY(holder->get(name)); auto value = TRY(holder->get(name));
if (value.is_object()) { if (value.is_object()) {
auto is_array = TRY(value.is_array(global_object)); auto is_array = TRY(value.is_array(vm));
auto& value_object = value.as_object(); auto& value_object = value.as_object();
auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> { auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> {

View file

@ -1,6 +1,6 @@
/* /*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2020, Linus Groh <linusg@serenityos.org> * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org> * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
@ -78,7 +78,7 @@ void MathObject::initialize(Realm& realm)
// 21.3.2.1 Math.abs ( x ), https://tc39.es/ecma262/#sec-math.abs // 21.3.2.1 Math.abs ( x ), https://tc39.es/ecma262/#sec-math.abs
JS_DEFINE_NATIVE_FUNCTION(MathObject::abs) JS_DEFINE_NATIVE_FUNCTION(MathObject::abs)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
if (number.is_negative_zero()) if (number.is_negative_zero())
@ -98,7 +98,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::random)
// 21.3.2.32 Math.sqrt ( x ), https://tc39.es/ecma262/#sec-math.sqrt // 21.3.2.32 Math.sqrt ( x ), https://tc39.es/ecma262/#sec-math.sqrt
JS_DEFINE_NATIVE_FUNCTION(MathObject::sqrt) JS_DEFINE_NATIVE_FUNCTION(MathObject::sqrt)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value(::sqrt(number.as_double())); return Value(::sqrt(number.as_double()));
@ -107,7 +107,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::sqrt)
// 21.3.2.16 Math.floor ( x ), https://tc39.es/ecma262/#sec-math.floor // 21.3.2.16 Math.floor ( x ), https://tc39.es/ecma262/#sec-math.floor
JS_DEFINE_NATIVE_FUNCTION(MathObject::floor) JS_DEFINE_NATIVE_FUNCTION(MathObject::floor)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value(::floor(number.as_double())); return Value(::floor(number.as_double()));
@ -116,7 +116,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::floor)
// 21.3.2.10 Math.ceil ( x ), https://tc39.es/ecma262/#sec-math.ceil // 21.3.2.10 Math.ceil ( x ), https://tc39.es/ecma262/#sec-math.ceil
JS_DEFINE_NATIVE_FUNCTION(MathObject::ceil) JS_DEFINE_NATIVE_FUNCTION(MathObject::ceil)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
auto number_double = number.as_double(); auto number_double = number.as_double();
@ -128,7 +128,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::ceil)
// 21.3.2.28 Math.round ( x ), https://tc39.es/ecma262/#sec-math.round // 21.3.2.28 Math.round ( x ), https://tc39.es/ecma262/#sec-math.round
JS_DEFINE_NATIVE_FUNCTION(MathObject::round) JS_DEFINE_NATIVE_FUNCTION(MathObject::round)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
double integer = ::ceil(value); double integer = ::ceil(value);
if (integer - 0.5 > value) if (integer - 0.5 > value)
integer--; integer--;
@ -140,7 +140,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::max)
{ {
Vector<Value> coerced; Vector<Value> coerced;
for (size_t i = 0; i < vm.argument_count(); ++i) for (size_t i = 0; i < vm.argument_count(); ++i)
coerced.append(TRY(vm.argument(i).to_number(global_object))); coerced.append(TRY(vm.argument(i).to_number(vm)));
auto highest = js_negative_infinity(); auto highest = js_negative_infinity();
for (auto& number : coerced) { for (auto& number : coerced) {
@ -157,7 +157,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::min)
{ {
Vector<Value> coerced; Vector<Value> coerced;
for (size_t i = 0; i < vm.argument_count(); ++i) for (size_t i = 0; i < vm.argument_count(); ++i)
coerced.append(TRY(vm.argument(i).to_number(global_object))); coerced.append(TRY(vm.argument(i).to_number(vm)));
auto lowest = js_infinity(); auto lowest = js_infinity();
for (auto& number : coerced) { for (auto& number : coerced) {
@ -172,7 +172,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::min)
// 21.3.2.35 Math.trunc ( x ), https://tc39.es/ecma262/#sec-math.trunc // 21.3.2.35 Math.trunc ( x ), https://tc39.es/ecma262/#sec-math.trunc
JS_DEFINE_NATIVE_FUNCTION(MathObject::trunc) JS_DEFINE_NATIVE_FUNCTION(MathObject::trunc)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
if (number.as_double() < 0) if (number.as_double() < 0)
@ -184,7 +184,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::trunc)
JS_DEFINE_NATIVE_FUNCTION(MathObject::sin) JS_DEFINE_NATIVE_FUNCTION(MathObject::sin)
{ {
// 1. Let n be ? ToNumber(x). // 1. Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
// 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n. // 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
return number; return number;
@ -201,7 +201,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::sin)
JS_DEFINE_NATIVE_FUNCTION(MathObject::cos) JS_DEFINE_NATIVE_FUNCTION(MathObject::cos)
{ {
// 1. Let n be ? ToNumber(x). // 1. Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
// 2. If n is NaN, n is +∞𝔽, or n is -∞𝔽, return NaN. // 2. If n is NaN, n is +∞𝔽, or n is -∞𝔽, return NaN.
if (number.is_nan() || number.is_infinity()) if (number.is_nan() || number.is_infinity())
@ -219,7 +219,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::cos)
JS_DEFINE_NATIVE_FUNCTION(MathObject::tan) JS_DEFINE_NATIVE_FUNCTION(MathObject::tan)
{ {
// Let n be ? ToNumber(x). // Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
// 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n. // 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
@ -236,15 +236,15 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::tan)
// 21.3.2.26 Math.pow ( base, exponent ), https://tc39.es/ecma262/#sec-math.pow // 21.3.2.26 Math.pow ( base, exponent ), https://tc39.es/ecma262/#sec-math.pow
JS_DEFINE_NATIVE_FUNCTION(MathObject::pow) JS_DEFINE_NATIVE_FUNCTION(MathObject::pow)
{ {
auto base = TRY(vm.argument(0).to_number(global_object)); auto base = TRY(vm.argument(0).to_number(vm));
auto exponent = TRY(vm.argument(1).to_number(global_object)); auto exponent = TRY(vm.argument(1).to_number(vm));
return JS::exp(global_object, base, exponent); return JS::exp(vm, base, exponent);
} }
// 21.3.2.14 Math.exp ( x ), https://tc39.es/ecma262/#sec-math.exp // 21.3.2.14 Math.exp ( x ), https://tc39.es/ecma262/#sec-math.exp
JS_DEFINE_NATIVE_FUNCTION(MathObject::exp) JS_DEFINE_NATIVE_FUNCTION(MathObject::exp)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value(::exp(number.as_double())); return Value(::exp(number.as_double()));
@ -253,7 +253,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::exp)
// 21.3.2.15 Math.expm1 ( x ), https://tc39.es/ecma262/#sec-math.expm1 // 21.3.2.15 Math.expm1 ( x ), https://tc39.es/ecma262/#sec-math.expm1
JS_DEFINE_NATIVE_FUNCTION(MathObject::expm1) JS_DEFINE_NATIVE_FUNCTION(MathObject::expm1)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value(::expm1(number.as_double())); return Value(::expm1(number.as_double()));
@ -262,7 +262,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::expm1)
// 21.3.2.29 Math.sign ( x ), https://tc39.es/ecma262/#sec-math.sign // 21.3.2.29 Math.sign ( x ), https://tc39.es/ecma262/#sec-math.sign
JS_DEFINE_NATIVE_FUNCTION(MathObject::sign) JS_DEFINE_NATIVE_FUNCTION(MathObject::sign)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_positive_zero()) if (number.is_positive_zero())
return Value(0); return Value(0);
if (number.is_negative_zero()) if (number.is_negative_zero())
@ -277,7 +277,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::sign)
// 21.3.2.11 Math.clz32 ( x ), https://tc39.es/ecma262/#sec-math.clz32 // 21.3.2.11 Math.clz32 ( x ), https://tc39.es/ecma262/#sec-math.clz32
JS_DEFINE_NATIVE_FUNCTION(MathObject::clz32) JS_DEFINE_NATIVE_FUNCTION(MathObject::clz32)
{ {
auto number = TRY(vm.argument(0).to_u32(global_object)); auto number = TRY(vm.argument(0).to_u32(vm));
if (number == 0) if (number == 0)
return Value(32); return Value(32);
return Value(count_leading_zeroes(number)); return Value(count_leading_zeroes(number));
@ -286,7 +286,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::clz32)
// 21.3.2.2 Math.acos ( x ), https://tc39.es/ecma262/#sec-math.acos // 21.3.2.2 Math.acos ( x ), https://tc39.es/ecma262/#sec-math.acos
JS_DEFINE_NATIVE_FUNCTION(MathObject::acos) JS_DEFINE_NATIVE_FUNCTION(MathObject::acos)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan() || number.as_double() > 1 || number.as_double() < -1) if (number.is_nan() || number.as_double() > 1 || number.as_double() < -1)
return js_nan(); return js_nan();
if (number.as_double() == 1) if (number.as_double() == 1)
@ -297,7 +297,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::acos)
// 21.3.2.3 Math.acosh ( x ), https://tc39.es/ecma262/#sec-math.acosh // 21.3.2.3 Math.acosh ( x ), https://tc39.es/ecma262/#sec-math.acosh
JS_DEFINE_NATIVE_FUNCTION(MathObject::acosh) JS_DEFINE_NATIVE_FUNCTION(MathObject::acosh)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value < 1) if (value < 1)
return js_nan(); return js_nan();
return Value(::acosh(value)); return Value(::acosh(value));
@ -306,7 +306,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::acosh)
// 21.3.2.4 Math.asin ( x ), https://tc39.es/ecma262/#sec-math.asin // 21.3.2.4 Math.asin ( x ), https://tc39.es/ecma262/#sec-math.asin
JS_DEFINE_NATIVE_FUNCTION(MathObject::asin) JS_DEFINE_NATIVE_FUNCTION(MathObject::asin)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
return number; return number;
return Value(::asin(number.as_double())); return Value(::asin(number.as_double()));
@ -315,13 +315,13 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::asin)
// 21.3.2.5 Math.asinh ( x ), https://tc39.es/ecma262/#sec-math.asinh // 21.3.2.5 Math.asinh ( x ), https://tc39.es/ecma262/#sec-math.asinh
JS_DEFINE_NATIVE_FUNCTION(MathObject::asinh) JS_DEFINE_NATIVE_FUNCTION(MathObject::asinh)
{ {
return Value(::asinh(TRY(vm.argument(0).to_number(global_object)).as_double())); return Value(::asinh(TRY(vm.argument(0).to_number(vm)).as_double()));
} }
// 21.3.2.6 Math.atan ( x ), https://tc39.es/ecma262/#sec-math.atan // 21.3.2.6 Math.atan ( x ), https://tc39.es/ecma262/#sec-math.atan
JS_DEFINE_NATIVE_FUNCTION(MathObject::atan) JS_DEFINE_NATIVE_FUNCTION(MathObject::atan)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
return number; return number;
if (number.is_positive_infinity()) if (number.is_positive_infinity())
@ -334,7 +334,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::atan)
// 21.3.2.7 Math.atanh ( x ), https://tc39.es/ecma262/#sec-math.atanh // 21.3.2.7 Math.atanh ( x ), https://tc39.es/ecma262/#sec-math.atanh
JS_DEFINE_NATIVE_FUNCTION(MathObject::atanh) JS_DEFINE_NATIVE_FUNCTION(MathObject::atanh)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value > 1 || value < -1) if (value > 1 || value < -1)
return js_nan(); return js_nan();
return Value(::atanh(value)); return Value(::atanh(value));
@ -343,7 +343,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::atanh)
// 21.3.2.21 Math.log1p ( x ), https://tc39.es/ecma262/#sec-math.log1p // 21.3.2.21 Math.log1p ( x ), https://tc39.es/ecma262/#sec-math.log1p
JS_DEFINE_NATIVE_FUNCTION(MathObject::log1p) JS_DEFINE_NATIVE_FUNCTION(MathObject::log1p)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value < -1) if (value < -1)
return js_nan(); return js_nan();
return Value(::log1p(value)); return Value(::log1p(value));
@ -352,7 +352,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::log1p)
// 21.3.2.9 Math.cbrt ( x ), https://tc39.es/ecma262/#sec-math.cbrt // 21.3.2.9 Math.cbrt ( x ), https://tc39.es/ecma262/#sec-math.cbrt
JS_DEFINE_NATIVE_FUNCTION(MathObject::cbrt) JS_DEFINE_NATIVE_FUNCTION(MathObject::cbrt)
{ {
return Value(::cbrt(TRY(vm.argument(0).to_number(global_object)).as_double())); return Value(::cbrt(TRY(vm.argument(0).to_number(vm)).as_double()));
} }
// 21.3.2.8 Math.atan2 ( y, x ), https://tc39.es/ecma262/#sec-math.atan2 // 21.3.2.8 Math.atan2 ( y, x ), https://tc39.es/ecma262/#sec-math.atan2
@ -360,8 +360,8 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::atan2)
{ {
auto constexpr three_quarters_pi = M_PI_4 + M_PI_2; auto constexpr three_quarters_pi = M_PI_4 + M_PI_2;
auto y = TRY(vm.argument(0).to_number(global_object)); auto y = TRY(vm.argument(0).to_number(vm));
auto x = TRY(vm.argument(1).to_number(global_object)); auto x = TRY(vm.argument(1).to_number(vm));
if (y.is_nan() || x.is_nan()) if (y.is_nan() || x.is_nan())
return js_nan(); return js_nan();
@ -417,7 +417,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::atan2)
// 21.3.2.17 Math.fround ( x ), https://tc39.es/ecma262/#sec-math.fround // 21.3.2.17 Math.fround ( x ), https://tc39.es/ecma262/#sec-math.fround
JS_DEFINE_NATIVE_FUNCTION(MathObject::fround) JS_DEFINE_NATIVE_FUNCTION(MathObject::fround)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value((float)number.as_double()); return Value((float)number.as_double());
@ -428,7 +428,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::hypot)
{ {
Vector<Value> coerced; Vector<Value> coerced;
for (size_t i = 0; i < vm.argument_count(); ++i) for (size_t i = 0; i < vm.argument_count(); ++i)
coerced.append(TRY(vm.argument(i).to_number(global_object))); coerced.append(TRY(vm.argument(i).to_number(vm)));
for (auto& number : coerced) { for (auto& number : coerced) {
if (number.is_positive_infinity() || number.is_negative_infinity()) if (number.is_positive_infinity() || number.is_negative_infinity())
@ -454,15 +454,15 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::hypot)
// 21.3.2.19 Math.imul ( x, y ), https://tc39.es/ecma262/#sec-math.imul // 21.3.2.19 Math.imul ( x, y ), https://tc39.es/ecma262/#sec-math.imul
JS_DEFINE_NATIVE_FUNCTION(MathObject::imul) JS_DEFINE_NATIVE_FUNCTION(MathObject::imul)
{ {
auto a = TRY(vm.argument(0).to_u32(global_object)); auto a = TRY(vm.argument(0).to_u32(vm));
auto b = TRY(vm.argument(1).to_u32(global_object)); auto b = TRY(vm.argument(1).to_u32(vm));
return Value(static_cast<i32>(a * b)); return Value(static_cast<i32>(a * b));
} }
// 21.3.2.20 Math.log ( x ), https://tc39.es/ecma262/#sec-math.log // 21.3.2.20 Math.log ( x ), https://tc39.es/ecma262/#sec-math.log
JS_DEFINE_NATIVE_FUNCTION(MathObject::log) JS_DEFINE_NATIVE_FUNCTION(MathObject::log)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value < 0) if (value < 0)
return js_nan(); return js_nan();
return Value(::log(value)); return Value(::log(value));
@ -471,7 +471,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::log)
// 21.3.2.23 Math.log2 ( x ), https://tc39.es/ecma262/#sec-math.log2 // 21.3.2.23 Math.log2 ( x ), https://tc39.es/ecma262/#sec-math.log2
JS_DEFINE_NATIVE_FUNCTION(MathObject::log2) JS_DEFINE_NATIVE_FUNCTION(MathObject::log2)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value < 0) if (value < 0)
return js_nan(); return js_nan();
return Value(::log2(value)); return Value(::log2(value));
@ -480,7 +480,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::log2)
// 21.3.2.22 Math.log10 ( x ), https://tc39.es/ecma262/#sec-math.log10 // 21.3.2.22 Math.log10 ( x ), https://tc39.es/ecma262/#sec-math.log10
JS_DEFINE_NATIVE_FUNCTION(MathObject::log10) JS_DEFINE_NATIVE_FUNCTION(MathObject::log10)
{ {
auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); auto value = TRY(vm.argument(0).to_number(vm)).as_double();
if (value < 0) if (value < 0)
return js_nan(); return js_nan();
return Value(::log10(value)); return Value(::log10(value));
@ -489,7 +489,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::log10)
// 21.3.2.31 Math.sinh ( x ), https://tc39.es/ecma262/#sec-math.sinh // 21.3.2.31 Math.sinh ( x ), https://tc39.es/ecma262/#sec-math.sinh
JS_DEFINE_NATIVE_FUNCTION(MathObject::sinh) JS_DEFINE_NATIVE_FUNCTION(MathObject::sinh)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
return Value(::sinh(number.as_double())); return Value(::sinh(number.as_double()));
@ -499,7 +499,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::sinh)
JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh) JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh)
{ {
// 1. Let n be ? ToNumber(x). // 1. Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
// 2. If n is NaN, return NaN. // 2. If n is NaN, return NaN.
if (number.is_nan()) if (number.is_nan())
@ -520,7 +520,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh)
// 21.3.2.34 Math.tanh ( x ), https://tc39.es/ecma262/#sec-math.tanh // 21.3.2.34 Math.tanh ( x ), https://tc39.es/ecma262/#sec-math.tanh
JS_DEFINE_NATIVE_FUNCTION(MathObject::tanh) JS_DEFINE_NATIVE_FUNCTION(MathObject::tanh)
{ {
auto number = TRY(vm.argument(0).to_number(global_object)); auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan()) if (number.is_nan())
return js_nan(); return js_nan();
if (number.is_positive_infinity()) if (number.is_positive_infinity())

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org> * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -63,7 +63,7 @@ static ThrowCompletionOr<Value> get_value_from_constructor_argument(GlobalObject
Value number; Value number;
if (vm.argument_count() > 0) { if (vm.argument_count() > 0) {
auto primitive = TRY(vm.argument(0).to_numeric(global_object)); auto primitive = TRY(vm.argument(0).to_numeric(vm));
if (primitive.is_bigint()) { if (primitive.is_bigint()) {
// FIXME: How should huge values be handled here? // FIXME: How should huge values be handled here?
auto& big_integer = primitive.as_bigint().big_integer(); auto& big_integer = primitive.as_bigint().big_integer();

View file

@ -131,14 +131,14 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_exponential)
auto number_value = TRY(this_number_value(global_object, vm.this_value())); auto number_value = TRY(this_number_value(global_object, vm.this_value()));
// 2. Let f be ? ToIntegerOrInfinity(fractionDigits). // 2. Let f be ? ToIntegerOrInfinity(fractionDigits).
auto fraction_digits = TRY(fraction_digits_value.to_integer_or_infinity(global_object)); auto fraction_digits = TRY(fraction_digits_value.to_integer_or_infinity(vm));
// 3. Assert: If fractionDigits is undefined, then f is 0. // 3. Assert: If fractionDigits is undefined, then f is 0.
VERIFY(!fraction_digits_value.is_undefined() || (fraction_digits == 0)); VERIFY(!fraction_digits_value.is_undefined() || (fraction_digits == 0));
// 4. If x is not finite, return Number::toString(x). // 4. If x is not finite, return Number::toString(x).
if (!number_value.is_finite_number()) if (!number_value.is_finite_number())
return js_string(vm, MUST(number_value.to_string(global_object))); return js_string(vm, MUST(number_value.to_string(vm)));
// 5. If f < 0 or f > 100, throw a RangeError exception. // 5. If f < 0 or f > 100, throw a RangeError exception.
if (fraction_digits < 0 || fraction_digits > 100) if (fraction_digits < 0 || fraction_digits > 100)
@ -251,7 +251,7 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_fixed)
// 2. Let f be ? ToIntegerOrInfinity(fractionDigits). // 2. Let f be ? ToIntegerOrInfinity(fractionDigits).
// 3. Assert: If fractionDigits is undefined, then f is 0. // 3. Assert: If fractionDigits is undefined, then f is 0.
auto fraction_digits = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto fraction_digits = TRY(vm.argument(0).to_integer_or_infinity(vm));
// 4. If f is not finite, throw a RangeError exception. // 4. If f is not finite, throw a RangeError exception.
if (!Value(fraction_digits).is_finite_number()) if (!Value(fraction_digits).is_finite_number())
@ -263,7 +263,7 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_fixed)
// 6. If x is not finite, return Number::toString(x). // 6. If x is not finite, return Number::toString(x).
if (!number_value.is_finite_number()) if (!number_value.is_finite_number())
return js_string(vm, TRY(number_value.to_string(global_object))); return js_string(vm, TRY(number_value.to_string(vm)));
// 7. Set x to (x). // 7. Set x to (x).
auto number = number_value.as_double(); auto number = number_value.as_double();
@ -278,7 +278,7 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_fixed)
// 10. If x ≥ 10^21, then // 10. If x ≥ 10^21, then
if (fabs(number) >= 1e+21) if (fabs(number) >= 1e+21)
return js_string(vm, MUST(number_value.to_string(global_object))); return js_string(vm, MUST(number_value.to_string(vm)));
// 11. Else, // 11. Else,
// a. Let n be an integer for which n / (10^f) - x is as close to zero as possible. If there are two such n, pick the larger n. // a. Let n be an integer for which n / (10^f) - x is as close to zero as possible. If there are two such n, pick the larger n.
@ -345,14 +345,14 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_precision)
// 2. If precision is undefined, return ! ToString(x). // 2. If precision is undefined, return ! ToString(x).
if (precision_value.is_undefined()) if (precision_value.is_undefined())
return js_string(vm, MUST(number_value.to_string(global_object))); return js_string(vm, MUST(number_value.to_string(vm)));
// 3. Let p be ? ToIntegerOrInfinity(precision). // 3. Let p be ? ToIntegerOrInfinity(precision).
auto precision = TRY(precision_value.to_integer_or_infinity(global_object)); auto precision = TRY(precision_value.to_integer_or_infinity(vm));
// 4. If x is not finite, return Number::toString(x). // 4. If x is not finite, return Number::toString(x).
if (!number_value.is_finite_number()) if (!number_value.is_finite_number())
return js_string(vm, MUST(number_value.to_string(global_object))); return js_string(vm, MUST(number_value.to_string(vm)));
// 5. If p < 1 or p > 100, throw a RangeError exception. // 5. If p < 1 or p > 100, throw a RangeError exception.
if ((precision < 1) || (precision > 100)) if ((precision < 1) || (precision > 100))
@ -480,7 +480,7 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_string)
radix_mv = 10; radix_mv = 10;
// 3. Else, let radixMV be ? ToIntegerOrInfinity(radix). // 3. Else, let radixMV be ? ToIntegerOrInfinity(radix).
else else
radix_mv = TRY(vm.argument(0).to_integer_or_infinity(global_object)); radix_mv = TRY(vm.argument(0).to_integer_or_infinity(vm));
// 4. If radixMV < 2 or radixMV > 36, throw a RangeError exception. // 4. If radixMV < 2 or radixMV > 36, throw a RangeError exception.
if (radix_mv < 2 || radix_mv > 36) if (radix_mv < 2 || radix_mv > 36)
@ -488,7 +488,7 @@ JS_DEFINE_NATIVE_FUNCTION(NumberPrototype::to_string)
// 5. If radixMV = 10, return ! ToString(x). // 5. If radixMV = 10, return ! ToString(x).
if (radix_mv == 10) if (radix_mv == 10)
return js_string(vm, MUST(number_value.to_string(global_object))); return js_string(vm, MUST(number_value.to_string(vm)));
// 6. Return the String representation of this Number value using the radix specified by radixMV. Letters a-z are used for digits with values 10 through 35. The precise algorithm is implementation-defined, however the algorithm should be a generalization of that specified in 6.1.6.1.20. // 6. Return the String representation of this Number value using the radix specified by radixMV. Letters a-z are used for digits with values 10 through 35. The precise algorithm is implementation-defined, however the algorithm should be a generalization of that specified in 6.1.6.1.20.
if (number_value.is_positive_infinity()) if (number_value.is_positive_infinity())

View file

@ -262,7 +262,7 @@ ThrowCompletionOr<bool> Object::has_own_property(PropertyKey const& property_key
// 7.3.16 SetIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-setintegritylevel // 7.3.16 SetIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-setintegritylevel
ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level) ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
{ {
auto& global_object = this->global_object(); auto& vm = this->vm();
// 1. Let status be ? O.[[PreventExtensions]](). // 1. Let status be ? O.[[PreventExtensions]]().
auto status = TRY(internal_prevent_extensions()); auto status = TRY(internal_prevent_extensions());
@ -278,7 +278,7 @@ ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
if (level == IntegrityLevel::Sealed) { if (level == IntegrityLevel::Sealed) {
// a. For each element k of keys, do // a. For each element k of keys, do
for (auto& key : keys) { for (auto& key : keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// i. Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }). // i. Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }).
TRY(define_property_or_throw(property_key, { .configurable = false })); TRY(define_property_or_throw(property_key, { .configurable = false }));
@ -290,7 +290,7 @@ ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
// b. For each element k of keys, do // b. For each element k of keys, do
for (auto& key : keys) { for (auto& key : keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// i. Let currentDesc be ? O.[[GetOwnProperty]](k). // i. Let currentDesc be ? O.[[GetOwnProperty]](k).
auto current_descriptor = TRY(internal_get_own_property(property_key)); auto current_descriptor = TRY(internal_get_own_property(property_key));
@ -324,6 +324,8 @@ ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
// 7.3.17 TestIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-testintegritylevel // 7.3.17 TestIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-testintegritylevel
ThrowCompletionOr<bool> Object::test_integrity_level(IntegrityLevel level) const ThrowCompletionOr<bool> Object::test_integrity_level(IntegrityLevel level) const
{ {
auto& vm = this->vm();
// 1. Let extensible be ? IsExtensible(O). // 1. Let extensible be ? IsExtensible(O).
auto extensible = TRY(is_extensible()); auto extensible = TRY(is_extensible());
@ -337,7 +339,7 @@ ThrowCompletionOr<bool> Object::test_integrity_level(IntegrityLevel level) const
// 5. For each element k of keys, do // 5. For each element k of keys, do
for (auto& key : keys) { for (auto& key : keys) {
auto property_key = MUST(PropertyKey::from_value(global_object(), key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// a. Let currentDesc be ? O.[[GetOwnProperty]](k). // a. Let currentDesc be ? O.[[GetOwnProperty]](k).
auto current_descriptor = TRY(internal_get_own_property(property_key)); auto current_descriptor = TRY(internal_get_own_property(property_key));
@ -368,6 +370,7 @@ ThrowCompletionOr<MarkedVector<Value>> Object::enumerable_own_property_names(Pro
// spec text have been replaced with `continue`s in the loop below. // spec text have been replaced with `continue`s in the loop below.
auto& global_object = this->global_object(); auto& global_object = this->global_object();
auto& vm = this->vm();
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 1. Let ownKeys be ? O.[[OwnPropertyKeys]](). // 1. Let ownKeys be ? O.[[OwnPropertyKeys]]().
@ -381,7 +384,7 @@ ThrowCompletionOr<MarkedVector<Value>> Object::enumerable_own_property_names(Pro
// a. If Type(key) is String, then // a. If Type(key) is String, then
if (!key.is_string()) if (!key.is_string())
continue; continue;
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// i. Let desc be ? O.[[GetOwnProperty]](key). // i. Let desc be ? O.[[GetOwnProperty]](key).
auto descriptor = TRY(internal_get_own_property(property_key)); auto descriptor = TRY(internal_get_own_property(property_key));
@ -421,15 +424,15 @@ ThrowCompletionOr<MarkedVector<Value>> Object::enumerable_own_property_names(Pro
} }
// 7.3.26 CopyDataProperties ( target, source, excludedItems ), https://tc39.es/ecma262/#sec-copydataproperties // 7.3.26 CopyDataProperties ( target, source, excludedItems ), https://tc39.es/ecma262/#sec-copydataproperties
ThrowCompletionOr<void> Object::copy_data_properties(Value source, HashTable<PropertyKey> const& seen_names, GlobalObject& global_object) ThrowCompletionOr<void> Object::copy_data_properties(VM& vm, Value source, HashTable<PropertyKey> const& seen_names)
{ {
if (source.is_nullish()) if (source.is_nullish())
return {}; return {};
auto* from_object = MUST(source.to_object(global_object)); auto* from_object = MUST(source.to_object(vm));
for (auto& next_key_value : TRY(from_object->internal_own_property_keys())) { for (auto& next_key_value : TRY(from_object->internal_own_property_keys())) {
auto next_key = MUST(PropertyKey::from_value(global_object, next_key_value)); auto next_key = MUST(PropertyKey::from_value(vm, next_key_value));
if (seen_names.contains(next_key)) if (seen_names.contains(next_key))
continue; continue;
@ -1121,9 +1124,10 @@ void Object::define_native_function(PropertyKey const& property_key, Function<Th
ThrowCompletionOr<Object*> Object::define_properties(Value properties) ThrowCompletionOr<Object*> Object::define_properties(Value properties)
{ {
auto& global_object = this->global_object(); auto& global_object = this->global_object();
auto& vm = this->vm();
// 1. Let props be ? ToObject(Properties). // 1. Let props be ? ToObject(Properties).
auto* props = TRY(properties.to_object(global_object)); auto* props = TRY(properties.to_object(vm));
// 2. Let keys be ? props.[[OwnPropertyKeys]](). // 2. Let keys be ? props.[[OwnPropertyKeys]]().
auto keys = TRY(props->internal_own_property_keys()); auto keys = TRY(props->internal_own_property_keys());
@ -1138,7 +1142,7 @@ ThrowCompletionOr<Object*> Object::define_properties(Value properties)
// 4. For each element nextKey of keys, do // 4. For each element nextKey of keys, do
for (auto& next_key : keys) { for (auto& next_key : keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, next_key)); auto property_key = MUST(PropertyKey::from_value(vm, next_key));
// a. Let propDesc be ? props.[[GetOwnProperty]](nextKey). // a. Let propDesc be ? props.[[GetOwnProperty]](nextKey).
auto property_descriptor = TRY(props->internal_get_own_property(property_key)); auto property_descriptor = TRY(props->internal_get_own_property(property_key));

View file

@ -106,7 +106,7 @@ public:
ThrowCompletionOr<bool> set_integrity_level(IntegrityLevel); ThrowCompletionOr<bool> set_integrity_level(IntegrityLevel);
ThrowCompletionOr<bool> test_integrity_level(IntegrityLevel) const; ThrowCompletionOr<bool> test_integrity_level(IntegrityLevel) const;
ThrowCompletionOr<MarkedVector<Value>> enumerable_own_property_names(PropertyKind kind) const; ThrowCompletionOr<MarkedVector<Value>> enumerable_own_property_names(PropertyKind kind) const;
ThrowCompletionOr<void> copy_data_properties(Value source, HashTable<PropertyKey> const& seen_names, GlobalObject& global_object); ThrowCompletionOr<void> copy_data_properties(VM&, Value source, HashTable<PropertyKey> const& seen_names);
PrivateElement* private_element_find(PrivateName const& name); PrivateElement* private_element_find(PrivateName const& name);
ThrowCompletionOr<void> private_field_add(PrivateName const& name, Value value); ThrowCompletionOr<void> private_field_add(PrivateName const& name, Value value);

View file

@ -75,7 +75,7 @@ ThrowCompletionOr<Object*> ObjectConstructor::construct(FunctionObject& new_targ
auto value = vm.argument(0); auto value = vm.argument(0);
if (value.is_nullish()) if (value.is_nullish())
return Object::create(realm, global_object.object_prototype()); return Object::create(realm, global_object.object_prototype());
return value.to_object(global_object); return value.to_object(vm);
} }
enum class GetOwnPropertyKeysType { enum class GetOwnPropertyKeysType {
@ -89,7 +89,7 @@ static ThrowCompletionOr<MarkedVector<Value>> get_own_property_keys(GlobalObject
auto& vm = global_object.vm(); auto& vm = global_object.vm();
// 1. Let obj be ? ToObject(O). // 1. Let obj be ? ToObject(O).
auto* object = TRY(value.to_object(global_object)); auto* object = TRY(value.to_object(vm));
// 2. Let keys be ? obj.[[OwnPropertyKeys]](). // 2. Let keys be ? obj.[[OwnPropertyKeys]]().
auto keys = TRY(object->internal_own_property_keys()); auto keys = TRY(object->internal_own_property_keys());
@ -132,7 +132,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_symbols)
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_prototype_of) JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_prototype_of)
{ {
// 1. Let obj be ? ToObject(O). // 1. Let obj be ? ToObject(O).
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
// 2. Return ? obj.[[GetPrototypeOf]](). // 2. Return ? obj.[[GetPrototypeOf]]().
return TRY(object->internal_get_prototype_of()); return TRY(object->internal_get_prototype_of());
@ -235,7 +235,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::from_entries)
auto key = TRY(iterator_value.as_object().get(0)); auto key = TRY(iterator_value.as_object().get(0));
auto value = TRY(iterator_value.as_object().get(1)); auto value = TRY(iterator_value.as_object().get(1));
auto property_key = TRY(key.to_property_key(global_object)); auto property_key = TRY(key.to_property_key(vm));
MUST(object->create_data_property_or_throw(property_key, value)); MUST(object->create_data_property_or_throw(property_key, value));
return {}; return {};
@ -259,8 +259,8 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::seal)
// 20.1.2.8 Object.getOwnPropertyDescriptor ( O, P ), https://tc39.es/ecma262/#sec-object.getownpropertydescriptor // 20.1.2.8 Object.getOwnPropertyDescriptor ( O, P ), https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptor) JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptor)
{ {
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
auto key = TRY(vm.argument(1).to_property_key(global_object)); auto key = TRY(vm.argument(1).to_property_key(vm));
auto descriptor = TRY(object->internal_get_own_property(key)); auto descriptor = TRY(object->internal_get_own_property(key));
return from_property_descriptor(global_object, descriptor); return from_property_descriptor(global_object, descriptor);
} }
@ -271,7 +271,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptors)
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
// 1. Let obj be ? ToObject(O). // 1. Let obj be ? ToObject(O).
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
// 2. Let ownKeys be ? obj.[[OwnPropertyKeys]](). // 2. Let ownKeys be ? obj.[[OwnPropertyKeys]]().
auto own_keys = TRY(object->internal_own_property_keys()); auto own_keys = TRY(object->internal_own_property_keys());
@ -281,7 +281,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::get_own_property_descriptors)
// 4. For each element key of ownKeys, do // 4. For each element key of ownKeys, do
for (auto& key : own_keys) { for (auto& key : own_keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// a. Let desc be ? obj.[[GetOwnProperty]](key). // a. Let desc be ? obj.[[GetOwnProperty]](key).
auto desc = TRY(object->internal_get_own_property(property_key)); auto desc = TRY(object->internal_get_own_property(property_key));
@ -303,7 +303,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::define_property)
{ {
if (!vm.argument(0).is_object()) if (!vm.argument(0).is_object())
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, vm.argument(0).to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, vm.argument(0).to_string_without_side_effects());
auto key = TRY(vm.argument(1).to_property_key(global_object)); auto key = TRY(vm.argument(1).to_property_key(vm));
auto descriptor = TRY(to_property_descriptor(global_object, vm.argument(2))); auto descriptor = TRY(to_property_descriptor(global_object, vm.argument(2)));
TRY(vm.argument(0).as_object().define_property_or_throw(key, descriptor)); TRY(vm.argument(0).as_object().define_property_or_throw(key, descriptor));
return vm.argument(0); return vm.argument(0);
@ -334,7 +334,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::keys)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::Key)); auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::Key));
return Array::create_from(realm, name_list); return Array::create_from(realm, name_list);
} }
@ -344,7 +344,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::values)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::Value)); auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::Value));
return Array::create_from(realm, name_list); return Array::create_from(realm, name_list);
} }
@ -354,7 +354,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::entries)
{ {
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::KeyAndValue)); auto name_list = TRY(object->enumerable_own_property_names(PropertyKind::KeyAndValue));
return Array::create_from(realm, name_list); return Array::create_from(realm, name_list);
} }
@ -388,10 +388,10 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::create)
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::has_own) JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::has_own)
{ {
// 1. Let obj be ? ToObject(O). // 1. Let obj be ? ToObject(O).
auto* object = TRY(vm.argument(0).to_object(global_object)); auto* object = TRY(vm.argument(0).to_object(vm));
// 2. Let key be ? ToPropertyKey(P). // 2. Let key be ? ToPropertyKey(P).
auto key = TRY(vm.argument(1).to_property_key(global_object)); auto key = TRY(vm.argument(1).to_property_key(vm));
// 3. Return ? HasOwnProperty(obj, key). // 3. Return ? HasOwnProperty(obj, key).
return Value(TRY(object->has_own_property(key))); return Value(TRY(object->has_own_property(key)));
@ -401,7 +401,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::has_own)
JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::assign) JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::assign)
{ {
// 1. Let to be ? ToObject(target). // 1. Let to be ? ToObject(target).
auto* to = TRY(vm.argument(0).to_object(global_object)); auto* to = TRY(vm.argument(0).to_object(vm));
// 2. If only one argument was passed, return to. // 2. If only one argument was passed, return to.
if (vm.argument_count() == 1) if (vm.argument_count() == 1)
@ -416,14 +416,14 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::assign)
continue; continue;
// i. Let from be ! ToObject(nextSource). // i. Let from be ! ToObject(nextSource).
auto* from = MUST(next_source.to_object(global_object)); auto* from = MUST(next_source.to_object(vm));
// ii. Let keys be ? from.[[OwnPropertyKeys]](). // ii. Let keys be ? from.[[OwnPropertyKeys]]().
auto keys = TRY(from->internal_own_property_keys()); auto keys = TRY(from->internal_own_property_keys());
// iii. For each element nextKey of keys, do // iii. For each element nextKey of keys, do
for (auto& next_key : keys) { for (auto& next_key : keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, next_key)); auto property_key = MUST(PropertyKey::from_value(vm, next_key));
// 1. Let desc be ? from.[[GetOwnProperty]](nextKey). // 1. Let desc be ? from.[[GetOwnProperty]](nextKey).
auto desc = TRY(from->internal_get_own_property(property_key)); auto desc = TRY(from->internal_get_own_property(property_key));

View file

@ -58,8 +58,8 @@ ThrowCompletionOr<bool> ObjectPrototype::internal_set_prototype_of(Object* proto
// 20.1.3.2 Object.prototype.hasOwnProperty ( V ), https://tc39.es/ecma262/#sec-object.prototype.hasownproperty // 20.1.3.2 Object.prototype.hasOwnProperty ( V ), https://tc39.es/ecma262/#sec-object.prototype.hasownproperty
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::has_own_property) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::has_own_property)
{ {
auto property_key = TRY(vm.argument(0).to_property_key(global_object)); auto property_key = TRY(vm.argument(0).to_property_key(vm));
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
return Value(TRY(this_object->has_own_property(property_key))); return Value(TRY(this_object->has_own_property(property_key)));
} }
@ -77,10 +77,10 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_string)
return js_string(vm, "[object Null]"); return js_string(vm, "[object Null]");
// 3. Let O be ! ToObject(this value). // 3. Let O be ! ToObject(this value).
auto* object = MUST(this_value.to_object(global_object)); auto* object = MUST(this_value.to_object(vm));
// 4. Let isArray be ? IsArray(O). // 4. Let isArray be ? IsArray(O).
auto is_array = TRY(Value(object).is_array(global_object)); auto is_array = TRY(Value(object).is_array(vm));
String builtin_tag; String builtin_tag;
@ -135,22 +135,22 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_string)
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_locale_string) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_locale_string)
{ {
auto this_value = vm.this_value(); auto this_value = vm.this_value();
return this_value.invoke(global_object, vm.names.toString); return this_value.invoke(vm, vm.names.toString);
} }
// 20.1.3.7 Object.prototype.valueOf ( ), https://tc39.es/ecma262/#sec-object.prototype.valueof // 20.1.3.7 Object.prototype.valueOf ( ), https://tc39.es/ecma262/#sec-object.prototype.valueof
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::value_of) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::value_of)
{ {
return TRY(vm.this_value().to_object(global_object)); return TRY(vm.this_value().to_object(vm));
} }
// 20.1.3.4 Object.prototype.propertyIsEnumerable ( V ), https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable // 20.1.3.4 Object.prototype.propertyIsEnumerable ( V ), https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::property_is_enumerable) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::property_is_enumerable)
{ {
// 1. Let P be ? ToPropertyKey(V). // 1. Let P be ? ToPropertyKey(V).
auto property_key = TRY(vm.argument(0).to_property_key(global_object)); auto property_key = TRY(vm.argument(0).to_property_key(vm));
// 2. Let O be ? ToObject(this value). // 2. Let O be ? ToObject(this value).
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
// 3. Let desc be ? O.[[GetOwnProperty]](P). // 3. Let desc be ? O.[[GetOwnProperty]](P).
auto property_descriptor = TRY(this_object->internal_get_own_property(property_key)); auto property_descriptor = TRY(this_object->internal_get_own_property(property_key));
// 4. If desc is undefined, return false. // 4. If desc is undefined, return false.
@ -167,7 +167,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::is_prototype_of)
if (!object_argument.is_object()) if (!object_argument.is_object())
return Value(false); return Value(false);
auto* object = &object_argument.as_object(); auto* object = &object_argument.as_object();
auto* this_object = TRY(vm.this_value().to_object(global_object)); auto* this_object = TRY(vm.this_value().to_object(vm));
for (;;) { for (;;) {
object = TRY(object->internal_get_prototype_of()); object = TRY(object->internal_get_prototype_of());
@ -181,7 +181,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::is_prototype_of)
// B.2.2.2 Object.prototype.__defineGetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineGetter__ // B.2.2.2 Object.prototype.__defineGetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineGetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_getter) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_getter)
{ {
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
auto getter = vm.argument(1); auto getter = vm.argument(1);
if (!getter.is_function()) if (!getter.is_function())
@ -189,7 +189,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_getter)
auto descriptor = PropertyDescriptor { .get = &getter.as_function(), .enumerable = true, .configurable = true }; auto descriptor = PropertyDescriptor { .get = &getter.as_function(), .enumerable = true, .configurable = true };
auto key = TRY(vm.argument(0).to_property_key(global_object)); auto key = TRY(vm.argument(0).to_property_key(vm));
TRY(object->define_property_or_throw(key, descriptor)); TRY(object->define_property_or_throw(key, descriptor));
@ -199,7 +199,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_getter)
// B.2.2.3 Object.prototype.__defineSetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineSetter__ // B.2.2.3 Object.prototype.__defineSetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineSetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_setter) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_setter)
{ {
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
auto setter = vm.argument(1); auto setter = vm.argument(1);
if (!setter.is_function()) if (!setter.is_function())
@ -207,7 +207,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_setter)
auto descriptor = PropertyDescriptor { .set = &setter.as_function(), .enumerable = true, .configurable = true }; auto descriptor = PropertyDescriptor { .set = &setter.as_function(), .enumerable = true, .configurable = true };
auto key = TRY(vm.argument(0).to_property_key(global_object)); auto key = TRY(vm.argument(0).to_property_key(vm));
TRY(object->define_property_or_throw(key, descriptor)); TRY(object->define_property_or_throw(key, descriptor));
@ -217,9 +217,9 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_setter)
// B.2.2.4 Object.prototype.__lookupGetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupGetter__ // B.2.2.4 Object.prototype.__lookupGetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupGetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_getter) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_getter)
{ {
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
auto key = TRY(vm.argument(0).to_property_key(global_object)); auto key = TRY(vm.argument(0).to_property_key(vm));
while (object) { while (object) {
auto desc = TRY(object->internal_get_own_property(key)); auto desc = TRY(object->internal_get_own_property(key));
@ -237,9 +237,9 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_getter)
// B.2.2.5 Object.prototype.__lookupSetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupSetter__ // B.2.2.5 Object.prototype.__lookupSetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupSetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_setter) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_setter)
{ {
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
auto key = TRY(vm.argument(0).to_property_key(global_object)); auto key = TRY(vm.argument(0).to_property_key(vm));
while (object) { while (object) {
auto desc = TRY(object->internal_get_own_property(key)); auto desc = TRY(object->internal_get_own_property(key));
@ -257,7 +257,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_setter)
// B.2.2.1.1 get Object.prototype.__proto__, https://tc39.es/ecma262/#sec-get-object.prototype.__proto__ // B.2.2.1.1 get Object.prototype.__proto__, https://tc39.es/ecma262/#sec-get-object.prototype.__proto__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::proto_getter) JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::proto_getter)
{ {
auto* object = TRY(vm.this_value().to_object(global_object)); auto* object = TRY(vm.this_value().to_object(vm));
return TRY(object->internal_get_prototype_of()); return TRY(object->internal_get_prototype_of());
} }

View file

@ -27,7 +27,7 @@ static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object,
auto& vm = global_object.vm(); auto& vm = global_object.vm();
// 1. Let promiseResolve be ? Get(promiseConstructor, "resolve"). // 1. Let promiseResolve be ? Get(promiseConstructor, "resolve").
auto promise_resolve = TRY(constructor.get(global_object, vm.names.resolve)); auto promise_resolve = TRY(constructor.get(vm, vm.names.resolve));
// 2. If IsCallable(promiseResolve) is false, throw a TypeError exception. // 2. If IsCallable(promiseResolve) is false, throw a TypeError exception.
if (!promise_resolve.is_function()) if (!promise_resolve.is_function())
@ -146,7 +146,7 @@ static ThrowCompletionOr<Value> perform_promise_all(GlobalObject& global_object,
on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable); on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
// s. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »). // s. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »).
return next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject); return next_promise.invoke(vm, vm.names.then, on_fulfilled, result_capability.reject);
}); });
} }
@ -190,7 +190,7 @@ static ThrowCompletionOr<Value> perform_promise_all_settled(GlobalObject& global
on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable); on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
// ab. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »). // ab. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
return next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected); return next_promise.invoke(vm, vm.names.then, on_fulfilled, on_rejected);
}); });
} }
@ -226,7 +226,7 @@ static ThrowCompletionOr<Value> perform_promise_any(GlobalObject& global_object,
on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable); on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
// s. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »). // s. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »).
return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected); return next_promise.invoke(vm, vm.names.then, result_capability.resolve, on_rejected);
}); });
} }
@ -243,7 +243,7 @@ static ThrowCompletionOr<Value> perform_promise_race(GlobalObject& global_object
}, },
[&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) { [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
// i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »). // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject); return next_promise.invoke(vm, vm.names.then, result_capability.resolve, result_capability.reject);
}); });
} }
@ -321,7 +321,7 @@ ThrowCompletionOr<Object*> PromiseConstructor::construct(FunctionObject& new_tar
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all) JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
{ {
// 1. Let C be the this value. // 1. Let C be the this value.
auto* constructor = TRY(vm.this_value().to_object(global_object)); auto* constructor = TRY(vm.this_value().to_object(vm));
// 2. Let promiseCapability be ? NewPromiseCapability(C). // 2. Let promiseCapability be ? NewPromiseCapability(C).
auto promise_capability = TRY(new_promise_capability(global_object, constructor)); auto promise_capability = TRY(new_promise_capability(global_object, constructor));
@ -355,7 +355,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled) JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
{ {
// 1. Let C be the this value. // 1. Let C be the this value.
auto* constructor = TRY(vm.this_value().to_object(global_object)); auto* constructor = TRY(vm.this_value().to_object(vm));
// 2. Let promiseCapability be ? NewPromiseCapability(C). // 2. Let promiseCapability be ? NewPromiseCapability(C).
auto promise_capability = TRY(new_promise_capability(global_object, constructor)); auto promise_capability = TRY(new_promise_capability(global_object, constructor));
@ -389,7 +389,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any) JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
{ {
// 1. Let C be the this value. // 1. Let C be the this value.
auto* constructor = TRY(vm.this_value().to_object(global_object)); auto* constructor = TRY(vm.this_value().to_object(vm));
// 2. Let promiseCapability be ? NewPromiseCapability(C). // 2. Let promiseCapability be ? NewPromiseCapability(C).
auto promise_capability = TRY(new_promise_capability(global_object, constructor)); auto promise_capability = TRY(new_promise_capability(global_object, constructor));
@ -423,7 +423,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race) JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race)
{ {
// 1. Let C be the this value. // 1. Let C be the this value.
auto* constructor = TRY(vm.this_value().to_object(global_object)); auto* constructor = TRY(vm.this_value().to_object(vm));
// 2. Let promiseCapability be ? NewPromiseCapability(C). // 2. Let promiseCapability be ? NewPromiseCapability(C).
auto promise_capability = TRY(new_promise_capability(global_object, constructor)); auto promise_capability = TRY(new_promise_capability(global_object, constructor));
@ -459,7 +459,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject)
auto reason = vm.argument(0); auto reason = vm.argument(0);
// 1. Let C be the this value. // 1. Let C be the this value.
auto* constructor = TRY(vm.this_value().to_object(global_object)); auto* constructor = TRY(vm.this_value().to_object(vm));
// 2. Let promiseCapability be ? NewPromiseCapability(C). // 2. Let promiseCapability be ? NewPromiseCapability(C).
auto promise_capability = TRY(new_promise_capability(global_object, constructor)); auto promise_capability = TRY(new_promise_capability(global_object, constructor));

View file

@ -64,7 +64,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::catch_)
auto this_value = vm.this_value(); auto this_value = vm.this_value();
// 2. Return ? Invoke(promise, "then", « undefined, onRejected »). // 2. Return ? Invoke(promise, "then", « undefined, onRejected »).
return TRY(this_value.invoke(global_object, vm.names.then, js_undefined(), on_rejected)); return TRY(this_value.invoke(vm, vm.names.then, js_undefined(), on_rejected));
} }
// 27.2.5.3 Promise.prototype.finally ( onFinally ), https://tc39.es/ecma262/#sec-promise.prototype.finally // 27.2.5.3 Promise.prototype.finally ( onFinally ), https://tc39.es/ecma262/#sec-promise.prototype.finally
@ -123,7 +123,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally)
auto* value_thunk = NativeFunction::create(realm, move(return_value), 0, ""); auto* value_thunk = NativeFunction::create(realm, move(return_value), 0, "");
// v. Return ? Invoke(promise, "then", « valueThunk »). // v. Return ? Invoke(promise, "then", « valueThunk »).
return TRY(Value(promise).invoke(global_object, vm.names.then, value_thunk)); return TRY(Value(promise).invoke(vm, vm.names.then, value_thunk));
}; };
// b. Let thenFinally be CreateBuiltinFunction(thenFinallyClosure, 1, "", « »). // b. Let thenFinally be CreateBuiltinFunction(thenFinallyClosure, 1, "", « »).
@ -152,7 +152,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally)
auto* thrower = NativeFunction::create(realm, move(throw_reason), 0, ""); auto* thrower = NativeFunction::create(realm, move(throw_reason), 0, "");
// v. Return ? Invoke(promise, "then", « thrower »). // v. Return ? Invoke(promise, "then", « thrower »).
return TRY(Value(promise).invoke(global_object, vm.names.then, thrower)); return TRY(Value(promise).invoke(vm, vm.names.then, thrower));
}; };
// d. Let catchFinally be CreateBuiltinFunction(catchFinallyClosure, 1, "", « »). // d. Let catchFinally be CreateBuiltinFunction(catchFinallyClosure, 1, "", « »).
@ -160,7 +160,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally)
} }
// 7. Return ? Invoke(promise, "then", « thenFinally, catchFinally »). // 7. Return ? Invoke(promise, "then", « thenFinally, catchFinally »).
return TRY(promise.invoke(global_object, vm.names.then, then_finally, catch_finally)); return TRY(promise.invoke(vm, vm.names.then, then_finally, catch_finally));
} }
} }

View file

@ -26,7 +26,7 @@ public:
No, No,
}; };
static ThrowCompletionOr<PropertyKey> from_value(GlobalObject& global_object, Value value) static ThrowCompletionOr<PropertyKey> from_value(VM& vm, Value value)
{ {
if (value.is_empty()) if (value.is_empty())
return PropertyKey {}; return PropertyKey {};
@ -34,7 +34,7 @@ public:
return PropertyKey { value.as_symbol() }; return PropertyKey { value.as_symbol() };
if (value.is_integral_number() && value.as_double() >= 0 && value.as_double() < NumericLimits<u32>::max()) if (value.is_integral_number() && value.as_double() >= 0 && value.as_double() < NumericLimits<u32>::max())
return static_cast<u32>(value.as_double()); return static_cast<u32>(value.as_double());
return TRY(value.to_string(global_object)); return TRY(value.to_string(vm));
} }
PropertyKey() = default; PropertyKey() = default;

View file

@ -37,9 +37,7 @@ public:
// Use typed_this_object() when the spec coerces |this| value to an object. // Use typed_this_object() when the spec coerces |this| value to an object.
static ThrowCompletionOr<ObjectType*> typed_this_object(VM& vm) static ThrowCompletionOr<ObjectType*> typed_this_object(VM& vm)
{ {
auto& realm = *vm.current_realm(); auto* this_object = TRY(vm.this_value().to_object(vm));
auto& global_object = realm.global_object();
auto* this_object = TRY(vm.this_value().to_object(global_object));
if (!is<ObjectType>(this_object)) if (!is<ObjectType>(this_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, PrototypeType::display_name()); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, PrototypeType::display_name());
return static_cast<ObjectType*>(this_object); return static_cast<ObjectType*>(this_object);

View file

@ -56,7 +56,7 @@ ThrowCompletionOr<Object*> ProxyObject::internal_get_prototype_of() const
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "getPrototypeOf"). // 5. Let trap be ? GetMethod(handler, "getPrototypeOf").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.getPrototypeOf)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.getPrototypeOf));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -105,7 +105,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_set_prototype_of(Object* prototype
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "setPrototypeOf"). // 5. Let trap be ? GetMethod(handler, "setPrototypeOf").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.setPrototypeOf)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.setPrototypeOf));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -154,7 +154,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_is_extensible() const
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "isExtensible"). // 5. Let trap be ? GetMethod(handler, "isExtensible").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.isExtensible)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.isExtensible));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -192,7 +192,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_prevent_extensions()
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "preventExtensions"). // 5. Let trap be ? GetMethod(handler, "preventExtensions").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.preventExtensions)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.preventExtensions));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -235,7 +235,7 @@ ThrowCompletionOr<Optional<PropertyDescriptor>> ProxyObject::internal_get_own_pr
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor"). // 5. Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.getOwnPropertyDescriptor)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.getOwnPropertyDescriptor));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -327,7 +327,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_define_own_property(PropertyKey co
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "defineProperty"). // 5. Let trap be ? GetMethod(handler, "defineProperty").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.defineProperty)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.defineProperty));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -410,7 +410,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_has_property(PropertyKey const& pr
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "has"). // 5. Let trap be ? GetMethod(handler, "has").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.has)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.has));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -482,7 +482,7 @@ ThrowCompletionOr<Value> ProxyObject::internal_get(PropertyKey const& property_k
return vm.throw_completion<InternalError>(ErrorType::CallStackSizeExceeded); return vm.throw_completion<InternalError>(ErrorType::CallStackSizeExceeded);
// 5. Let trap be ? GetMethod(handler, "get"). // 5. Let trap be ? GetMethod(handler, "get").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.get)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.get));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -536,7 +536,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_set(PropertyKey const& property_ke
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "set"). // 5. Let trap be ? GetMethod(handler, "set").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.set)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.set));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -592,7 +592,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_delete(PropertyKey const& property
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "deleteProperty"). // 5. Let trap be ? GetMethod(handler, "deleteProperty").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.deleteProperty)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.deleteProperty));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -645,7 +645,7 @@ ThrowCompletionOr<MarkedVector<Value>> ProxyObject::internal_own_property_keys()
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "ownKeys"). // 5. Let trap be ? GetMethod(handler, "ownKeys").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.ownKeys)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.ownKeys));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -662,7 +662,7 @@ ThrowCompletionOr<MarkedVector<Value>> ProxyObject::internal_own_property_keys()
auto& vm = global_object.vm(); auto& vm = global_object.vm();
if (!value.is_string() && !value.is_symbol()) if (!value.is_string() && !value.is_symbol())
return vm.throw_completion<TypeError>(ErrorType::ProxyOwnPropertyKeysNotStringOrSymbol); return vm.throw_completion<TypeError>(ErrorType::ProxyOwnPropertyKeysNotStringOrSymbol);
auto property_key = MUST(value.to_property_key(global_object)); auto property_key = MUST(value.to_property_key(vm));
unique_keys.set(property_key, AK::HashSetExistingEntryBehavior::Keep); unique_keys.set(property_key, AK::HashSetExistingEntryBehavior::Keep);
return {}; return {};
})); }));
@ -688,7 +688,7 @@ ThrowCompletionOr<MarkedVector<Value>> ProxyObject::internal_own_property_keys()
// 16. For each element key of targetKeys, do // 16. For each element key of targetKeys, do
for (auto& key : target_keys) { for (auto& key : target_keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// a. Let desc be ? target.[[GetOwnProperty]](key). // a. Let desc be ? target.[[GetOwnProperty]](key).
auto descriptor = TRY(m_target.internal_get_own_property(property_key)); auto descriptor = TRY(m_target.internal_get_own_property(property_key));
@ -775,7 +775,7 @@ ThrowCompletionOr<Value> ProxyObject::internal_call(Value this_argument, MarkedV
// 4. Let target be O.[[ProxyTarget]]. // 4. Let target be O.[[ProxyTarget]].
// 5. Let trap be ? GetMethod(handler, "apply"). // 5. Let trap be ? GetMethod(handler, "apply").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.apply)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.apply));
// 6. If trap is undefined, then // 6. If trap is undefined, then
if (!trap) { if (!trap) {
@ -824,7 +824,7 @@ ThrowCompletionOr<Object*> ProxyObject::internal_construct(MarkedVector<Value> a
// 5. Assert: IsConstructor(target) is true. // 5. Assert: IsConstructor(target) is true.
// 6. Let trap be ? GetMethod(handler, "construct"). // 6. Let trap be ? GetMethod(handler, "construct").
auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.construct)); auto trap = TRY(Value(&m_handler).get_method(vm, vm.names.construct));
// 7. If trap is undefined, then // 7. If trap is undefined, then
if (!trap) { if (!trap) {

View file

@ -41,7 +41,7 @@ ThrowCompletionOr<void> Reference::put_value(GlobalObject& global_object, Value
// 5. If IsPropertyReference(V) is true, then // 5. If IsPropertyReference(V) is true, then
if (is_property_reference()) { if (is_property_reference()) {
// a. Let baseObj be ? ToObject(V.[[Base]]). // a. Let baseObj be ? ToObject(V.[[Base]]).
auto* base_obj = TRY(m_base_value.to_object(global_object)); auto* base_obj = TRY(m_base_value.to_object(vm));
// b. If IsPrivateReference(V) is true, then // b. If IsPrivateReference(V) is true, then
if (is_private_reference()) { if (is_private_reference()) {
@ -86,6 +86,8 @@ Completion Reference::throw_reference_error(GlobalObject& global_object) const
// 6.2.4.5 GetValue ( V ), https://tc39.es/ecma262/#sec-getvalue // 6.2.4.5 GetValue ( V ), https://tc39.es/ecma262/#sec-getvalue
ThrowCompletionOr<Value> Reference::get_value(GlobalObject& global_object) const ThrowCompletionOr<Value> Reference::get_value(GlobalObject& global_object) const
{ {
auto& vm = global_object.vm();
// 1. ReturnIfAbrupt(V). // 1. ReturnIfAbrupt(V).
// 2. If V is not a Reference Record, return V. // 2. If V is not a Reference Record, return V.
@ -105,7 +107,7 @@ ThrowCompletionOr<Value> Reference::get_value(GlobalObject& global_object) const
// as things currently stand this does the "wrong thing" but // as things currently stand this does the "wrong thing" but
// the error is unobservable // the error is unobservable
auto* base_obj = TRY(m_base_value.to_object(global_object)); auto* base_obj = TRY(m_base_value.to_object(vm));
// i. Return ? PrivateGet(baseObj, V.[[ReferencedName]]). // i. Return ? PrivateGet(baseObj, V.[[ReferencedName]]).
return base_obj->private_get(m_private_name); return base_obj->private_get(m_private_name);
@ -123,7 +125,7 @@ ThrowCompletionOr<Value> Reference::get_value(GlobalObject& global_object) const
else if (m_base_value.is_boolean()) else if (m_base_value.is_boolean())
base_obj = global_object.boolean_prototype(); base_obj = global_object.boolean_prototype();
else else
base_obj = TRY(m_base_value.to_object(global_object)); base_obj = TRY(m_base_value.to_object(vm));
// c. Return ? baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V)). // c. Return ? baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V)).
return base_obj->internal_get(m_name, get_this_value()); return base_obj->internal_get(m_name, get_this_value());
@ -173,7 +175,7 @@ ThrowCompletionOr<bool> Reference::delete_(GlobalObject& global_object)
return vm.throw_completion<ReferenceError>(ErrorType::UnsupportedDeleteSuperProperty); return vm.throw_completion<ReferenceError>(ErrorType::UnsupportedDeleteSuperProperty);
// c. Let baseObj be ! ToObject(ref.[[Base]]). // c. Let baseObj be ! ToObject(ref.[[Base]]).
auto* base_obj = MUST(m_base_value.to_object(global_object)); auto* base_obj = MUST(m_base_value.to_object(vm));
// d. Let deleteStatus be ? baseObj.[[Delete]](ref.[[ReferencedName]]). // d. Let deleteStatus be ? baseObj.[[Delete]](ref.[[ReferencedName]]).
bool delete_status = TRY(base_obj->internal_delete(m_name)); bool delete_status = TRY(base_obj->internal_delete(m_name));

View file

@ -99,7 +99,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::define_property)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. Let desc be ? ToPropertyDescriptor(attributes). // 3. Let desc be ? ToPropertyDescriptor(attributes).
auto descriptor = TRY(to_property_descriptor(global_object, attributes)); auto descriptor = TRY(to_property_descriptor(global_object, attributes));
@ -119,7 +119,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::delete_property)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. Return ? target.[[Delete]](key). // 3. Return ? target.[[Delete]](key).
return Value(TRY(target.as_object().internal_delete(key))); return Value(TRY(target.as_object().internal_delete(key)));
@ -137,7 +137,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::get)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. If receiver is not present, then // 3. If receiver is not present, then
if (vm.argument_count() < 3) { if (vm.argument_count() < 3) {
@ -160,7 +160,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::get_own_property_descriptor)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. Let desc be ? target.[[GetOwnProperty]](key). // 3. Let desc be ? target.[[GetOwnProperty]](key).
auto descriptor = TRY(target.as_object().internal_get_own_property(key)); auto descriptor = TRY(target.as_object().internal_get_own_property(key));
@ -193,7 +193,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::has)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. Return ? target.[[HasProperty]](key). // 3. Return ? target.[[HasProperty]](key).
return Value(TRY(target.as_object().internal_has_property(key))); return Value(TRY(target.as_object().internal_has_property(key)));
@ -256,7 +256,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::set)
return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects()); return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
// 2. Let key be ? ToPropertyKey(propertyKey). // 2. Let key be ? ToPropertyKey(propertyKey).
auto key = TRY(property_key.to_property_key(global_object)); auto key = TRY(property_key.to_property_key(vm));
// 3. If receiver is not present, then // 3. If receiver is not present, then
if (vm.argument_count() < 4) { if (vm.argument_count() < 4) {

View file

@ -33,12 +33,11 @@ void RegExpConstructor::initialize(Realm& realm)
ThrowCompletionOr<Value> RegExpConstructor::call() ThrowCompletionOr<Value> RegExpConstructor::call()
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto& global_object = this->global_object();
auto pattern = vm.argument(0); auto pattern = vm.argument(0);
auto flags = vm.argument(1); auto flags = vm.argument(1);
bool pattern_is_regexp = TRY(pattern.is_regexp(global_object)); bool pattern_is_regexp = TRY(pattern.is_regexp(vm));
if (pattern_is_regexp && flags.is_undefined()) { if (pattern_is_regexp && flags.is_undefined()) {
auto pattern_constructor = TRY(pattern.as_object().get(vm.names.constructor)); auto pattern_constructor = TRY(pattern.as_object().get(vm.names.constructor));
@ -58,7 +57,7 @@ ThrowCompletionOr<Object*> RegExpConstructor::construct(FunctionObject&)
auto pattern = vm.argument(0); auto pattern = vm.argument(0);
auto flags = vm.argument(1); auto flags = vm.argument(1);
bool pattern_is_regexp = TRY(pattern.is_regexp(global_object)); bool pattern_is_regexp = TRY(pattern.is_regexp(vm));
Value pattern_value; Value pattern_value;
Value flags_value; Value flags_value;

View file

@ -162,7 +162,7 @@ ThrowCompletionOr<RegExpObject*> RegExpObject::regexp_initialize(GlobalObject& g
if (flags.is_undefined()) { if (flags.is_undefined()) {
f = String::empty(); f = String::empty();
} else { } else {
f = TRY(flags.to_string(global_object)); f = TRY(flags.to_string(vm));
} }
String original_pattern; String original_pattern;
@ -172,7 +172,7 @@ ThrowCompletionOr<RegExpObject*> RegExpObject::regexp_initialize(GlobalObject& g
original_pattern = String::empty(); original_pattern = String::empty();
parsed_pattern = String::empty(); parsed_pattern = String::empty();
} else { } else {
original_pattern = TRY(pattern.to_string(global_object)); original_pattern = TRY(pattern.to_string(vm));
bool unicode = f.find('u').has_value(); bool unicode = f.find('u').has_value();
bool unicode_sets = f.find('v').has_value(); bool unicode_sets = f.find('v').has_value();
parsed_pattern = TRY(parse_regex_pattern(vm, original_pattern, unicode, unicode_sets)); parsed_pattern = TRY(parse_regex_pattern(vm, original_pattern, unicode, unicode_sets));

View file

@ -58,7 +58,7 @@ static ThrowCompletionOr<void> increment_last_index(GlobalObject& global_object,
// Let thisIndex be (? ToLength(? Get(rx, "lastIndex"))). // Let thisIndex be (? ToLength(? Get(rx, "lastIndex"))).
auto last_index_value = TRY(regexp_object.get(vm.names.lastIndex)); auto last_index_value = TRY(regexp_object.get(vm.names.lastIndex));
auto last_index = TRY(last_index_value.to_length(global_object)); auto last_index = TRY(last_index_value.to_length(vm));
// Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode). // Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
last_index = advance_string_index(string, last_index, unicode); last_index = advance_string_index(string, last_index, unicode);
@ -174,7 +174,7 @@ static ThrowCompletionOr<Value> regexp_builtin_exec(GlobalObject& global_object,
// 1. Let length be the length of S. // 1. Let length be the length of S.
// 2. Let lastIndex be (? ToLength(? Get(R, "lastIndex"))). // 2. Let lastIndex be (? ToLength(? Get(R, "lastIndex"))).
auto last_index_value = TRY(regexp_object.get(vm.names.lastIndex)); auto last_index_value = TRY(regexp_object.get(vm.names.lastIndex));
auto last_index = TRY(last_index_value.to_length(global_object)); auto last_index = TRY(last_index_value.to_length(vm));
auto& regex = regexp_object.regex(); auto& regex = regexp_object.regex();
@ -445,7 +445,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::exec)
auto* regexp_object = TRY(typed_this_object(vm)); auto* regexp_object = TRY(typed_this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Return ? RegExpBuiltinExec(R, S). // 4. Return ? RegExpBuiltinExec(R, S).
return TRY(regexp_builtin_exec(global_object, *regexp_object, move(string))); return TRY(regexp_builtin_exec(global_object, *regexp_object, move(string)));
@ -500,7 +500,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Let global be ToBoolean(? Get(rx, "global")). // 4. Let global be ToBoolean(? Get(rx, "global")).
bool global = TRY(regexp_object->get(vm.names.global)).to_boolean(); bool global = TRY(regexp_object->get(vm.names.global)).to_boolean();
@ -533,10 +533,10 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match)
// g. Repeat, // g. Repeat,
while (true) { while (true) {
// i. Let result be ? RegExpExec(rx, S). // i. Let result be ? RegExpExec(rx, S).
auto result = TRY(regexp_exec(global_object, *regexp_object, string)); auto result_value = TRY(regexp_exec(global_object, *regexp_object, string));
// ii. If result is null, then // ii. If result is null, then
if (result.is_null()) { if (result_value.is_null()) {
// 1. If n = 0, return null. // 1. If n = 0, return null.
if (n == 0) if (n == 0)
return js_null(); return js_null();
@ -545,11 +545,14 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match)
return array; return array;
} }
VERIFY(result_value.is_object());
auto& result = result_value.as_object();
// iii. Else, // iii. Else,
// 1. Let matchStr be ? ToString(? Get(result, "0")). // 1. Let matchStr be ? ToString(? Get(result, "0")).
auto match_value = TRY(result.get(global_object, 0)); auto match_value = TRY(result.get(0));
auto match_str = TRY(match_value.to_string(global_object)); auto match_str = TRY(match_value.to_string(vm));
// 2. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), matchStr). // 2. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), matchStr).
MUST(array->create_data_property_or_throw(n, js_string(vm, match_str))); MUST(array->create_data_property_or_throw(n, js_string(vm, match_str)));
@ -576,14 +579,14 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match_all)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Let C be ? SpeciesConstructor(R, %RegExp%). // 4. Let C be ? SpeciesConstructor(R, %RegExp%).
auto* constructor = TRY(species_constructor(global_object, *regexp_object, *global_object.regexp_constructor())); auto* constructor = TRY(species_constructor(global_object, *regexp_object, *global_object.regexp_constructor()));
// 5. Let flags be ? ToString(? Get(R, "flags")). // 5. Let flags be ? ToString(? Get(R, "flags")).
auto flags_value = TRY(regexp_object->get(vm.names.flags)); auto flags_value = TRY(regexp_object->get(vm.names.flags));
auto flags = TRY(flags_value.to_string(global_object)); auto flags = TRY(flags_value.to_string(vm));
// Steps 9-12 are performed early so that flags can be moved. // Steps 9-12 are performed early so that flags can be moved.
@ -600,7 +603,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match_all)
// 7. Let lastIndex be ? ToLength(? Get(R, "lastIndex")). // 7. Let lastIndex be ? ToLength(? Get(R, "lastIndex")).
auto last_index_value = TRY(regexp_object->get(vm.names.lastIndex)); auto last_index_value = TRY(regexp_object->get(vm.names.lastIndex));
auto last_index = TRY(last_index_value.to_length(global_object)); auto last_index = TRY(last_index_value.to_length(vm));
// 8. Perform ? Set(matcher, "lastIndex", lastIndex, true). // 8. Perform ? Set(matcher, "lastIndex", lastIndex, true).
TRY(matcher->set(vm.names.lastIndex, Value(last_index), Object::ShouldThrowExceptions::Yes)); TRY(matcher->set(vm.names.lastIndex, Value(last_index), Object::ShouldThrowExceptions::Yes));
@ -621,7 +624,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(string_value.to_utf16_string(global_object)); auto string = TRY(string_value.to_utf16_string(vm));
// 4. Let lengthS be the number of code unit elements in S. // 4. Let lengthS be the number of code unit elements in S.
// 5. Let functionalReplace be IsCallable(replaceValue). // 5. Let functionalReplace be IsCallable(replaceValue).
@ -629,7 +632,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
// 6. If functionalReplace is false, then // 6. If functionalReplace is false, then
if (!replace_value.is_function()) { if (!replace_value.is_function()) {
// a. Set replaceValue to ? ToString(replaceValue). // a. Set replaceValue to ? ToString(replaceValue).
auto replace_string = TRY(replace_value.to_string(global_object)); auto replace_string = TRY(replace_value.to_string(vm));
replace_value = js_string(vm, move(replace_string)); replace_value = js_string(vm, move(replace_string));
} }
@ -651,7 +654,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
} }
// 9. Let results be a new empty List. // 9. Let results be a new empty List.
MarkedVector<Value> results(vm.heap()); MarkedVector<Object*> results(vm.heap());
// 10. Let done be false. // 10. Let done be false.
// 11. Repeat, while done is false, // 11. Repeat, while done is false,
@ -666,7 +669,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
// c. Else, // c. Else,
// i. Append result to the end of results. // i. Append result to the end of results.
results.append(result); results.append(&result.as_object());
// ii. If global is false, set done to true. // ii. If global is false, set done to true.
if (!global) if (!global)
@ -675,8 +678,8 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
// iii. Else, // iii. Else,
// 1. Let matchStr be ? ToString(? Get(result, "0")). // 1. Let matchStr be ? ToString(? Get(result, "0")).
auto match_value = TRY(result.get(global_object, 0)); auto match_value = TRY(result.get(vm, 0));
auto match_str = TRY(match_value.to_string(global_object)); auto match_str = TRY(match_value.to_string(vm));
// 2. If matchStr is the empty String, then // 2. If matchStr is the empty String, then
if (match_str.is_empty()) { if (match_str.is_empty()) {
@ -694,21 +697,21 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
// 14. For each element result of results, do // 14. For each element result of results, do
for (auto& result : results) { for (auto& result : results) {
// a. Let resultLength be ? LengthOfArrayLike(result). // a. Let resultLength be ? LengthOfArrayLike(result).
size_t result_length = TRY(length_of_array_like(global_object, result.as_object())); size_t result_length = TRY(length_of_array_like(global_object, *result));
// b. Let nCaptures be max(resultLength - 1, 0). // b. Let nCaptures be max(resultLength - 1, 0).
size_t n_captures = result_length == 0 ? 0 : result_length - 1; size_t n_captures = result_length == 0 ? 0 : result_length - 1;
// c. Let matched be ? ToString(? Get(result, "0")). // c. Let matched be ? ToString(? Get(result, "0")).
auto matched_value = TRY(result.get(global_object, 0)); auto matched_value = TRY(result->get(0));
auto matched = TRY(matched_value.to_utf16_string(global_object)); auto matched = TRY(matched_value.to_utf16_string(vm));
// d. Let matchLength be the length of matched. // d. Let matchLength be the length of matched.
auto matched_length = matched.length_in_code_units(); auto matched_length = matched.length_in_code_units();
// e. Let position be ? ToIntegerOrInfinity(? Get(result, "index")). // e. Let position be ? ToIntegerOrInfinity(? Get(result, "index")).
auto position_value = TRY(result.get(global_object, vm.names.index)); auto position_value = TRY(result->get(vm.names.index));
double position = TRY(position_value.to_integer_or_infinity(global_object)); double position = TRY(position_value.to_integer_or_infinity(vm));
// f. Set position to the result of clamping position between 0 and lengthS. // f. Set position to the result of clamping position between 0 and lengthS.
position = clamp(position, static_cast<double>(0), static_cast<double>(string.length_in_code_units())); position = clamp(position, static_cast<double>(0), static_cast<double>(string.length_in_code_units()));
@ -721,12 +724,12 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
// i. Repeat, while n ≤ nCaptures, // i. Repeat, while n ≤ nCaptures,
for (size_t n = 1; n <= n_captures; ++n) { for (size_t n = 1; n <= n_captures; ++n) {
// i. Let capN be ? Get(result, ! ToString(𝔽(n))). // i. Let capN be ? Get(result, ! ToString(𝔽(n))).
auto capture = TRY(result.get(global_object, n)); auto capture = TRY(result->get(n));
// ii. If capN is not undefined, then // ii. If capN is not undefined, then
if (!capture.is_undefined()) { if (!capture.is_undefined()) {
// 1. Set capN to ? ToString(capN). // 1. Set capN to ? ToString(capN).
capture = js_string(vm, TRY(capture.to_string(global_object))); capture = js_string(vm, TRY(capture.to_string(vm)));
} }
// iii. Append capN as the last element of captures. // iii. Append capN as the last element of captures.
@ -737,7 +740,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
} }
// j. Let namedCaptures be ? Get(result, "groups"). // j. Let namedCaptures be ? Get(result, "groups").
auto named_captures = TRY(result.get(global_object, vm.names.groups)); auto named_captures = TRY(result->get(vm.names.groups));
String replacement; String replacement;
@ -764,14 +767,14 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace)
auto replace_result = TRY(call(global_object, replace_value.as_function(), js_undefined(), move(replacer_args))); auto replace_result = TRY(call(global_object, replace_value.as_function(), js_undefined(), move(replacer_args)));
// vi. Let replacement be ? ToString(replValue). // vi. Let replacement be ? ToString(replValue).
replacement = TRY(replace_result.to_string(global_object)); replacement = TRY(replace_result.to_string(vm));
} }
// l. Else, // l. Else,
else { else {
/// i. If namedCaptures is not undefined, then /// i. If namedCaptures is not undefined, then
if (!named_captures.is_undefined()) { if (!named_captures.is_undefined()) {
// 1. Set namedCaptures to ? ToObject(namedCaptures). // 1. Set namedCaptures to ? ToObject(namedCaptures).
named_captures = TRY(named_captures.to_object(global_object)); named_captures = TRY(named_captures.to_object(vm));
} }
// ii. Let replacement be ? GetSubstitution(matched, S, position, captures, namedCaptures, replaceValue). // ii. Let replacement be ? GetSubstitution(matched, S, position, captures, namedCaptures, replaceValue).
@ -811,7 +814,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_search)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Let previousLastIndex be ? Get(rx, "lastIndex"). // 4. Let previousLastIndex be ? Get(rx, "lastIndex").
auto previous_last_index = TRY(regexp_object->get(vm.names.lastIndex)); auto previous_last_index = TRY(regexp_object->get(vm.names.lastIndex));
@ -839,7 +842,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_search)
return Value(-1); return Value(-1);
// 10. Return ? Get(result, "index"). // 10. Return ? Get(result, "index").
return TRY(result.get(global_object, vm.names.index)); return TRY(result.get(vm, vm.names.index));
} }
// 22.2.5.13 get RegExp.prototype.source, https://tc39.es/ecma262/#sec-get-regexp.prototype.source // 22.2.5.13 get RegExp.prototype.source, https://tc39.es/ecma262/#sec-get-regexp.prototype.source
@ -876,14 +879,14 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_split)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let S be ? ToString(string). // 3. Let S be ? ToString(string).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Let C be ? SpeciesConstructor(rx, %RegExp%). // 4. Let C be ? SpeciesConstructor(rx, %RegExp%).
auto* constructor = TRY(species_constructor(global_object, *regexp_object, *global_object.regexp_constructor())); auto* constructor = TRY(species_constructor(global_object, *regexp_object, *global_object.regexp_constructor()));
// 5. Let flags be ? ToString(? Get(rx, "flags")). // 5. Let flags be ? ToString(? Get(rx, "flags")).
auto flags_value = TRY(regexp_object->get(vm.names.flags)); auto flags_value = TRY(regexp_object->get(vm.names.flags));
auto flags = TRY(flags_value.to_string(global_object)); auto flags = TRY(flags_value.to_string(vm));
// 6. If flags contains "u", let unicodeMatching be true. // 6. If flags contains "u", let unicodeMatching be true.
// 7. Else, let unicodeMatching be false. // 7. Else, let unicodeMatching be false.
@ -905,7 +908,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_split)
// 13. If limit is undefined, let lim be 2^32 - 1; else let lim be (? ToUint32(limit)). // 13. If limit is undefined, let lim be 2^32 - 1; else let lim be (? ToUint32(limit)).
auto limit = NumericLimits<u32>::max(); auto limit = NumericLimits<u32>::max();
if (!vm.argument(1).is_undefined()) if (!vm.argument(1).is_undefined())
limit = TRY(vm.argument(1).to_u32(global_object)); limit = TRY(vm.argument(1).to_u32(vm));
// 14. If lim is 0, return A. // 14. If lim is 0, return A.
if (limit == 0) if (limit == 0)
@ -952,7 +955,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_split)
// i. Let e be (? ToLength(? Get(splitter, "lastIndex"))). // i. Let e be (? ToLength(? Get(splitter, "lastIndex"))).
auto last_index_value = TRY(splitter->get(vm.names.lastIndex)); auto last_index_value = TRY(splitter->get(vm.names.lastIndex));
auto last_index = TRY(last_index_value.to_length(global_object)); auto last_index = TRY(last_index_value.to_length(vm));
// ii. Set e to min(e, size). // ii. Set e to min(e, size).
last_index = min(last_index, string.length_in_code_units()); last_index = min(last_index, string.length_in_code_units());
@ -993,7 +996,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_split)
for (size_t i = 1; i <= number_of_captures; ++i) { for (size_t i = 1; i <= number_of_captures; ++i) {
// a. Let nextCapture be ? Get(z, ! ToString(𝔽(i))). // a. Let nextCapture be ? Get(z, ! ToString(𝔽(i))).
auto next_capture = TRY(result.get(global_object, i)); auto next_capture = TRY(result.get(vm, i));
// b. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), nextCapture). // b. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), nextCapture).
MUST(array->create_data_property_or_throw(array_length, next_capture)); MUST(array->create_data_property_or_throw(array_length, next_capture));
@ -1030,7 +1033,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::test)
auto* regexp_object = TRY(this_object(vm)); auto* regexp_object = TRY(this_object(vm));
// 3. Let string be ? ToString(S). // 3. Let string be ? ToString(S).
auto string = TRY(vm.argument(0).to_utf16_string(global_object)); auto string = TRY(vm.argument(0).to_utf16_string(vm));
// 4. Let match be ? RegExpExec(R, string). // 4. Let match be ? RegExpExec(R, string).
auto match = TRY(regexp_exec(global_object, *regexp_object, move(string))); auto match = TRY(regexp_exec(global_object, *regexp_object, move(string)));
@ -1048,11 +1051,11 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::to_string)
// 3. Let pattern be ? ToString(? Get(R, "source")). // 3. Let pattern be ? ToString(? Get(R, "source")).
auto source_attr = TRY(regexp_object->get(vm.names.source)); auto source_attr = TRY(regexp_object->get(vm.names.source));
auto pattern = TRY(source_attr.to_string(global_object)); auto pattern = TRY(source_attr.to_string(vm));
// 4. Let flags be ? ToString(? Get(R, "flags")). // 4. Let flags be ? ToString(? Get(R, "flags")).
auto flags_attr = TRY(regexp_object->get(vm.names.flags)); auto flags_attr = TRY(regexp_object->get(vm.names.flags));
auto flags = TRY(flags_attr.to_string(global_object)); auto flags = TRY(flags_attr.to_string(vm));
// 5. Let result be the string-concatenation of "/", pattern, "/", and flags. // 5. Let result be the string-concatenation of "/", pattern, "/", and flags.
// 6. Return result. // 6. Return result.

View file

@ -49,12 +49,12 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpStringIteratorPrototype::next)
return create_iterator_result_object(global_object, match, false); return create_iterator_result_object(global_object, match, false);
} }
auto* match_object = TRY(match.to_object(global_object)); auto* match_object = TRY(match.to_object(vm));
auto match_string_value = TRY(match_object->get(0)); auto match_string_value = TRY(match_object->get(0));
auto match_string = TRY(match_string_value.to_string(global_object)); auto match_string = TRY(match_string_value.to_string(vm));
if (match_string.is_empty()) { if (match_string.is_empty()) {
auto last_index_value = TRY(iterator->regexp_object().get(vm.names.lastIndex)); auto last_index_value = TRY(iterator->regexp_object().get(vm.names.lastIndex));
auto last_index = TRY(last_index_value.to_length(global_object)); auto last_index = TRY(last_index_value.to_length(vm));
last_index = advance_string_index(iterator->string().view(), last_index, iterator->unicode()); last_index = advance_string_index(iterator->string().view(), last_index, iterator->unicode());

View file

@ -66,7 +66,7 @@ ThrowCompletionOr<void> copy_name_and_length(GlobalObject& global_object, Functi
// iii. Else, // iii. Else,
else { else {
// 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen). // 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
auto target_length_as_int = MUST(target_length.to_integer_or_infinity(global_object)); auto target_length_as_int = MUST(target_length.to_integer_or_infinity(vm));
// 2. Assert: targetLenAsInt is finite. // 2. Assert: targetLenAsInt is finite.
VERIFY(!isinf(target_length_as_int)); VERIFY(!isinf(target_length_as_int));

View file

@ -63,7 +63,7 @@ JS_DEFINE_NATIVE_FUNCTION(ShadowRealmPrototype::import_value)
auto* object = TRY(typed_this_object(vm)); auto* object = TRY(typed_this_object(vm));
// 3. Let specifierString be ? ToString(specifier). // 3. Let specifierString be ? ToString(specifier).
auto specifier_string = TRY(specifier.to_string(global_object)); auto specifier_string = TRY(specifier.to_string(vm));
// 4. If Type(exportName) is not String, throw a TypeError exception. // 4. If Type(exportName) is not String, throw a TypeError exception.
if (!export_name.is_string()) if (!export_name.is_string())

View file

@ -41,11 +41,12 @@ void StringConstructor::initialize(Realm& realm)
// 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value // 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value
ThrowCompletionOr<Value> StringConstructor::call() ThrowCompletionOr<Value> StringConstructor::call()
{ {
if (!vm().argument_count()) auto& vm = this->vm();
if (!vm.argument_count())
return js_string(heap(), ""); return js_string(heap(), "");
if (vm().argument(0).is_symbol()) if (vm.argument(0).is_symbol())
return js_string(heap(), vm().argument(0).as_symbol().to_string()); return js_string(vm, vm.argument(0).as_symbol().to_string());
return TRY(vm().argument(0).to_primitive_string(global_object())); return TRY(vm.argument(0).to_primitive_string(vm));
} }
// 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value // 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value
@ -59,7 +60,7 @@ ThrowCompletionOr<Object*> StringConstructor::construct(FunctionObject& new_targ
if (!vm.argument_count()) if (!vm.argument_count())
primitive_string = js_string(vm, ""); primitive_string = js_string(vm, "");
else else
primitive_string = TRY(vm.argument(0).to_primitive_string(global_object)); primitive_string = TRY(vm.argument(0).to_primitive_string(vm));
auto* prototype = TRY(get_prototype_from_constructor(global_object, new_target, &GlobalObject::string_prototype)); auto* prototype = TRY(get_prototype_from_constructor(global_object, new_target, &GlobalObject::string_prototype));
return StringObject::create(realm, *primitive_string, *prototype); return StringObject::create(realm, *primitive_string, *prototype);
} }
@ -67,9 +68,9 @@ ThrowCompletionOr<Object*> StringConstructor::construct(FunctionObject& new_targ
// 22.1.2.4 String.raw ( template, ...substitutions ), https://tc39.es/ecma262/#sec-string.raw // 22.1.2.4 String.raw ( template, ...substitutions ), https://tc39.es/ecma262/#sec-string.raw
JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw) JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw)
{ {
auto* cooked = TRY(vm.argument(0).to_object(global_object)); auto* cooked = TRY(vm.argument(0).to_object(vm));
auto raw_value = TRY(cooked->get(vm.names.raw)); auto raw_value = TRY(cooked->get(vm.names.raw));
auto* raw = TRY(raw_value.to_object(global_object)); auto* raw = TRY(raw_value.to_object(vm));
auto literal_segments = TRY(length_of_array_like(global_object, *raw)); auto literal_segments = TRY(length_of_array_like(global_object, *raw));
if (literal_segments == 0) if (literal_segments == 0)
@ -81,7 +82,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw)
for (size_t i = 0; i < literal_segments; ++i) { for (size_t i = 0; i < literal_segments; ++i) {
auto next_key = String::number(i); auto next_key = String::number(i);
auto next_segment_value = TRY(raw->get(next_key)); auto next_segment_value = TRY(raw->get(next_key));
auto next_segment = TRY(next_segment_value.to_string(global_object)); auto next_segment = TRY(next_segment_value.to_string(vm));
builder.append(next_segment); builder.append(next_segment);
@ -90,7 +91,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw)
if (i < number_of_substituions) { if (i < number_of_substituions) {
auto next = vm.argument(i + 1); auto next = vm.argument(i + 1);
auto next_sub = TRY(next.to_string(global_object)); auto next_sub = TRY(next.to_string(vm));
builder.append(next_sub); builder.append(next_sub);
} }
} }
@ -104,7 +105,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringConstructor::from_char_code)
string.ensure_capacity(vm.argument_count()); string.ensure_capacity(vm.argument_count());
for (size_t i = 0; i < vm.argument_count(); ++i) for (size_t i = 0; i < vm.argument_count(); ++i)
string.append(TRY(vm.argument(i).to_u16(global_object))); string.append(TRY(vm.argument(i).to_u16(vm)));
return js_string(vm, Utf16String(move(string))); return js_string(vm, Utf16String(move(string)));
} }
@ -116,10 +117,10 @@ JS_DEFINE_NATIVE_FUNCTION(StringConstructor::from_code_point)
string.ensure_capacity(vm.argument_count()); // This will be an under-estimate if any code point is > 0xffff. string.ensure_capacity(vm.argument_count()); // This will be an under-estimate if any code point is > 0xffff.
for (size_t i = 0; i < vm.argument_count(); ++i) { for (size_t i = 0; i < vm.argument_count(); ++i) {
auto next_code_point = TRY(vm.argument(i).to_number(global_object)); auto next_code_point = TRY(vm.argument(i).to_number(vm));
if (!next_code_point.is_integral_number()) if (!next_code_point.is_integral_number())
return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, next_code_point.to_string_without_side_effects()); return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, next_code_point.to_string_without_side_effects());
auto code_point = TRY(next_code_point.to_i32(global_object)); auto code_point = TRY(next_code_point.to_i32(vm));
if (code_point < 0 || code_point > 0x10FFFF) if (code_point < 0 || code_point > 0x10FFFF)
return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, next_code_point.to_string_without_side_effects()); return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, next_code_point.to_string_without_side_effects());

View file

@ -35,13 +35,13 @@ namespace JS {
static ThrowCompletionOr<String> ak_string_from(VM& vm, GlobalObject& global_object) static ThrowCompletionOr<String> ak_string_from(VM& vm, GlobalObject& global_object)
{ {
auto this_value = TRY(require_object_coercible(global_object, vm.this_value())); auto this_value = TRY(require_object_coercible(global_object, vm.this_value()));
return TRY(this_value.to_string(global_object)); return TRY(this_value.to_string(vm));
} }
static ThrowCompletionOr<Utf16String> utf16_string_from(VM& vm, GlobalObject& global_object) static ThrowCompletionOr<Utf16String> utf16_string_from(VM& vm, GlobalObject& global_object)
{ {
auto this_value = TRY(require_object_coercible(global_object, vm.this_value())); auto this_value = TRY(require_object_coercible(global_object, vm.this_value()));
return TRY(this_value.to_utf16_string(global_object)); return TRY(this_value.to_utf16_string(vm));
} }
// 22.1.3.21.1 SplitMatch ( S, q, R ), https://tc39.es/ecma262/#sec-splitmatch // 22.1.3.21.1 SplitMatch ( S, q, R ), https://tc39.es/ecma262/#sec-splitmatch
@ -179,7 +179,7 @@ static ThrowCompletionOr<PrimitiveString*> this_string_value(GlobalObject& globa
JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at) JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at)
{ {
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto position = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (position < 0 || position >= string.length_in_code_units()) if (position < 0 || position >= string.length_in_code_units())
return js_string(vm, String::empty()); return js_string(vm, String::empty());
@ -190,7 +190,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at)
JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at) JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at)
{ {
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto position = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (position < 0 || position >= string.length_in_code_units()) if (position < 0 || position >= string.length_in_code_units())
return js_nan(); return js_nan();
@ -201,7 +201,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at)
JS_DEFINE_NATIVE_FUNCTION(StringPrototype::code_point_at) JS_DEFINE_NATIVE_FUNCTION(StringPrototype::code_point_at)
{ {
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto position = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (position < 0 || position >= string.length_in_code_units()) if (position < 0 || position >= string.length_in_code_units())
return js_undefined(); return js_undefined();
@ -214,7 +214,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::repeat)
{ {
auto string = TRY(ak_string_from(vm, global_object)); auto string = TRY(ak_string_from(vm, global_object));
auto n = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto n = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (n < 0) if (n < 0)
return vm.throw_completion<RangeError>(ErrorType::StringRepeatCountMustBe, "positive"); return vm.throw_completion<RangeError>(ErrorType::StringRepeatCountMustBe, "positive");
@ -242,17 +242,17 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::starts_with)
auto search_string_value = vm.argument(0); auto search_string_value = vm.argument(0);
bool search_is_regexp = TRY(search_string_value.is_regexp(global_object)); bool search_is_regexp = TRY(search_string_value.is_regexp(vm));
if (search_is_regexp) if (search_is_regexp)
return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression"); return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression");
auto search_string = TRY(search_string_value.to_utf16_string(global_object)); auto search_string = TRY(search_string_value.to_utf16_string(vm));
auto string_length = string.length_in_code_units(); auto string_length = string.length_in_code_units();
auto search_length = search_string.length_in_code_units(); auto search_length = search_string.length_in_code_units();
size_t start = 0; size_t start = 0;
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
auto position = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(1).to_integer_or_infinity(vm));
start = clamp(position, static_cast<double>(0), static_cast<double>(string_length)); start = clamp(position, static_cast<double>(0), static_cast<double>(string_length));
} }
@ -274,17 +274,17 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::ends_with)
auto search_string_value = vm.argument(0); auto search_string_value = vm.argument(0);
bool search_is_regexp = TRY(search_string_value.is_regexp(global_object)); bool search_is_regexp = TRY(search_string_value.is_regexp(vm));
if (search_is_regexp) if (search_is_regexp)
return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression"); return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression");
auto search_string = TRY(search_string_value.to_utf16_string(global_object)); auto search_string = TRY(search_string_value.to_utf16_string(vm));
auto string_length = string.length_in_code_units(); auto string_length = string.length_in_code_units();
auto search_length = search_string.length_in_code_units(); auto search_length = search_string.length_in_code_units();
size_t end = string_length; size_t end = string_length;
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
auto position = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(1).to_integer_or_infinity(vm));
end = clamp(position, static_cast<double>(0), static_cast<double>(string_length)); end = clamp(position, static_cast<double>(0), static_cast<double>(string_length));
} }
@ -304,13 +304,13 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::index_of)
{ {
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto search_string = TRY(vm.argument(0).to_utf16_string(global_object)); auto search_string = TRY(vm.argument(0).to_utf16_string(vm));
auto utf16_string_view = string.view(); auto utf16_string_view = string.view();
auto utf16_search_view = search_string.view(); auto utf16_search_view = search_string.view();
size_t start = 0; size_t start = 0;
if (vm.argument_count() > 1) { if (vm.argument_count() > 1) {
auto position = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(1).to_integer_or_infinity(vm));
start = clamp(position, static_cast<double>(0), static_cast<double>(utf16_string_view.length_in_code_units())); start = clamp(position, static_cast<double>(0), static_cast<double>(utf16_string_view.length_in_code_units()));
} }
@ -446,13 +446,13 @@ static ThrowCompletionOr<Value> pad_string(GlobalObject& global_object, Utf16Str
auto& vm = global_object.vm(); auto& vm = global_object.vm();
auto string_length = string.length_in_code_units(); auto string_length = string.length_in_code_units();
auto max_length = TRY(vm.argument(0).to_length(global_object)); auto max_length = TRY(vm.argument(0).to_length(vm));
if (max_length <= string_length) if (max_length <= string_length)
return js_string(vm, move(string)); return js_string(vm, move(string));
Utf16String fill_string(Vector<u16, 1> { 0x20 }); Utf16String fill_string(Vector<u16, 1> { 0x20 });
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
fill_string = TRY(vm.argument(1).to_utf16_string(global_object)); fill_string = TRY(vm.argument(1).to_utf16_string(vm));
if (fill_string.is_empty()) if (fill_string.is_empty())
return js_string(vm, move(string)); return js_string(vm, move(string));
} }
@ -489,11 +489,13 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::pad_end)
ThrowCompletionOr<String> trim_string(GlobalObject& global_object, Value input_value, TrimMode where) ThrowCompletionOr<String> trim_string(GlobalObject& global_object, Value input_value, TrimMode where)
{ {
auto& vm = global_object.vm();
// 1. Let str be ? RequireObjectCoercible(string). // 1. Let str be ? RequireObjectCoercible(string).
auto input_string = TRY(require_object_coercible(global_object, input_value)); auto input_string = TRY(require_object_coercible(global_object, input_value));
// 2. Let S be ? ToString(str). // 2. Let S be ? ToString(str).
auto string = TRY(input_string.to_string(global_object)); auto string = TRY(input_string.to_string(vm));
// 3. If where is start, let T be the String value that is a copy of S with leading white space removed. // 3. If where is start, let T be the String value that is a copy of S with leading white space removed.
// 4. Else if where is end, let T be the String value that is a copy of S with trailing white space removed. // 4. Else if where is end, let T be the String value that is a copy of S with trailing white space removed.
@ -531,7 +533,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::concat)
auto object = TRY(require_object_coercible(global_object, vm.this_value())); auto object = TRY(require_object_coercible(global_object, vm.this_value()));
// 2. Let S be ? ToString(O). // 2. Let S be ? ToString(O).
auto* string = TRY(object.to_primitive_string(global_object)); auto* string = TRY(object.to_primitive_string(vm));
// 3. Let R be S. // 3. Let R be S.
auto* result = string; auto* result = string;
@ -539,7 +541,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::concat)
// 4. For each element next of args, do // 4. For each element next of args, do
for (size_t i = 0; i < vm.argument_count(); ++i) { for (size_t i = 0; i < vm.argument_count(); ++i) {
// a. Let nextString be ? ToString(next). // a. Let nextString be ? ToString(next).
auto* next_string = TRY(vm.argument(i).to_primitive_string(global_object)); auto* next_string = TRY(vm.argument(i).to_primitive_string(vm));
// b. Set R to the string-concatenation of R and nextString. // b. Set R to the string-concatenation of R and nextString.
result = js_rope_string(vm, *result, *next_string); result = js_rope_string(vm, *result, *next_string);
@ -555,10 +557,10 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substring)
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto string_length = static_cast<double>(string.length_in_code_units()); auto string_length = static_cast<double>(string.length_in_code_units());
auto start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto start = TRY(vm.argument(0).to_integer_or_infinity(vm));
auto end = string_length; auto end = string_length;
if (!vm.argument(1).is_undefined()) if (!vm.argument(1).is_undefined())
end = TRY(vm.argument(1).to_integer_or_infinity(global_object)); end = TRY(vm.argument(1).to_integer_or_infinity(vm));
size_t final_start = clamp(start, static_cast<double>(0), string_length); size_t final_start = clamp(start, static_cast<double>(0), string_length);
size_t final_end = clamp(end, static_cast<double>(0), string_length); size_t final_end = clamp(end, static_cast<double>(0), string_length);
@ -575,7 +577,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substr)
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto size = string.length_in_code_units(); auto size = string.length_in_code_units();
auto int_start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto int_start = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (Value(int_start).is_negative_infinity()) if (Value(int_start).is_negative_infinity())
int_start = 0; int_start = 0;
else if (int_start < 0) else if (int_start < 0)
@ -583,7 +585,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substr)
auto length = vm.argument(1); auto length = vm.argument(1);
auto int_length = length.is_undefined() ? size : TRY(length.to_integer_or_infinity(global_object)); auto int_length = length.is_undefined() ? size : TRY(length.to_integer_or_infinity(vm));
if (Value(int_start).is_positive_infinity() || (int_length <= 0) || Value(int_length).is_positive_infinity()) if (Value(int_start).is_positive_infinity() || (int_length <= 0) || Value(int_length).is_positive_infinity())
return js_string(vm, String::empty()); return js_string(vm, String::empty());
@ -602,15 +604,15 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::includes)
auto search_string_value = vm.argument(0); auto search_string_value = vm.argument(0);
bool search_is_regexp = TRY(search_string_value.is_regexp(global_object)); bool search_is_regexp = TRY(search_string_value.is_regexp(vm));
if (search_is_regexp) if (search_is_regexp)
return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression"); return vm.throw_completion<TypeError>(ErrorType::IsNotA, "searchString", "string, but a regular expression");
auto search_string = TRY(search_string_value.to_utf16_string(global_object)); auto search_string = TRY(search_string_value.to_utf16_string(vm));
size_t start = 0; size_t start = 0;
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
auto position = TRY(vm.argument(1).to_integer_or_infinity(global_object)); auto position = TRY(vm.argument(1).to_integer_or_infinity(vm));
start = clamp(position, static_cast<double>(0), static_cast<double>(string.length_in_code_units())); start = clamp(position, static_cast<double>(0), static_cast<double>(string.length_in_code_units()));
} }
@ -624,7 +626,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::slice)
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto string_length = static_cast<double>(string.length_in_code_units()); auto string_length = static_cast<double>(string.length_in_code_units());
auto int_start = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto int_start = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (Value(int_start).is_negative_infinity()) if (Value(int_start).is_negative_infinity())
int_start = 0; int_start = 0;
else if (int_start < 0) else if (int_start < 0)
@ -634,7 +636,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::slice)
auto int_end = string_length; auto int_end = string_length;
if (!vm.argument(1).is_undefined()) { if (!vm.argument(1).is_undefined()) {
int_end = TRY(vm.argument(1).to_integer_or_infinity(global_object)); int_end = TRY(vm.argument(1).to_integer_or_infinity(vm));
if (Value(int_end).is_negative_infinity()) if (Value(int_end).is_negative_infinity())
int_end = 0; int_end = 0;
else if (int_end < 0) else if (int_end < 0)
@ -660,21 +662,21 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::split)
auto limit_argument = vm.argument(1); auto limit_argument = vm.argument(1);
if (!separator_argument.is_nullish()) { if (!separator_argument.is_nullish()) {
auto splitter = TRY(separator_argument.get_method(global_object, *vm.well_known_symbol_split())); auto splitter = TRY(separator_argument.get_method(vm, *vm.well_known_symbol_split()));
if (splitter) if (splitter)
return TRY(call(global_object, *splitter, separator_argument, object, limit_argument)); return TRY(call(global_object, *splitter, separator_argument, object, limit_argument));
} }
auto string = TRY(object.to_utf16_string(global_object)); auto string = TRY(object.to_utf16_string(vm));
auto* array = MUST(Array::create(realm, 0)); auto* array = MUST(Array::create(realm, 0));
size_t array_length = 0; size_t array_length = 0;
auto limit = NumericLimits<u32>::max(); auto limit = NumericLimits<u32>::max();
if (!limit_argument.is_undefined()) if (!limit_argument.is_undefined())
limit = TRY(limit_argument.to_u32(global_object)); limit = TRY(limit_argument.to_u32(vm));
auto separator = TRY(separator_argument.to_utf16_string(global_object)); auto separator = TRY(separator_argument.to_utf16_string(vm));
if (limit == 0) if (limit == 0)
return array; return array;
@ -722,12 +724,12 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::last_index_of)
{ {
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto search_string = TRY(vm.argument(0).to_utf16_string(global_object)); auto search_string = TRY(vm.argument(0).to_utf16_string(vm));
auto string_length = string.length_in_code_units(); auto string_length = string.length_in_code_units();
auto search_length = search_string.length_in_code_units(); auto search_length = search_string.length_in_code_units();
auto position = TRY(vm.argument(1).to_number(global_object)); auto position = TRY(vm.argument(1).to_number(vm));
double pos = position.is_nan() ? static_cast<double>(INFINITY) : TRY(position.to_integer_or_infinity(global_object)); double pos = position.is_nan() ? static_cast<double>(INFINITY) : TRY(position.to_integer_or_infinity(vm));
size_t start = clamp(pos, static_cast<double>(0), static_cast<double>(string_length)); size_t start = clamp(pos, static_cast<double>(0), static_cast<double>(string_length));
Optional<size_t> last_index; Optional<size_t> last_index;
@ -755,7 +757,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::at)
auto string = TRY(utf16_string_from(vm, global_object)); auto string = TRY(utf16_string_from(vm, global_object));
auto length = string.length_in_code_units(); auto length = string.length_in_code_units();
auto relative_index = TRY(vm.argument(0).to_integer_or_infinity(global_object)); auto relative_index = TRY(vm.argument(0).to_integer_or_infinity(vm));
if (Value(relative_index).is_infinity()) if (Value(relative_index).is_infinity())
return js_undefined(); return js_undefined();
@ -778,7 +780,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::symbol_iterator)
auto& realm = *global_object.associated_realm(); auto& realm = *global_object.associated_realm();
auto this_object = TRY(require_object_coercible(global_object, vm.this_value())); auto this_object = TRY(require_object_coercible(global_object, vm.this_value()));
auto string = TRY(this_object.to_string(global_object)); auto string = TRY(this_object.to_string(vm));
return StringIterator::create(realm, string); return StringIterator::create(realm, string);
} }
@ -788,14 +790,14 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::match)
auto this_object = TRY(require_object_coercible(global_object, vm.this_value())); auto this_object = TRY(require_object_coercible(global_object, vm.this_value()));
auto regexp = vm.argument(0); auto regexp = vm.argument(0);
if (!regexp.is_nullish()) { if (!regexp.is_nullish()) {
if (auto* matcher = TRY(regexp.get_method(global_object, *vm.well_known_symbol_match()))) if (auto* matcher = TRY(regexp.get_method(vm, *vm.well_known_symbol_match())))
return TRY(call(global_object, *matcher, regexp, this_object)); return TRY(call(global_object, *matcher, regexp, this_object));
} }
auto string = TRY(this_object.to_utf16_string(global_object)); auto string = TRY(this_object.to_utf16_string(vm));
auto* rx = TRY(regexp_create(global_object, regexp, js_undefined())); auto* rx = TRY(regexp_create(global_object, regexp, js_undefined()));
return TRY(Value(rx).invoke(global_object, *vm.well_known_symbol_match(), js_string(vm, move(string)))); return TRY(Value(rx).invoke(vm, *vm.well_known_symbol_match(), js_string(vm, move(string))));
} }
// 22.1.3.13 String.prototype.matchAll ( regexp ), https://tc39.es/ecma262/#sec-string.prototype.matchall // 22.1.3.13 String.prototype.matchAll ( regexp ), https://tc39.es/ecma262/#sec-string.prototype.matchall
@ -804,22 +806,22 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::match_all)
auto this_object = TRY(require_object_coercible(global_object, vm.this_value())); auto this_object = TRY(require_object_coercible(global_object, vm.this_value()));
auto regexp = vm.argument(0); auto regexp = vm.argument(0);
if (!regexp.is_nullish()) { if (!regexp.is_nullish()) {
auto is_regexp = TRY(regexp.is_regexp(global_object)); auto is_regexp = TRY(regexp.is_regexp(vm));
if (is_regexp) { if (is_regexp) {
auto flags = TRY(regexp.as_object().get("flags")); auto flags = TRY(regexp.as_object().get("flags"));
auto flags_object = TRY(require_object_coercible(global_object, flags)); auto flags_object = TRY(require_object_coercible(global_object, flags));
auto flags_string = TRY(flags_object.to_string(global_object)); auto flags_string = TRY(flags_object.to_string(vm));
if (!flags_string.contains('g')) if (!flags_string.contains('g'))
return vm.throw_completion<TypeError>(ErrorType::StringNonGlobalRegExp); return vm.throw_completion<TypeError>(ErrorType::StringNonGlobalRegExp);
} }
if (auto* matcher = TRY(regexp.get_method(global_object, *vm.well_known_symbol_match_all()))) if (auto* matcher = TRY(regexp.get_method(vm, *vm.well_known_symbol_match_all())))
return TRY(call(global_object, *matcher, regexp, this_object)); return TRY(call(global_object, *matcher, regexp, this_object));
} }
auto string = TRY(this_object.to_utf16_string(global_object)); auto string = TRY(this_object.to_utf16_string(vm));
auto* rx = TRY(regexp_create(global_object, regexp, js_string(vm, "g"))); auto* rx = TRY(regexp_create(global_object, regexp, js_string(vm, "g")));
return TRY(Value(rx).invoke(global_object, *vm.well_known_symbol_match_all(), js_string(vm, move(string)))); return TRY(Value(rx).invoke(vm, *vm.well_known_symbol_match_all(), js_string(vm, move(string))));
} }
// 22.1.3.14 String.prototype.normalize ( [ form ] ), https://tc39.es/ecma262/#sec-string.prototype.normalize // 22.1.3.14 String.prototype.normalize ( [ form ] ), https://tc39.es/ecma262/#sec-string.prototype.normalize
@ -834,7 +836,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::normalize)
String form = "NFC"; String form = "NFC";
auto form_value = vm.argument(0); auto form_value = vm.argument(0);
if (!form_value.is_undefined()) if (!form_value.is_undefined())
form = TRY(form_value.to_string(global_object)); form = TRY(form_value.to_string(vm));
// 5. If f is not one of "NFC", "NFD", "NFKC", or "NFKD", throw a RangeError exception. // 5. If f is not one of "NFC", "NFD", "NFKC", or "NFKD", throw a RangeError exception.
if (!form.is_one_of("NFC"sv, "NFD"sv, "NFKC"sv, "NFKD"sv)) if (!form.is_one_of("NFC"sv, "NFD"sv, "NFKC"sv, "NFKD"sv))
@ -855,15 +857,15 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::replace)
auto replace_value = vm.argument(1); auto replace_value = vm.argument(1);
if (!search_value.is_nullish()) { if (!search_value.is_nullish()) {
if (auto* replacer = TRY(search_value.get_method(global_object, *vm.well_known_symbol_replace()))) if (auto* replacer = TRY(search_value.get_method(vm, *vm.well_known_symbol_replace())))
return TRY(call(global_object, *replacer, search_value, this_object, replace_value)); return TRY(call(global_object, *replacer, search_value, this_object, replace_value));
} }
auto string = TRY(this_object.to_utf16_string(global_object)); auto string = TRY(this_object.to_utf16_string(vm));
auto search_string = TRY(search_value.to_utf16_string(global_object)); auto search_string = TRY(search_value.to_utf16_string(vm));
if (!replace_value.is_function()) { if (!replace_value.is_function()) {
auto replace_string = TRY(replace_value.to_utf16_string(global_object)); auto replace_string = TRY(replace_value.to_utf16_string(vm));
replace_value = js_string(vm, move(replace_string)); replace_value = js_string(vm, move(replace_string));
} }
@ -876,7 +878,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::replace)
if (replace_value.is_function()) { if (replace_value.is_function()) {
auto result = TRY(call(global_object, replace_value.as_function(), js_undefined(), js_string(vm, search_string), Value(position.value()), js_string(vm, string))); auto result = TRY(call(global_object, replace_value.as_function(), js_undefined(), js_string(vm, search_string), Value(position.value()), js_string(vm, string)));
replacement = TRY(result.to_string(global_object)); replacement = TRY(result.to_string(vm));
} else { } else {
replacement = TRY(get_substitution(global_object, search_string.view(), string.view(), *position, {}, js_undefined(), replace_value)); replacement = TRY(get_substitution(global_object, search_string.view(), string.view(), *position, {}, js_undefined(), replace_value));
} }
@ -897,26 +899,26 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::replace_all)
auto replace_value = vm.argument(1); auto replace_value = vm.argument(1);
if (!search_value.is_nullish()) { if (!search_value.is_nullish()) {
bool is_regexp = TRY(search_value.is_regexp(global_object)); bool is_regexp = TRY(search_value.is_regexp(vm));
if (is_regexp) { if (is_regexp) {
auto flags = TRY(search_value.as_object().get(vm.names.flags)); auto flags = TRY(search_value.as_object().get(vm.names.flags));
auto flags_object = TRY(require_object_coercible(global_object, flags)); auto flags_object = TRY(require_object_coercible(global_object, flags));
auto flags_string = TRY(flags_object.to_string(global_object)); auto flags_string = TRY(flags_object.to_string(vm));
if (!flags_string.contains('g')) if (!flags_string.contains('g'))
return vm.throw_completion<TypeError>(ErrorType::StringNonGlobalRegExp); return vm.throw_completion<TypeError>(ErrorType::StringNonGlobalRegExp);
} }
auto* replacer = TRY(search_value.get_method(global_object, *vm.well_known_symbol_replace())); auto* replacer = TRY(search_value.get_method(vm, *vm.well_known_symbol_replace()));
if (replacer) if (replacer)
return TRY(call(global_object, *replacer, search_value, this_object, replace_value)); return TRY(call(global_object, *replacer, search_value, this_object, replace_value));
} }
auto string = TRY(this_object.to_utf16_string(global_object)); auto string = TRY(this_object.to_utf16_string(vm));
auto search_string = TRY(search_value.to_utf16_string(global_object)); auto search_string = TRY(search_value.to_utf16_string(vm));
if (!replace_value.is_function()) { if (!replace_value.is_function()) {
auto replace_string = TRY(replace_value.to_utf16_string(global_object)); auto replace_string = TRY(replace_value.to_utf16_string(vm));
replace_value = js_string(vm, move(replace_string)); replace_value = js_string(vm, move(replace_string));
} }
@ -941,7 +943,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::replace_all)
if (replace_value.is_function()) { if (replace_value.is_function()) {
auto result = TRY(call(global_object, replace_value.as_function(), js_undefined(), js_string(vm, search_string), Value(position), js_string(vm, string))); auto result = TRY(call(global_object, replace_value.as_function(), js_undefined(), js_string(vm, search_string), Value(position), js_string(vm, string)));
replacement = TRY(result.to_string(global_object)); replacement = TRY(result.to_string(vm));
} else { } else {
replacement = TRY(get_substitution(global_object, search_string.view(), string.view(), position, {}, js_undefined(), replace_value)); replacement = TRY(get_substitution(global_object, search_string.view(), string.view(), position, {}, js_undefined(), replace_value));
} }
@ -964,14 +966,14 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::search)
auto this_object = TRY(require_object_coercible(global_object, vm.this_value())); auto this_object = TRY(require_object_coercible(global_object, vm.this_value()));
auto regexp = vm.argument(0); auto regexp = vm.argument(0);
if (!regexp.is_nullish()) { if (!regexp.is_nullish()) {
if (auto* searcher = TRY(regexp.get_method(global_object, *vm.well_known_symbol_search()))) if (auto* searcher = TRY(regexp.get_method(vm, *vm.well_known_symbol_search())))
return TRY(call(global_object, *searcher, regexp, this_object)); return TRY(call(global_object, *searcher, regexp, this_object));
} }
auto string = TRY(this_object.to_utf16_string(global_object)); auto string = TRY(this_object.to_utf16_string(vm));
auto* rx = TRY(regexp_create(global_object, regexp, js_undefined())); auto* rx = TRY(regexp_create(global_object, regexp, js_undefined()));
return TRY(Value(rx).invoke(global_object, *vm.well_known_symbol_search(), js_string(vm, move(string)))); return TRY(Value(rx).invoke(vm, *vm.well_known_symbol_search(), js_string(vm, move(string))));
} }
// B.2.2.2.1 CreateHTML ( string, tag, attribute, value ), https://tc39.es/ecma262/#sec-createhtml // B.2.2.2.1 CreateHTML ( string, tag, attribute, value ), https://tc39.es/ecma262/#sec-createhtml
@ -979,12 +981,12 @@ static ThrowCompletionOr<Value> create_html(GlobalObject& global_object, Value s
{ {
auto& vm = global_object.vm(); auto& vm = global_object.vm();
TRY(require_object_coercible(global_object, string)); TRY(require_object_coercible(global_object, string));
auto str = TRY(string.to_string(global_object)); auto str = TRY(string.to_string(vm));
StringBuilder builder; StringBuilder builder;
builder.append('<'); builder.append('<');
builder.append(tag); builder.append(tag);
if (!attribute.is_empty()) { if (!attribute.is_empty()) {
auto value_string = TRY(value.to_string(global_object)); auto value_string = TRY(value.to_string(vm));
builder.append(' '); builder.append(' ');
builder.append(attribute); builder.append(attribute);
builder.append("=\""sv); builder.append("=\""sv);
@ -1085,10 +1087,10 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::locale_compare)
auto object = TRY(require_object_coercible(global_object, vm.this_value())); auto object = TRY(require_object_coercible(global_object, vm.this_value()));
// 2. Let S be ? ToString(O). // 2. Let S be ? ToString(O).
auto string = TRY(object.to_string(global_object)); auto string = TRY(object.to_string(vm));
// 3. Let thatValue be ? ToString(that). // 3. Let thatValue be ? ToString(that).
auto that_value = TRY(vm.argument(0).to_string(global_object)); auto that_value = TRY(vm.argument(0).to_string(vm));
// 4. Let collator be ? Construct(%Collator%, « locales, options »). // 4. Let collator be ? Construct(%Collator%, « locales, options »).
auto* collator = TRY(construct(global_object, *global_object.intl_collator_constructor(), vm.argument(1), vm.argument(2))); auto* collator = TRY(construct(global_object, *global_object.intl_collator_constructor(), vm.argument(1), vm.argument(2)));

View file

@ -38,9 +38,10 @@ void SymbolConstructor::initialize(Realm& realm)
// 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description // 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description
ThrowCompletionOr<Value> SymbolConstructor::call() ThrowCompletionOr<Value> SymbolConstructor::call()
{ {
if (vm().argument(0).is_undefined()) auto& vm = this->vm();
return js_symbol(heap(), {}, false); if (vm.argument(0).is_undefined())
return js_symbol(heap(), TRY(vm().argument(0).to_string(global_object())), false); return js_symbol(vm, {}, false);
return js_symbol(vm, TRY(vm.argument(0).to_string(vm)), false);
} }
// 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description // 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description
@ -52,7 +53,7 @@ ThrowCompletionOr<Object*> SymbolConstructor::construct(FunctionObject&)
// 20.4.2.2 Symbol.for ( key ), https://tc39.es/ecma262/#sec-symbol.for // 20.4.2.2 Symbol.for ( key ), https://tc39.es/ecma262/#sec-symbol.for
JS_DEFINE_NATIVE_FUNCTION(SymbolConstructor::for_) JS_DEFINE_NATIVE_FUNCTION(SymbolConstructor::for_)
{ {
auto description = TRY(vm.argument(0).to_string(global_object)); auto description = TRY(vm.argument(0).to_string(vm));
return global_object.vm().get_global_symbol(description); return global_object.vm().get_global_symbol(description);
} }

View file

@ -104,9 +104,6 @@ ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey c
{ {
VERIFY(property.is_string()); VERIFY(property.is_string());
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let value be ? Get(options, property). // 1. Let value be ? Get(options, property).
auto value = TRY(options.get(property)); auto value = TRY(options.get(property));
@ -133,7 +130,7 @@ ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey c
// 6. Else if type is "number", then // 6. Else if type is "number", then
else if (type == OptionType::Number) { else if (type == OptionType::Number) {
// a. Set value to ? ToNumber(value). // a. Set value to ? ToNumber(value).
value = TRY(value.to_number(global_object)); value = TRY(value.to_number(vm));
// b. If value is NaN, throw a RangeError exception. // b. If value is NaN, throw a RangeError exception.
if (value.is_nan()) if (value.is_nan())
@ -145,7 +142,7 @@ ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey c
VERIFY(type == OptionType::String); VERIFY(type == OptionType::String);
// b. Set value to ? ToString(value). // b. Set value to ? ToString(value).
value = TRY(value.to_primitive_string(global_object)); value = TRY(value.to_primitive_string(vm));
} }
// 8. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception. // 8. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
@ -327,9 +324,6 @@ ThrowCompletionOr<u64> to_temporal_date_time_rounding_increment(VM& vm, Object c
// 13.14 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision // 13.14 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(VM& vm, Object const& normalized_options) ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(VM& vm, Object const& normalized_options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let smallestUnit be ? GetTemporalUnit(normalizedOptions, "smallestUnit", time, undefined). // 1. Let smallestUnit be ? GetTemporalUnit(normalizedOptions, "smallestUnit", time, undefined).
auto smallest_unit = TRY(get_temporal_unit(vm, normalized_options, vm.names.smallestUnit, UnitGroup::Time, Optional<StringView> {})); auto smallest_unit = TRY(get_temporal_unit(vm, normalized_options, vm.names.smallestUnit, UnitGroup::Time, Optional<StringView> {}));
@ -378,7 +372,7 @@ ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(VM& vm, Ob
// a. If fractionalDigitsVal is not undefined, then // a. If fractionalDigitsVal is not undefined, then
if (!fractional_digits_value.is_undefined()) { if (!fractional_digits_value.is_undefined()) {
// i. If ? ToString(fractionalDigitsVal) is not "auto", throw a RangeError exception. // i. If ? ToString(fractionalDigitsVal) is not "auto", throw a RangeError exception.
if (TRY(fractional_digits_value.to_string(global_object)) != "auto"sv) if (TRY(fractional_digits_value.to_string(vm)) != "auto"sv)
return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv); return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
} }
@ -536,7 +530,6 @@ ThrowCompletionOr<Optional<String>> get_temporal_unit(VM& vm, Object const& norm
ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& options) ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& options)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(options) is Object. // 1. Assert: Type(options) is Object.
@ -617,7 +610,7 @@ ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& optio
// 7. Else, // 7. Else,
else { else {
// a. Let string be ? ToString(value). // a. Let string be ? ToString(value).
auto string = TRY(value.to_string(global_object)); auto string = TRY(value.to_string(vm));
// b. Let result be ? ParseTemporalRelativeToString(string). // b. Let result be ? ParseTemporalRelativeToString(string).
auto parsed_result = TRY(parse_temporal_relative_to_string(vm, string)); auto parsed_result = TRY(parse_temporal_relative_to_string(vm, string));
@ -681,7 +674,7 @@ ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& optio
if (offset_behavior == OffsetBehavior::Option) { if (offset_behavior == OffsetBehavior::Option) {
// i. Set offsetString to ? ToString(offsetString). // i. Set offsetString to ? ToString(offsetString).
// NOTE: offsetString is not used after this path, so we don't need to put this into the original offset_string which is of type JS::Value. // NOTE: offsetString is not used after this path, so we don't need to put this into the original offset_string which is of type JS::Value.
auto actual_offset_string = TRY(offset_string.to_string(global_object)); auto actual_offset_string = TRY(offset_string.to_string(vm));
// ii. Let offsetNs be ? ParseTimeZoneOffsetString(offsetString). // ii. Let offsetNs be ? ParseTimeZoneOffsetString(offsetString).
offset_ns = TRY(parse_time_zone_offset_string(vm, actual_offset_string)); offset_ns = TRY(parse_time_zone_offset_string(vm, actual_offset_string));
@ -728,7 +721,6 @@ StringView larger_of_two_temporal_units(StringView unit1, StringView unit2)
ThrowCompletionOr<Object*> merge_largest_unit_option(VM& vm, Object const& options, String largest_unit) ThrowCompletionOr<Object*> merge_largest_unit_option(VM& vm, Object const& options, String largest_unit)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let merged be OrdinaryObjectCreate(null). // 1. Let merged be OrdinaryObjectCreate(null).
auto* merged = Object::create(realm, nullptr); auto* merged = Object::create(realm, nullptr);
@ -738,7 +730,7 @@ ThrowCompletionOr<Object*> merge_largest_unit_option(VM& vm, Object const& optio
// 3. For each element nextKey of keys, do // 3. For each element nextKey of keys, do
for (auto& key : keys) { for (auto& key : keys) {
auto next_key = MUST(PropertyKey::from_value(global_object, key)); auto next_key = MUST(PropertyKey::from_value(vm, key));
// a. Let propValue be ? Get(options, nextKey). // a. Let propValue be ? Get(options, nextKey).
auto prop_value = TRY(options.get(next_key)); auto prop_value = TRY(options.get(next_key));
@ -1729,7 +1721,6 @@ ThrowCompletionOr<double> to_positive_integer(VM& vm, Value argument)
ThrowCompletionOr<Object*> prepare_temporal_fields(VM& vm, Object const& fields, Vector<String> const& field_names, Variant<PrepareTemporalFieldsPartial, Vector<StringView>> const& required_fields) ThrowCompletionOr<Object*> prepare_temporal_fields(VM& vm, Object const& fields, Vector<String> const& field_names, Variant<PrepareTemporalFieldsPartial, Vector<StringView>> const& required_fields)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let result be OrdinaryObjectCreate(null). // 1. Let result be OrdinaryObjectCreate(null).
auto* result = Object::create(realm, nullptr); auto* result = Object::create(realm, nullptr);
@ -1766,7 +1757,7 @@ ThrowCompletionOr<Object*> prepare_temporal_fields(VM& vm, Object const& fields,
else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv)) { else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv)) {
// a. Assert: Conversion is ToString. // a. Assert: Conversion is ToString.
// b. Set value to ? ToString(value). // b. Set value to ? ToString(value).
value = TRY(value.to_primitive_string(global_object)); value = TRY(value.to_primitive_string(vm));
} }
// iii. Perform ! CreateDataPropertyOrThrow(result, property, value). // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).

View file

@ -191,11 +191,8 @@ ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey c
template<typename... Args> template<typename... Args>
ThrowCompletionOr<double> to_integer_throw_on_infinity(VM& vm, Value argument, ErrorType error_type, Args... args) ThrowCompletionOr<double> to_integer_throw_on_infinity(VM& vm, Value argument, ErrorType error_type, Args... args)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let integer be ? ToIntegerOrInfinity(argument). // 1. Let integer be ? ToIntegerOrInfinity(argument).
auto integer = TRY(argument.to_integer_or_infinity(global_object)); auto integer = TRY(argument.to_integer_or_infinity(vm));
// 2. If integer is -∞ or +∞ , then // 2. If integer is -∞ or +∞ , then
if (Value(integer).is_infinity()) { if (Value(integer).is_infinity()) {
@ -211,11 +208,8 @@ ThrowCompletionOr<double> to_integer_throw_on_infinity(VM& vm, Value argument, E
template<typename... Args> template<typename... Args>
ThrowCompletionOr<double> to_integer_without_rounding(VM& vm, Value argument, ErrorType error_type, Args... args) ThrowCompletionOr<double> to_integer_without_rounding(VM& vm, Value argument, ErrorType error_type, Args... args)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let number be ? ToNumber(argument). // 1. Let number be ? ToNumber(argument).
auto number = TRY(argument.to_number(global_object)); auto number = TRY(argument.to_number(vm));
// 2. If number is NaN, +0𝔽, or -0𝔽, return 0. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())

View file

@ -106,7 +106,7 @@ ThrowCompletionOr<Vector<String>> calendar_fields(VM& vm, Object& calendar, Vect
auto& global_object = realm.global_object(); auto& global_object = realm.global_object();
// 1. Let fields be ? GetMethod(calendar, "fields"). // 1. Let fields be ? GetMethod(calendar, "fields").
auto fields = TRY(Value(&calendar).get_method(global_object, vm.names.fields)); auto fields = TRY(Value(&calendar).get_method(vm, vm.names.fields));
// 2. Let fieldsArray be CreateArrayFromList(fieldNames). // 2. Let fieldsArray be CreateArrayFromList(fieldNames).
auto field_names_values = MarkedVector<Value> { vm.heap() }; auto field_names_values = MarkedVector<Value> { vm.heap() };
@ -136,7 +136,7 @@ ThrowCompletionOr<Object*> calendar_merge_fields(VM& vm, Object& calendar, Objec
auto& global_object = realm.global_object(); auto& global_object = realm.global_object();
// 1. Let mergeFields be ? GetMethod(calendar, "mergeFields"). // 1. Let mergeFields be ? GetMethod(calendar, "mergeFields").
auto* merge_fields = TRY(Value(&calendar).get_method(global_object, vm.names.mergeFields)); auto* merge_fields = TRY(Value(&calendar).get_method(vm, vm.names.mergeFields));
// 2. If mergeFields is undefined, then // 2. If mergeFields is undefined, then
if (!merge_fields) { if (!merge_fields) {
@ -168,13 +168,13 @@ ThrowCompletionOr<PlainDate*> calendar_date_add(VM& vm, Object& calendar, Value
// 4. If dateAdd is not present, set dateAdd to ? GetMethod(calendar, "dateAdd"). // 4. If dateAdd is not present, set dateAdd to ? GetMethod(calendar, "dateAdd").
if (!date_add) if (!date_add)
date_add = TRY(Value(&calendar).get_method(global_object, vm.names.dateAdd)); date_add = TRY(Value(&calendar).get_method(vm, vm.names.dateAdd));
// 5. Let addedDate be ? Call(dateAdd, calendar, « date, duration, options »). // 5. Let addedDate be ? Call(dateAdd, calendar, « date, duration, options »).
auto added_date = TRY(call(global_object, date_add ?: js_undefined(), &calendar, date, &duration, options ?: js_undefined())); auto added_date = TRY(call(global_object, date_add ?: js_undefined(), &calendar, date, &duration, options ?: js_undefined()));
// 6. Perform ? RequireInternalSlot(addedDate, [[InitializedTemporalDate]]). // 6. Perform ? RequireInternalSlot(addedDate, [[InitializedTemporalDate]]).
auto* added_date_object = TRY(added_date.to_object(global_object)); auto* added_date_object = TRY(added_date.to_object(vm));
if (!is<PlainDate>(added_date_object)) if (!is<PlainDate>(added_date_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate"); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate");
@ -192,13 +192,13 @@ ThrowCompletionOr<Duration*> calendar_date_until(VM& vm, Object& calendar, Value
// 2. If dateUntil is not present, set dateUntil to ? GetMethod(calendar, "dateUntil"). // 2. If dateUntil is not present, set dateUntil to ? GetMethod(calendar, "dateUntil").
if (!date_until) if (!date_until)
date_until = TRY(Value(&calendar).get_method(global_object, vm.names.dateUntil)); date_until = TRY(Value(&calendar).get_method(vm, vm.names.dateUntil));
// 3. Let duration be ? Call(dateUntil, calendar, « one, two, options »). // 3. Let duration be ? Call(dateUntil, calendar, « one, two, options »).
auto duration = TRY(call(global_object, date_until ?: js_undefined(), &calendar, one, two, &options)); auto duration = TRY(call(global_object, date_until ?: js_undefined(), &calendar, one, two, &options));
// 4. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). // 4. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]).
auto* duration_object = TRY(duration.to_object(global_object)); auto* duration_object = TRY(duration.to_object(vm));
if (!is<Duration>(duration_object)) if (!is<Duration>(duration_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.Duration"); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.Duration");
@ -209,13 +209,10 @@ ThrowCompletionOr<Duration*> calendar_date_until(VM& vm, Object& calendar, Value
// 12.2.8 CalendarYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryear // 12.2.8 CalendarYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryear
ThrowCompletionOr<double> calendar_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<double> calendar_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "year", « dateLike »). // 2. Let result be ? Invoke(calendar, "year", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.year, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.year, &date_like));
// 3. If result is undefined, throw a RangeError exception. // 3. If result is undefined, throw a RangeError exception.
if (result.is_undefined()) if (result.is_undefined())
@ -228,13 +225,10 @@ ThrowCompletionOr<double> calendar_year(VM& vm, Object& calendar, Object& date_l
// 12.2.9 CalendarMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonth // 12.2.9 CalendarMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonth
ThrowCompletionOr<double> calendar_month(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<double> calendar_month(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "month", « dateLike »). // 2. Let result be ? Invoke(calendar, "month", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.month, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.month, &date_like));
// NOTE: Explicitly handled for a better error message similar to the other calendar property AOs // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
if (result.is_undefined()) if (result.is_undefined())
@ -247,32 +241,26 @@ ThrowCompletionOr<double> calendar_month(VM& vm, Object& calendar, Object& date_
// 12.2.10 CalendarMonthCode ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthcode // 12.2.10 CalendarMonthCode ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthcode
ThrowCompletionOr<String> calendar_month_code(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<String> calendar_month_code(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "monthCode", « dateLike »). // 2. Let result be ? Invoke(calendar, "monthCode", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.monthCode, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.monthCode, &date_like));
// 3. If result is undefined, throw a RangeError exception. // 3. If result is undefined, throw a RangeError exception.
if (result.is_undefined()) if (result.is_undefined())
return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.monthCode.as_string(), vm.names.undefined.as_string()); return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.monthCode.as_string(), vm.names.undefined.as_string());
// 4. Return ? ToString(result). // 4. Return ? ToString(result).
return result.to_string(global_object); return result.to_string(vm);
} }
// 12.2.11 CalendarDay ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarday // 12.2.11 CalendarDay ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarday
ThrowCompletionOr<double> calendar_day(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<double> calendar_day(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "day", « dateLike »). // 2. Let result be ? Invoke(calendar, "day", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.day, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.day, &date_like));
// NOTE: Explicitly handled for a better error message similar to the other calendar property AOs // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
if (result.is_undefined()) if (result.is_undefined())
@ -285,113 +273,86 @@ ThrowCompletionOr<double> calendar_day(VM& vm, Object& calendar, Object& date_li
// 12.2.12 CalendarDayOfWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofweek // 12.2.12 CalendarDayOfWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofweek
ThrowCompletionOr<Value> calendar_day_of_week(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_day_of_week(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "dayOfWeek", « dateLike »). // 2. Return ? Invoke(calendar, "dayOfWeek", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.dayOfWeek, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.dayOfWeek, &date_like));
} }
// 12.2.13 CalendarDayOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofyear // 12.2.13 CalendarDayOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofyear
ThrowCompletionOr<Value> calendar_day_of_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_day_of_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "dayOfYear", « dateLike »). // 2. Return ? Invoke(calendar, "dayOfYear", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.dayOfYear, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.dayOfYear, &date_like));
} }
// 12.2.14 CalendarWeekOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarweekofyear // 12.2.14 CalendarWeekOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarweekofyear
ThrowCompletionOr<Value> calendar_week_of_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_week_of_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "weekOfYear", « dateLike »). // 2. Return ? Invoke(calendar, "weekOfYear", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.weekOfYear, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.weekOfYear, &date_like));
} }
// 12.2.14 CalendarDaysInWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinweek // 12.2.14 CalendarDaysInWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinweek
ThrowCompletionOr<Value> calendar_days_in_week(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_days_in_week(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "daysInWeek", « dateLike »). // 2. Return ? Invoke(calendar, "daysInWeek", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.daysInWeek, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.daysInWeek, &date_like));
} }
// 12.2.16 CalendarDaysInMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinmonth // 12.2.16 CalendarDaysInMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinmonth
ThrowCompletionOr<Value> calendar_days_in_month(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_days_in_month(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "daysInMonth", « dateLike »). // 2. Return ? Invoke(calendar, "daysInMonth", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.daysInMonth, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.daysInMonth, &date_like));
} }
// 12.2.17 CalendarDaysInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinyear // 12.2.17 CalendarDaysInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinyear
ThrowCompletionOr<Value> calendar_days_in_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_days_in_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "daysInYear", « dateLike »). // 2. Return ? Invoke(calendar, "daysInYear", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.daysInYear, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.daysInYear, &date_like));
} }
// 12.2.18 CalendarMonthsInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthsinyear // 12.2.18 CalendarMonthsInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthsinyear
ThrowCompletionOr<Value> calendar_months_in_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_months_in_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "monthsInYear", « dateLike »). // 2. Return ? Invoke(calendar, "monthsInYear", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.monthsInYear, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.monthsInYear, &date_like));
} }
// 12.2.29 CalendarInLeapYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarinleapyear // 12.2.29 CalendarInLeapYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarinleapyear
ThrowCompletionOr<Value> calendar_in_leap_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_in_leap_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Return ? Invoke(calendar, "inLeapYear", « dateLike »). // 2. Return ? Invoke(calendar, "inLeapYear", « dateLike »).
return TRY(Value(&calendar).invoke(global_object, vm.names.inLeapYear, &date_like)); return TRY(Value(&calendar).invoke(vm, vm.names.inLeapYear, &date_like));
} }
// 15.6.1.1 CalendarEra ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarera // 15.6.1.1 CalendarEra ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarera
ThrowCompletionOr<Value> calendar_era(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_era(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "era", « dateLike »). // 2. Let result be ? Invoke(calendar, "era", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.era, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.era, &date_like));
// 3. If result is not undefined, set result to ? ToString(result). // 3. If result is not undefined, set result to ? ToString(result).
if (!result.is_undefined()) if (!result.is_undefined())
result = js_string(vm, TRY(result.to_string(global_object))); result = js_string(vm, TRY(result.to_string(vm)));
// 4. Return result. // 4. Return result.
return result; return result;
@ -400,13 +361,10 @@ ThrowCompletionOr<Value> calendar_era(VM& vm, Object& calendar, Object& date_lik
// 15.6.1.2 CalendarEraYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarerayear // 15.6.1.2 CalendarEraYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarerayear
ThrowCompletionOr<Value> calendar_era_year(VM& vm, Object& calendar, Object& date_like) ThrowCompletionOr<Value> calendar_era_year(VM& vm, Object& calendar, Object& date_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(calendar) is Object. // 1. Assert: Type(calendar) is Object.
// 2. Let result be ? Invoke(calendar, "eraYear", « dateLike »). // 2. Let result be ? Invoke(calendar, "eraYear", « dateLike »).
auto result = TRY(Value(&calendar).invoke(global_object, vm.names.eraYear, &date_like)); auto result = TRY(Value(&calendar).invoke(vm, vm.names.eraYear, &date_like));
// 3. If result is not undefined, set result to ? ToIntegerThrowOnInfinity(result). // 3. If result is not undefined, set result to ? ToIntegerThrowOnInfinity(result).
if (!result.is_undefined()) if (!result.is_undefined())
@ -419,9 +377,6 @@ ThrowCompletionOr<Value> calendar_era_year(VM& vm, Object& calendar, Object& dat
// 12.2.20 ToTemporalCalendar ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendar // 12.2.20 ToTemporalCalendar ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendar
ThrowCompletionOr<Object*> to_temporal_calendar(VM& vm, Value temporal_calendar_like) ThrowCompletionOr<Object*> to_temporal_calendar(VM& vm, Value temporal_calendar_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If Type(temporalCalendarLike) is Object, then // 1. If Type(temporalCalendarLike) is Object, then
if (temporal_calendar_like.is_object()) { if (temporal_calendar_like.is_object()) {
auto& temporal_calendar_like_object = temporal_calendar_like.as_object(); auto& temporal_calendar_like_object = temporal_calendar_like.as_object();
@ -453,7 +408,7 @@ ThrowCompletionOr<Object*> to_temporal_calendar(VM& vm, Value temporal_calendar_
} }
// 2. Let identifier be ? ToString(temporalCalendarLike). // 2. Let identifier be ? ToString(temporalCalendarLike).
auto identifier = TRY(temporal_calendar_like.to_string(global_object)); auto identifier = TRY(temporal_calendar_like.to_string(vm));
// 3. If IsBuiltinCalendar(identifier) is false, then // 3. If IsBuiltinCalendar(identifier) is false, then
if (!is_builtin_calendar(identifier)) { if (!is_builtin_calendar(identifier)) {
@ -509,16 +464,13 @@ ThrowCompletionOr<Object*> get_temporal_calendar_with_iso_default(VM& vm, Object
// 12.2.23 CalendarDateFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendardatefromfields // 12.2.23 CalendarDateFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendardatefromfields
ThrowCompletionOr<PlainDate*> calendar_date_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options) ThrowCompletionOr<PlainDate*> calendar_date_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Let date be ? Invoke(calendar, "dateFromFields", « fields, options »). // 2. Let date be ? Invoke(calendar, "dateFromFields", « fields, options »).
auto date = TRY(Value(&calendar).invoke(global_object, vm.names.dateFromFields, &fields, options ?: js_undefined())); auto date = TRY(Value(&calendar).invoke(vm, vm.names.dateFromFields, &fields, options ?: js_undefined()));
// 3. Perform ? RequireInternalSlot(date, [[InitializedTemporalDate]]). // 3. Perform ? RequireInternalSlot(date, [[InitializedTemporalDate]]).
auto* date_object = TRY(date.to_object(global_object)); auto* date_object = TRY(date.to_object(vm));
if (!is<PlainDate>(date_object)) if (!is<PlainDate>(date_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate"); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate");
@ -529,16 +481,13 @@ ThrowCompletionOr<PlainDate*> calendar_date_from_fields(VM& vm, Object& calendar
// 12.2.24 CalendarYearMonthFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryearmonthfromfields // 12.2.24 CalendarYearMonthFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryearmonthfromfields
ThrowCompletionOr<PlainYearMonth*> calendar_year_month_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options) ThrowCompletionOr<PlainYearMonth*> calendar_year_month_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Let yearMonth be ? Invoke(calendar, "yearMonthFromFields", « fields, options »). // 2. Let yearMonth be ? Invoke(calendar, "yearMonthFromFields", « fields, options »).
auto year_month = TRY(Value(&calendar).invoke(global_object, vm.names.yearMonthFromFields, &fields, options ?: js_undefined())); auto year_month = TRY(Value(&calendar).invoke(vm, vm.names.yearMonthFromFields, &fields, options ?: js_undefined()));
// 3. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]). // 3. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]).
auto* year_month_object = TRY(year_month.to_object(global_object)); auto* year_month_object = TRY(year_month.to_object(vm));
if (!is<PlainYearMonth>(year_month_object)) if (!is<PlainYearMonth>(year_month_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainYearMonth"); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainYearMonth");
@ -549,16 +498,13 @@ ThrowCompletionOr<PlainYearMonth*> calendar_year_month_from_fields(VM& vm, Objec
// 12.2.25 CalendarMonthDayFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdayfromfields // 12.2.25 CalendarMonthDayFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdayfromfields
ThrowCompletionOr<PlainMonthDay*> calendar_month_day_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options) ThrowCompletionOr<PlainMonthDay*> calendar_month_day_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Let monthDay be ? Invoke(calendar, "monthDayFromFields", « fields, options »). // 2. Let monthDay be ? Invoke(calendar, "monthDayFromFields", « fields, options »).
auto month_day = TRY(Value(&calendar).invoke(global_object, vm.names.monthDayFromFields, &fields, options ?: js_undefined())); auto month_day = TRY(Value(&calendar).invoke(vm, vm.names.monthDayFromFields, &fields, options ?: js_undefined()));
// 3. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]). // 3. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]).
auto* month_day_object = TRY(month_day.to_object(global_object)); auto* month_day_object = TRY(month_day.to_object(vm));
if (!is<PlainMonthDay>(month_day_object)) if (!is<PlainMonthDay>(month_day_object))
return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainMonthDay"); return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainMonthDay");
@ -587,18 +533,15 @@ String format_calendar_annotation(StringView id, StringView show_calendar)
// 12.2.27 CalendarEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-calendarequals // 12.2.27 CalendarEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-calendarequals
ThrowCompletionOr<bool> calendar_equals(VM& vm, Object& one, Object& two) ThrowCompletionOr<bool> calendar_equals(VM& vm, Object& one, Object& two)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If one and two are the same Object value, return true. // 1. If one and two are the same Object value, return true.
if (&one == &two) if (&one == &two)
return true; return true;
// 2. Let calendarOne be ? ToString(one). // 2. Let calendarOne be ? ToString(one).
auto calendar_one = TRY(Value(&one).to_string(global_object)); auto calendar_one = TRY(Value(&one).to_string(vm));
// 3. Let calendarTwo be ? ToString(two). // 3. Let calendarTwo be ? ToString(two).
auto calendar_two = TRY(Value(&two).to_string(global_object)); auto calendar_two = TRY(Value(&two).to_string(vm));
// 4. If calendarOne is calendarTwo, return true. // 4. If calendarOne is calendarTwo, return true.
if (calendar_one == calendar_two) if (calendar_one == calendar_two)
@ -611,18 +554,15 @@ ThrowCompletionOr<bool> calendar_equals(VM& vm, Object& one, Object& two)
// 12.2.28 ConsolidateCalendars ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-consolidatecalendars // 12.2.28 ConsolidateCalendars ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-consolidatecalendars
ThrowCompletionOr<Object*> consolidate_calendars(VM& vm, Object& one, Object& two) ThrowCompletionOr<Object*> consolidate_calendars(VM& vm, Object& one, Object& two)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If one and two are the same Object value, return two. // 1. If one and two are the same Object value, return two.
if (&one == &two) if (&one == &two)
return &two; return &two;
// 2. Let calendarOne be ? ToString(one). // 2. Let calendarOne be ? ToString(one).
auto calendar_one = TRY(Value(&one).to_string(global_object)); auto calendar_one = TRY(Value(&one).to_string(vm));
// 3. Let calendarTwo be ? ToString(two). // 3. Let calendarTwo be ? ToString(two).
auto calendar_two = TRY(Value(&two).to_string(global_object)); auto calendar_two = TRY(Value(&two).to_string(vm));
// 4. If calendarOne is calendarTwo, return two. // 4. If calendarOne is calendarTwo, return two.
if (calendar_one == calendar_two) if (calendar_one == calendar_two)
@ -706,9 +646,6 @@ String build_iso_month_code(u8 month)
// 12.2.32 ResolveISOMonth ( fields ), https://tc39.es/proposal-temporal/#sec-temporal-resolveisomonth // 12.2.32 ResolveISOMonth ( fields ), https://tc39.es/proposal-temporal/#sec-temporal-resolveisomonth
ThrowCompletionOr<double> resolve_iso_month(VM& vm, Object const& fields) ThrowCompletionOr<double> resolve_iso_month(VM& vm, Object const& fields)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: fields is an ordinary object with no more and no less than the own data properties listed in Table 13. // 1. Assert: fields is an ordinary object with no more and no less than the own data properties listed in Table 13.
// 2. Let month be ! Get(fields, "month"). // 2. Let month be ! Get(fields, "month").
@ -745,7 +682,7 @@ ThrowCompletionOr<double> resolve_iso_month(VM& vm, Object const& fields)
auto number_part = month_code_string.substring(1); auto number_part = month_code_string.substring(1);
// 9. Set numberPart to ! ToIntegerOrInfinity(numberPart). // 9. Set numberPart to ! ToIntegerOrInfinity(numberPart).
auto number_part_integer = MUST(Value(js_string(vm, move(number_part))).to_integer_or_infinity(global_object)); auto number_part_integer = MUST(Value(js_string(vm, move(number_part))).to_integer_or_infinity(vm));
// 10. If numberPart < 1 or numberPart > 12, throw a RangeError exception. // 10. If numberPart < 1 or numberPart > 12, throw a RangeError exception.
if (number_part_integer < 1 || number_part_integer > 12) if (number_part_integer < 1 || number_part_integer > 12)
@ -970,7 +907,7 @@ ThrowCompletionOr<Object*> default_merge_calendar_fields(VM& vm, Object const& f
for (auto& key : fields_keys) { for (auto& key : fields_keys) {
// a. If key is not "month" or "monthCode", then // a. If key is not "month" or "monthCode", then
if (key.as_string().string() != vm.names.month.as_string() && key.as_string().string() != vm.names.monthCode.as_string()) { if (key.as_string().string() != vm.names.month.as_string() && key.as_string().string() != vm.names.monthCode.as_string()) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// i. Let propValue be ? Get(fields, key). // i. Let propValue be ? Get(fields, key).
auto prop_value = TRY(fields.get(property_key)); auto prop_value = TRY(fields.get(property_key));
@ -991,7 +928,7 @@ ThrowCompletionOr<Object*> default_merge_calendar_fields(VM& vm, Object const& f
// 5. For each element key of additionalFieldsKeys, do // 5. For each element key of additionalFieldsKeys, do
for (auto& key : additional_fields_keys) { for (auto& key : additional_fields_keys) {
auto property_key = MUST(PropertyKey::from_value(global_object, key)); auto property_key = MUST(PropertyKey::from_value(vm, key));
// a. Let propValue be ? Get(additionalFields, key). // a. Let propValue be ? Get(additionalFields, key).
auto prop_value = TRY(additional_fields.get(property_key)); auto prop_value = TRY(additional_fields.get(property_key));

View file

@ -45,10 +45,9 @@ ThrowCompletionOr<Value> CalendarConstructor::call()
ThrowCompletionOr<Object*> CalendarConstructor::construct(FunctionObject& new_target) ThrowCompletionOr<Object*> CalendarConstructor::construct(FunctionObject& new_target)
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto& global_object = this->global_object();
// 2. Set id to ? ToString(id). // 2. Set id to ? ToString(id).
auto identifier = TRY(vm.argument(0).to_string(global_object)); auto identifier = TRY(vm.argument(0).to_string(vm));
// 3. If IsBuiltinCalendar(id) is false, then // 3. If IsBuiltinCalendar(id) is false, then
if (!is_builtin_calendar(identifier)) { if (!is_builtin_calendar(identifier)) {

View file

@ -70,7 +70,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::id_getter)
auto* calendar = TRY(typed_this_object(vm)); auto* calendar = TRY(typed_this_object(vm));
// 3. Return ? ToString(calendar). // 3. Return ? ToString(calendar).
return { js_string(vm, TRY(Value(calendar).to_string(global_object))) }; return { js_string(vm, TRY(Value(calendar).to_string(vm))) };
} }
// 12.4.4 Temporal.Calendar.prototype.dateFromFields ( fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype.datefromfields // 12.4.4 Temporal.Calendar.prototype.dateFromFields ( fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype.datefromfields
@ -575,10 +575,10 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::merge_fields)
auto* calendar = TRY(typed_this_object(vm)); auto* calendar = TRY(typed_this_object(vm));
// 3. Set fields to ? ToObject(fields). // 3. Set fields to ? ToObject(fields).
auto* fields = TRY(vm.argument(0).to_object(global_object)); auto* fields = TRY(vm.argument(0).to_object(vm));
// 4. Set additionalFields to ? ToObject(additionalFields). // 4. Set additionalFields to ? ToObject(additionalFields).
auto* additional_fields = TRY(vm.argument(1).to_object(global_object)); auto* additional_fields = TRY(vm.argument(1).to_object(vm));
// 5. Assert: calendar.[[Identifier]] is "iso8601". // 5. Assert: calendar.[[Identifier]] is "iso8601".
VERIFY(calendar->identifier() == "iso8601"sv); VERIFY(calendar->identifier() == "iso8601"sv);
@ -606,7 +606,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::to_json)
auto* calendar = TRY(typed_this_object(vm)); auto* calendar = TRY(typed_this_object(vm));
// 3. Return ? ToString(calendar). // 3. Return ? ToString(calendar).
return js_string(vm, TRY(Value(calendar).to_string(global_object))); return js_string(vm, TRY(Value(calendar).to_string(vm)));
} }
// 15.6.2.6 Temporal.Calendar.prototype.era ( temporalDateLike ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype.era // 15.6.2.6 Temporal.Calendar.prototype.era ( temporalDateLike ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype.era

View file

@ -139,13 +139,10 @@ ThrowCompletionOr<Duration*> to_temporal_duration(VM& vm, Value item)
// 7.5.9 ToTemporalDurationRecord ( temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldurationrecord // 7.5.9 ToTemporalDurationRecord ( temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldurationrecord
ThrowCompletionOr<DurationRecord> to_temporal_duration_record(VM& vm, Value temporal_duration_like) ThrowCompletionOr<DurationRecord> to_temporal_duration_record(VM& vm, Value temporal_duration_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If Type(temporalDurationLike) is not Object, then // 1. If Type(temporalDurationLike) is not Object, then
if (!temporal_duration_like.is_object()) { if (!temporal_duration_like.is_object()) {
// a. Let string be ? ToString(temporalDurationLike). // a. Let string be ? ToString(temporalDurationLike).
auto string = TRY(temporal_duration_like.to_string(global_object)); auto string = TRY(temporal_duration_like.to_string(vm));
// b. Return ? ParseTemporalDurationString(string). // b. Return ? ParseTemporalDurationString(string).
return parse_temporal_duration_string(vm, string); return parse_temporal_duration_string(vm, string);
@ -566,7 +563,6 @@ ThrowCompletionOr<TimeDurationRecord> balance_duration(VM& vm, double days, doub
ThrowCompletionOr<DateDurationRecord> unbalance_duration_relative(VM& vm, double years, double months, double weeks, double days, String const& largest_unit, Value relative_to) ThrowCompletionOr<DateDurationRecord> unbalance_duration_relative(VM& vm, double years, double months, double weeks, double days, String const& largest_unit, Value relative_to)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If largestUnit is "year", or years, months, weeks, and days are all 0, then // 1. If largestUnit is "year", or years, months, weeks, and days are all 0, then
if (largest_unit == "year"sv || (years == 0 && months == 0 && weeks == 0 && days == 0)) { if (largest_unit == "year"sv || (years == 0 && months == 0 && weeks == 0 && days == 0)) {
@ -615,10 +611,10 @@ ThrowCompletionOr<DateDurationRecord> unbalance_duration_relative(VM& vm, double
} }
// b. Let dateAdd be ? GetMethod(calendar, "dateAdd"). // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd)); auto* date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
// c. Let dateUntil be ? GetMethod(calendar, "dateUntil"). // c. Let dateUntil be ? GetMethod(calendar, "dateUntil").
auto* date_until = TRY(Value(calendar).get_method(global_object, vm.names.dateUntil)); auto* date_until = TRY(Value(calendar).get_method(vm, vm.names.dateUntil));
// d. Repeat, while years ≠ 0, // d. Repeat, while years ≠ 0,
while (years != 0) { while (years != 0) {
@ -750,7 +746,6 @@ ThrowCompletionOr<DateDurationRecord> unbalance_duration_relative(VM& vm, double
ThrowCompletionOr<DateDurationRecord> balance_duration_relative(VM& vm, double years, double months, double weeks, double days, String const& largest_unit, Value relative_to_value) ThrowCompletionOr<DateDurationRecord> balance_duration_relative(VM& vm, double years, double months, double weeks, double days, String const& largest_unit, Value relative_to_value)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If largestUnit is not one of "year", "month", or "week", or years, months, weeks, and days are all 0, then // 1. If largestUnit is not one of "year", "month", or "week", or years, months, weeks, and days are all 0, then
if (!largest_unit.is_one_of("year"sv, "month"sv, "week"sv) || (years == 0 && months == 0 && weeks == 0 && days == 0)) { if (!largest_unit.is_one_of("year"sv, "month"sv, "week"sv) || (years == 0 && months == 0 && weeks == 0 && days == 0)) {
@ -848,13 +843,13 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(VM& vm, double y
} }
// i. Let dateAdd be ? GetMethod(calendar, "dateAdd"). // i. Let dateAdd be ? GetMethod(calendar, "dateAdd").
auto* date_add = TRY(Value(&calendar).get_method(global_object, vm.names.dateAdd)); auto* date_add = TRY(Value(&calendar).get_method(vm, vm.names.dateAdd));
// j. Set newRelativeTo to ? CalendarDateAdd(calendar, relativeTo, oneYear, undefined, dateAdd). // j. Set newRelativeTo to ? CalendarDateAdd(calendar, relativeTo, oneYear, undefined, dateAdd).
new_relative_to = TRY(calendar_date_add(vm, calendar, relative_to, *one_year, nullptr, date_add)); new_relative_to = TRY(calendar_date_add(vm, calendar, relative_to, *one_year, nullptr, date_add));
// k. Let dateUntil be ? GetMethod(calendar, "dateUntil"). // k. Let dateUntil be ? GetMethod(calendar, "dateUntil").
auto* date_until = TRY(Value(&calendar).get_method(global_object, vm.names.dateUntil)); auto* date_until = TRY(Value(&calendar).get_method(vm, vm.names.dateUntil));
// l. Let untilOptions be OrdinaryObjectCreate(null). // l. Let untilOptions be OrdinaryObjectCreate(null).
auto* until_options = Object::create(realm, nullptr); auto* until_options = Object::create(realm, nullptr);
@ -971,7 +966,6 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(VM& vm, double y
ThrowCompletionOr<DurationRecord> add_duration(VM& vm, double years1, double months1, double weeks1, double days1, double hours1, double minutes1, double seconds1, double milliseconds1, double microseconds1, double nanoseconds1, double years2, double months2, double weeks2, double days2, double hours2, double minutes2, double seconds2, double milliseconds2, double microseconds2, double nanoseconds2, Value relative_to_value) ThrowCompletionOr<DurationRecord> add_duration(VM& vm, double years1, double months1, double weeks1, double days1, double hours1, double minutes1, double seconds1, double milliseconds1, double microseconds1, double nanoseconds1, double years2, double months2, double weeks2, double days2, double hours2, double minutes2, double seconds2, double milliseconds2, double microseconds2, double nanoseconds2, Value relative_to_value)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
VERIFY(all_of(AK::Array { years1, months1, weeks1, days1, hours1, minutes1, seconds1, milliseconds1, microseconds1, nanoseconds1, years2, months2, weeks2, days2, hours2, minutes2, seconds2, milliseconds2, microseconds2, nanoseconds2 }, [](auto value) { return value == trunc(value); })); VERIFY(all_of(AK::Array { years1, months1, weeks1, days1, hours1, minutes1, seconds1, milliseconds1, microseconds1, nanoseconds1, years2, months2, weeks2, days2, hours2, minutes2, seconds2, milliseconds2, microseconds2, nanoseconds2 }, [](auto value) { return value == trunc(value); }));
@ -1014,7 +1008,7 @@ ThrowCompletionOr<DurationRecord> add_duration(VM& vm, double years1, double mon
auto* date_duration2 = MUST(create_temporal_duration(vm, years2, months2, weeks2, days2, 0, 0, 0, 0, 0, 0)); auto* date_duration2 = MUST(create_temporal_duration(vm, years2, months2, weeks2, days2, 0, 0, 0, 0, 0, 0));
// d. Let dateAdd be ? GetMethod(calendar, "dateAdd"). // d. Let dateAdd be ? GetMethod(calendar, "dateAdd").
auto* date_add = TRY(Value(&calendar).get_method(global_object, vm.names.dateAdd)); auto* date_add = TRY(Value(&calendar).get_method(vm, vm.names.dateAdd));
// e. Let intermediate be ? CalendarDateAdd(calendar, relativeTo, dateDuration1, undefined, dateAdd). // e. Let intermediate be ? CalendarDateAdd(calendar, relativeTo, dateDuration1, undefined, dateAdd).
auto* intermediate = TRY(calendar_date_add(vm, calendar, &relative_to, *date_duration1, nullptr, date_add)); auto* intermediate = TRY(calendar_date_add(vm, calendar, &relative_to, *date_duration1, nullptr, date_add));
@ -1102,7 +1096,6 @@ ThrowCompletionOr<ZonedDateTime*> move_relative_zoned_date_time(VM& vm, ZonedDat
ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, u32 increment, StringView unit, StringView rounding_mode, Object* relative_to_object) ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, u32 increment, StringView unit, StringView rounding_mode, Object* relative_to_object)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
Object* calendar = nullptr; Object* calendar = nullptr;
double fractional_seconds = 0; double fractional_seconds = 0;
@ -1196,7 +1189,7 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
auto* years_duration = MUST(create_temporal_duration(vm, years, 0, 0, 0, 0, 0, 0, 0, 0, 0)); auto* years_duration = MUST(create_temporal_duration(vm, years, 0, 0, 0, 0, 0, 0, 0, 0, 0));
// b. Let dateAdd be ? GetMethod(calendar, "dateAdd"). // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd)); auto* date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
// c. Let yearsLater be ? CalendarDateAdd(calendar, relativeTo, yearsDuration, undefined, dateAdd). // c. Let yearsLater be ? CalendarDateAdd(calendar, relativeTo, yearsDuration, undefined, dateAdd).
auto* years_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_duration, nullptr, date_add)); auto* years_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_duration, nullptr, date_add));
@ -1286,7 +1279,7 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
auto* years_months = MUST(create_temporal_duration(vm, years, months, 0, 0, 0, 0, 0, 0, 0, 0)); auto* years_months = MUST(create_temporal_duration(vm, years, months, 0, 0, 0, 0, 0, 0, 0, 0));
// b. Let dateAdd be ? GetMethod(calendar, "dateAdd"). // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd)); auto* date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
// c. Let yearsMonthsLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonths, undefined, dateAdd). // c. Let yearsMonthsLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonths, undefined, dateAdd).
auto* years_months_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_months, nullptr, date_add)); auto* years_months_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_months, nullptr, date_add));

View file

@ -75,9 +75,6 @@ ThrowCompletionOr<Instant*> create_temporal_instant(VM& vm, BigInt const& epoch_
// 8.5.3 ToTemporalInstant ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalinstant // 8.5.3 ToTemporalInstant ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalinstant
ThrowCompletionOr<Instant*> to_temporal_instant(VM& vm, Value item) ThrowCompletionOr<Instant*> to_temporal_instant(VM& vm, Value item)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If Type(item) is Object, then // 1. If Type(item) is Object, then
if (item.is_object()) { if (item.is_object()) {
// a. If item has an [[InitializedTemporalInstant]] internal slot, then // a. If item has an [[InitializedTemporalInstant]] internal slot, then
@ -96,7 +93,7 @@ ThrowCompletionOr<Instant*> to_temporal_instant(VM& vm, Value item)
} }
// 2. Let string be ? ToString(item). // 2. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// 3. Let epochNanoseconds be ? ParseTemporalInstant(string). // 3. Let epochNanoseconds be ? ParseTemporalInstant(string).
auto* epoch_nanoseconds = TRY(parse_temporal_instant(vm, string)); auto* epoch_nanoseconds = TRY(parse_temporal_instant(vm, string));

View file

@ -52,10 +52,9 @@ ThrowCompletionOr<Value> InstantConstructor::call()
ThrowCompletionOr<Object*> InstantConstructor::construct(FunctionObject& new_target) ThrowCompletionOr<Object*> InstantConstructor::construct(FunctionObject& new_target)
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto& global_object = this->global_object();
// 2. Let epochNanoseconds be ? ToBigInt(epochNanoseconds). // 2. Let epochNanoseconds be ? ToBigInt(epochNanoseconds).
auto* epoch_nanoseconds = TRY(vm.argument(0).to_bigint(global_object)); auto* epoch_nanoseconds = TRY(vm.argument(0).to_bigint(vm));
// 3. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception. // 3. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception.
if (!is_valid_epoch_nanoseconds(*epoch_nanoseconds)) if (!is_valid_epoch_nanoseconds(*epoch_nanoseconds))
@ -84,7 +83,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from)
JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_seconds) JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_seconds)
{ {
// 1. Set epochSeconds to ? ToNumber(epochSeconds). // 1. Set epochSeconds to ? ToNumber(epochSeconds).
auto epoch_seconds_value = TRY(vm.argument(0).to_number(global_object)); auto epoch_seconds_value = TRY(vm.argument(0).to_number(vm));
// 2. Set epochSeconds to ? NumberToBigInt(epochSeconds). // 2. Set epochSeconds to ? NumberToBigInt(epochSeconds).
auto* epoch_seconds = TRY(number_to_bigint(global_object, epoch_seconds_value)); auto* epoch_seconds = TRY(number_to_bigint(global_object, epoch_seconds_value));
@ -104,7 +103,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_seconds)
JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_milliseconds) JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_milliseconds)
{ {
// 1. Set epochMilliseconds to ? ToNumber(epochMilliseconds). // 1. Set epochMilliseconds to ? ToNumber(epochMilliseconds).
auto epoch_milliseconds_value = TRY(vm.argument(0).to_number(global_object)); auto epoch_milliseconds_value = TRY(vm.argument(0).to_number(vm));
// 2. Set epochMilliseconds to ? NumberToBigInt(epochMilliseconds). // 2. Set epochMilliseconds to ? NumberToBigInt(epochMilliseconds).
auto* epoch_milliseconds = TRY(number_to_bigint(global_object, epoch_milliseconds_value)); auto* epoch_milliseconds = TRY(number_to_bigint(global_object, epoch_milliseconds_value));
@ -124,7 +123,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_milliseconds)
JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_microseconds) JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_microseconds)
{ {
// 1. Set epochMicroseconds to ? ToBigInt(epochMicroseconds). // 1. Set epochMicroseconds to ? ToBigInt(epochMicroseconds).
auto* epoch_microseconds = TRY(vm.argument(0).to_bigint(global_object)); auto* epoch_microseconds = TRY(vm.argument(0).to_bigint(vm));
// 2. Let epochNanoseconds be epochMicroseconds × 1000. // 2. Let epochNanoseconds be epochMicroseconds × 1000.
auto* epoch_nanoseconds = js_bigint(vm, epoch_microseconds->big_integer().multiplied_by(Crypto::UnsignedBigInteger { 1'000 })); auto* epoch_nanoseconds = js_bigint(vm, epoch_microseconds->big_integer().multiplied_by(Crypto::UnsignedBigInteger { 1'000 }));
@ -141,7 +140,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_microseconds)
JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_nanoseconds) JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_nanoseconds)
{ {
// 1. Set epochNanoseconds to ? ToBigInt(epochNanoseconds). // 1. Set epochNanoseconds to ? ToBigInt(epochNanoseconds).
auto* epoch_nanoseconds = TRY(vm.argument(0).to_bigint(global_object)); auto* epoch_nanoseconds = TRY(vm.argument(0).to_bigint(vm));
// 2. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception. // 2. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception.
if (!is_valid_epoch_nanoseconds(*epoch_nanoseconds)) if (!is_valid_epoch_nanoseconds(*epoch_nanoseconds))

View file

@ -83,9 +83,6 @@ ThrowCompletionOr<PlainDate*> create_temporal_date(VM& vm, i32 iso_year, u8 iso_
// 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate // 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate
ThrowCompletionOr<PlainDate*> to_temporal_date(VM& vm, Value item, Object const* options) ThrowCompletionOr<PlainDate*> to_temporal_date(VM& vm, Value item, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Assert: Type(options) is Object or Undefined. // 2. Assert: Type(options) is Object or Undefined.
@ -143,7 +140,7 @@ ThrowCompletionOr<PlainDate*> to_temporal_date(VM& vm, Value item, Object const*
(void)TRY(to_temporal_overflow(vm, options)); (void)TRY(to_temporal_overflow(vm, options));
// 5. Let string be ? ToString(item). // 5. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// 6. Let result be ? ParseTemporalDateString(string). // 6. Let result be ? ParseTemporalDateString(string).
auto result = TRY(parse_temporal_date_string(vm, string)); auto result = TRY(parse_temporal_date_string(vm, string));
@ -419,9 +416,6 @@ String pad_iso_year(i32 y)
// 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring // 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring
ThrowCompletionOr<String> temporal_date_to_string(VM& vm, PlainDate& temporal_date, StringView show_calendar) ThrowCompletionOr<String> temporal_date_to_string(VM& vm, PlainDate& temporal_date, StringView show_calendar)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(temporalDate) is Object. // 1. Assert: Type(temporalDate) is Object.
// 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot. // 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot.
@ -435,7 +429,7 @@ ThrowCompletionOr<String> temporal_date_to_string(VM& vm, PlainDate& temporal_da
auto day = String::formatted("{:02}", temporal_date.iso_day()); auto day = String::formatted("{:02}", temporal_date.iso_day());
// 6. Let calendarID be ? ToString(temporalDate.[[Calendar]]). // 6. Let calendarID be ? ToString(temporalDate.[[Calendar]]).
auto calendar_id = TRY(Value(&temporal_date.calendar()).to_string(global_object)); auto calendar_id = TRY(Value(&temporal_date.calendar()).to_string(vm));
// 7. Let calendar be ! FormatCalendarAnnotation(calendarID, showCalendar). // 7. Let calendar be ! FormatCalendarAnnotation(calendarID, showCalendar).
auto calendar = format_calendar_annotation(calendar_id, show_calendar); auto calendar = format_calendar_annotation(calendar_id, show_calendar);

View file

@ -127,9 +127,6 @@ ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(VM& vm, Objec
// 5.5.4 ToTemporalDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetime // 5.5.4 ToTemporalDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetime
ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(VM& vm, Value item, Object const* options) ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(VM& vm, Value item, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Assert: Type(options) is Object or Undefined. // 2. Assert: Type(options) is Object or Undefined.
@ -189,7 +186,7 @@ ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(VM& vm, Value item, Obje
(void)TRY(to_temporal_overflow(vm, options)); (void)TRY(to_temporal_overflow(vm, options));
// b. Let string be ? ToString(item). // b. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// c. Let result be ? ParseTemporalDateTimeString(string). // c. Let result be ? ParseTemporalDateTimeString(string).
result = TRY(parse_temporal_date_time_string(vm, string)); result = TRY(parse_temporal_date_time_string(vm, string));
@ -274,9 +271,6 @@ ThrowCompletionOr<PlainDateTime*> create_temporal_date_time(VM& vm, i32 iso_year
// 5.5.7 TemporalDateTimeToString ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar, precision, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetimetostring // 5.5.7 TemporalDateTimeToString ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar, precision, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetimetostring
ThrowCompletionOr<String> temporal_date_time_to_string(VM& vm, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Value calendar, Variant<StringView, u8> const& precision, StringView show_calendar) ThrowCompletionOr<String> temporal_date_time_to_string(VM& vm, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Value calendar, Variant<StringView, u8> const& precision, StringView show_calendar)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers. // 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
// 2. Let year be ! PadISOYear(isoYear). // 2. Let year be ! PadISOYear(isoYear).
@ -289,7 +283,7 @@ ThrowCompletionOr<String> temporal_date_time_to_string(VM& vm, i32 iso_year, u8
auto seconds = format_seconds_string_part(second, millisecond, microsecond, nanosecond, precision); auto seconds = format_seconds_string_part(second, millisecond, microsecond, nanosecond, precision);
// 8. Let calendarID be ? ToString(calendar). // 8. Let calendarID be ? ToString(calendar).
auto calendar_id = TRY(calendar.to_string(global_object)); auto calendar_id = TRY(calendar.to_string(vm));
// 9. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar). // 9. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
auto calendar_string = format_calendar_annotation(calendar_id, show_calendar); auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);

View file

@ -36,9 +36,6 @@ void PlainMonthDay::visit_edges(Visitor& visitor)
// 10.5.1 ToTemporalMonthDay ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalmonthday // 10.5.1 ToTemporalMonthDay ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalmonthday
ThrowCompletionOr<PlainMonthDay*> to_temporal_month_day(VM& vm, Value item, Object const* options) ThrowCompletionOr<PlainMonthDay*> to_temporal_month_day(VM& vm, Value item, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Assert: Type(options) is Object or Undefined. // 2. Assert: Type(options) is Object or Undefined.
@ -122,7 +119,7 @@ ThrowCompletionOr<PlainMonthDay*> to_temporal_month_day(VM& vm, Value item, Obje
(void)TRY(to_temporal_overflow(vm, options)); (void)TRY(to_temporal_overflow(vm, options));
// 6. Let string be ? ToString(item). // 6. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// 7. Let result be ? ParseTemporalMonthDayString(string). // 7. Let result be ? ParseTemporalMonthDayString(string).
auto result = TRY(parse_temporal_month_day_string(vm, string)); auto result = TRY(parse_temporal_month_day_string(vm, string));
@ -179,9 +176,6 @@ ThrowCompletionOr<PlainMonthDay*> create_temporal_month_day(VM& vm, u8 iso_month
// 10.5.3 TemporalMonthDayToString ( monthDay, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalmonthdaytostring // 10.5.3 TemporalMonthDayToString ( monthDay, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalmonthdaytostring
ThrowCompletionOr<String> temporal_month_day_to_string(VM& vm, PlainMonthDay& month_day, StringView show_calendar) ThrowCompletionOr<String> temporal_month_day_to_string(VM& vm, PlainMonthDay& month_day, StringView show_calendar)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(monthDay) is Object. // 1. Assert: Type(monthDay) is Object.
// 2. Assert: monthDay has an [[InitializedTemporalMonthDay]] internal slot. // 2. Assert: monthDay has an [[InitializedTemporalMonthDay]] internal slot.
@ -191,7 +185,7 @@ ThrowCompletionOr<String> temporal_month_day_to_string(VM& vm, PlainMonthDay& mo
auto result = String::formatted("{:02}-{:02}", month_day.iso_month(), month_day.iso_day()); auto result = String::formatted("{:02}-{:02}", month_day.iso_month(), month_day.iso_day());
// 6. Let calendarID be ? ToString(monthDay.[[Calendar]]). // 6. Let calendarID be ? ToString(monthDay.[[Calendar]]).
auto calendar_id = TRY(Value(&month_day.calendar()).to_string(global_object)); auto calendar_id = TRY(Value(&month_day.calendar()).to_string(vm));
// 7. If showCalendar is "always" or if calendarID is not "iso8601", then // 7. If showCalendar is "always" or if calendarID is not "iso8601", then
if (show_calendar == "always"sv || calendar_id != "iso8601"sv) { if (show_calendar == "always"sv || calendar_id != "iso8601"sv) {

View file

@ -77,9 +77,6 @@ TimeDurationRecord difference_time(VM& vm, u8 hour1, u8 minute1, u8 second1, u16
// 4.5.2 ToTemporalTime ( item [ , overflow ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltime // 4.5.2 ToTemporalTime ( item [ , overflow ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltime
ThrowCompletionOr<PlainTime*> to_temporal_time(VM& vm, Value item, Optional<StringView> overflow) ThrowCompletionOr<PlainTime*> to_temporal_time(VM& vm, Value item, Optional<StringView> overflow)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If overflow is not present, set overflow to "constrain". // 1. If overflow is not present, set overflow to "constrain".
if (!overflow.has_value()) if (!overflow.has_value())
overflow = "constrain"sv; overflow = "constrain"sv;
@ -124,7 +121,7 @@ ThrowCompletionOr<PlainTime*> to_temporal_time(VM& vm, Value item, Optional<Stri
auto* calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object)); auto* calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object));
// e. If ? ToString(calendar) is not "iso8601", then // e. If ? ToString(calendar) is not "iso8601", then
auto calendar_identifier = TRY(Value(calendar).to_string(global_object)); auto calendar_identifier = TRY(Value(calendar).to_string(vm));
if (calendar_identifier != "iso8601"sv) { if (calendar_identifier != "iso8601"sv) {
// i. Throw a RangeError exception. // i. Throw a RangeError exception.
return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, calendar_identifier); return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, calendar_identifier);
@ -139,7 +136,7 @@ ThrowCompletionOr<PlainTime*> to_temporal_time(VM& vm, Value item, Optional<Stri
// 4. Else, // 4. Else,
else { else {
// a. Let string be ? ToString(item). // a. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// b. Let result be ? ParseTemporalTimeString(string). // b. Let result be ? ParseTemporalTimeString(string).
result = TRY(parse_temporal_time_string(vm, string)); result = TRY(parse_temporal_time_string(vm, string));

View file

@ -35,9 +35,6 @@ void PlainYearMonth::visit_edges(Visitor& visitor)
// 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth // 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth
ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(VM& vm, Value item, Object const* options) ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(VM& vm, Value item, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Assert: Type(options) is Object or Undefined. // 2. Assert: Type(options) is Object or Undefined.
@ -68,7 +65,7 @@ ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(VM& vm, Value item, Ob
(void)TRY(to_temporal_overflow(vm, options)); (void)TRY(to_temporal_overflow(vm, options));
// 5. Let string be ? ToString(item). // 5. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// 6. Let result be ? ParseTemporalYearMonthString(string). // 6. Let result be ? ParseTemporalYearMonthString(string).
auto result = TRY(parse_temporal_year_month_string(vm, string)); auto result = TRY(parse_temporal_year_month_string(vm, string));
@ -220,9 +217,6 @@ ThrowCompletionOr<PlainYearMonth*> create_temporal_year_month(VM& vm, i32 iso_ye
// 9.5.7 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring // 9.5.7 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring
ThrowCompletionOr<String> temporal_year_month_to_string(VM& vm, PlainYearMonth& year_month, StringView show_calendar) ThrowCompletionOr<String> temporal_year_month_to_string(VM& vm, PlainYearMonth& year_month, StringView show_calendar)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Assert: Type(yearMonth) is Object. // 1. Assert: Type(yearMonth) is Object.
// 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot. // 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot.
@ -232,7 +226,7 @@ ThrowCompletionOr<String> temporal_year_month_to_string(VM& vm, PlainYearMonth&
auto result = String::formatted("{}-{:02}", pad_iso_year(year_month.iso_year()), year_month.iso_month()); auto result = String::formatted("{}-{:02}", pad_iso_year(year_month.iso_year()), year_month.iso_month());
// 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]). // 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]).
auto calendar_id = TRY(Value(&year_month.calendar()).to_string(global_object)); auto calendar_id = TRY(Value(&year_month.calendar()).to_string(vm));
// 7. If showCalendar is "always" or if calendarID is not "iso8601", then // 7. If showCalendar is "always" or if calendarID is not "iso8601", then
if (show_calendar == "always"sv || calendar_id != "iso8601") { if (show_calendar == "always"sv || calendar_id != "iso8601") {
@ -311,7 +305,6 @@ ThrowCompletionOr<Duration*> difference_temporal_plain_year_month(VM& vm, Differ
ThrowCompletionOr<PlainYearMonth*> add_duration_to_or_subtract_duration_from_plain_year_month(VM& vm, ArithmeticOperation operation, PlainYearMonth& year_month, Value temporal_duration_like, Value options_value) ThrowCompletionOr<PlainYearMonth*> add_duration_to_or_subtract_duration_from_plain_year_month(VM& vm, ArithmeticOperation operation, PlainYearMonth& year_month, Value temporal_duration_like, Value options_value)
{ {
auto& realm = *vm.current_realm(); auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. Let duration be ? ToTemporalDuration(temporalDurationLike). // 1. Let duration be ? ToTemporalDuration(temporalDurationLike).
auto* duration = TRY(to_temporal_duration(vm, temporal_duration_like)); auto* duration = TRY(to_temporal_duration(vm, temporal_duration_like));
@ -373,7 +366,7 @@ ThrowCompletionOr<PlainYearMonth*> add_duration_to_or_subtract_duration_from_pla
// 16. For each element entry of entries, do // 16. For each element entry of entries, do
for (auto& entry : entries) { for (auto& entry : entries) {
auto key = MUST(entry.as_array().get_without_side_effects(0).to_property_key(global_object)); auto key = MUST(entry.as_array().get_without_side_effects(0).to_property_key(vm));
auto value = entry.as_array().get_without_side_effects(1); auto value = entry.as_array().get_without_side_effects(1);
// a. Perform ! CreateDataPropertyOrThrow(optionsCopy, entry[0], entry[1]). // a. Perform ! CreateDataPropertyOrThrow(optionsCopy, entry[0], entry[1]).

View file

@ -418,9 +418,6 @@ String format_iso_time_zone_offset_string(double offset_nanoseconds)
// 11.6.10 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone // 11.6.10 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
ThrowCompletionOr<Object*> to_temporal_time_zone(VM& vm, Value temporal_time_zone_like) ThrowCompletionOr<Object*> to_temporal_time_zone(VM& vm, Value temporal_time_zone_like)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If Type(temporalTimeZoneLike) is Object, then // 1. If Type(temporalTimeZoneLike) is Object, then
if (temporal_time_zone_like.is_object()) { if (temporal_time_zone_like.is_object()) {
// a. If temporalTimeZoneLike has an [[InitializedTemporalZonedDateTime]] internal slot, then // a. If temporalTimeZoneLike has an [[InitializedTemporalZonedDateTime]] internal slot, then
@ -444,7 +441,7 @@ ThrowCompletionOr<Object*> to_temporal_time_zone(VM& vm, Value temporal_time_zon
} }
// 2. Let identifier be ? ToString(temporalTimeZoneLike). // 2. Let identifier be ? ToString(temporalTimeZoneLike).
auto identifier = TRY(temporal_time_zone_like.to_string(global_object)); auto identifier = TRY(temporal_time_zone_like.to_string(vm));
// 3. Let parseResult be ? ParseTemporalTimeZoneString(identifier). // 3. Let parseResult be ? ParseTemporalTimeZoneString(identifier).
auto parse_result = TRY(parse_temporal_time_zone_string(vm, identifier)); auto parse_result = TRY(parse_temporal_time_zone_string(vm, identifier));
@ -483,7 +480,7 @@ ThrowCompletionOr<double> get_offset_nanoseconds_for(VM& vm, Value time_zone, In
auto& global_object = realm.global_object(); auto& global_object = realm.global_object();
// 1. Let getOffsetNanosecondsFor be ? GetMethod(timeZone, "getOffsetNanosecondsFor"). // 1. Let getOffsetNanosecondsFor be ? GetMethod(timeZone, "getOffsetNanosecondsFor").
auto* get_offset_nanoseconds_for = TRY(time_zone.get_method(global_object, vm.names.getOffsetNanosecondsFor)); auto* get_offset_nanoseconds_for = TRY(time_zone.get_method(vm, vm.names.getOffsetNanosecondsFor));
// 2. Let offsetNanoseconds be ? Call(getOffsetNanosecondsFor, timeZone, « instant »). // 2. Let offsetNanoseconds be ? Call(getOffsetNanosecondsFor, timeZone, « instant »).
auto offset_nanoseconds_value = TRY(call(global_object, get_offset_nanoseconds_for, time_zone, &instant)); auto offset_nanoseconds_value = TRY(call(global_object, get_offset_nanoseconds_for, time_zone, &instant));
@ -674,7 +671,7 @@ ThrowCompletionOr<MarkedVector<Instant*>> get_possible_instants_for(VM& vm, Valu
// 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot. // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
// 2. Let possibleInstants be ? Invoke(timeZone, "getPossibleInstantsFor", « dateTime »). // 2. Let possibleInstants be ? Invoke(timeZone, "getPossibleInstantsFor", « dateTime »).
auto possible_instants = TRY(time_zone.invoke(global_object, vm.names.getPossibleInstantsFor, &date_time)); auto possible_instants = TRY(time_zone.invoke(vm, vm.names.getPossibleInstantsFor, &date_time));
// 3. Let iteratorRecord be ? GetIterator(possibleInstants, sync). // 3. Let iteratorRecord be ? GetIterator(possibleInstants, sync).
auto iterator = TRY(get_iterator(global_object, possible_instants, IteratorHint::Sync)); auto iterator = TRY(get_iterator(global_object, possible_instants, IteratorHint::Sync));
@ -716,18 +713,15 @@ ThrowCompletionOr<MarkedVector<Instant*>> get_possible_instants_for(VM& vm, Valu
// 11.6.17 TimeZoneEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-timezoneequals // 11.6.17 TimeZoneEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-timezoneequals
ThrowCompletionOr<bool> time_zone_equals(VM& vm, Object& one, Object& two) ThrowCompletionOr<bool> time_zone_equals(VM& vm, Object& one, Object& two)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If one and two are the same Object value, return true. // 1. If one and two are the same Object value, return true.
if (&one == &two) if (&one == &two)
return true; return true;
// 2. Let timeZoneOne be ? ToString(one). // 2. Let timeZoneOne be ? ToString(one).
auto time_zone_one = TRY(Value(&one).to_string(global_object)); auto time_zone_one = TRY(Value(&one).to_string(vm));
// 3. Let timeZoneTwo be ? ToString(two). // 3. Let timeZoneTwo be ? ToString(two).
auto time_zone_two = TRY(Value(&two).to_string(global_object)); auto time_zone_two = TRY(Value(&two).to_string(vm));
// 4. If timeZoneOne is timeZoneTwo, return true. // 4. If timeZoneOne is timeZoneTwo, return true.
if (time_zone_one == time_zone_two) if (time_zone_one == time_zone_two)

View file

@ -45,10 +45,9 @@ ThrowCompletionOr<Value> TimeZoneConstructor::call()
ThrowCompletionOr<Object*> TimeZoneConstructor::construct(FunctionObject& new_target) ThrowCompletionOr<Object*> TimeZoneConstructor::construct(FunctionObject& new_target)
{ {
auto& vm = this->vm(); auto& vm = this->vm();
auto& global_object = this->global_object();
// 2. Set identifier to ? ToString(identifier). // 2. Set identifier to ? ToString(identifier).
auto identifier = TRY(vm.argument(0).to_string(global_object)); auto identifier = TRY(vm.argument(0).to_string(vm));
// 3. Let parseResult be ParseText(StringToCodePoints(identifier), TimeZoneNumericUTCOffset). // 3. Let parseResult be ParseText(StringToCodePoints(identifier), TimeZoneNumericUTCOffset).
// 4. If parseResult is a List of errors, then // 4. If parseResult is a List of errors, then

View file

@ -52,7 +52,7 @@ JS_DEFINE_NATIVE_FUNCTION(TimeZonePrototype::id_getter)
auto* time_zone = TRY(typed_this_object(vm)); auto* time_zone = TRY(typed_this_object(vm));
// 3. Return ? ToString(timeZone). // 3. Return ? ToString(timeZone).
return js_string(vm, TRY(Value(time_zone).to_string(global_object))); return js_string(vm, TRY(Value(time_zone).to_string(vm)));
} }
// 11.4.4 Temporal.TimeZone.prototype.getOffsetNanosecondsFor ( instant ), https://tc39.es/proposal-temporal/#sec-temporal.timezone.prototype.getoffsetnanosecondsfor // 11.4.4 Temporal.TimeZone.prototype.getOffsetNanosecondsFor ( instant ), https://tc39.es/proposal-temporal/#sec-temporal.timezone.prototype.getoffsetnanosecondsfor
@ -243,7 +243,7 @@ JS_DEFINE_NATIVE_FUNCTION(TimeZonePrototype::to_json)
auto* time_zone = TRY(typed_this_object(vm)); auto* time_zone = TRY(typed_this_object(vm));
// 3. Return ? ToString(timeZone). // 3. Return ? ToString(timeZone).
return js_string(vm, TRY(Value(time_zone).to_string(global_object))); return js_string(vm, TRY(Value(time_zone).to_string(vm)));
} }
} }

View file

@ -120,9 +120,6 @@ ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(VM& vm, i32 year
// 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime // 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime
ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(VM& vm, Value item, Object const* options) ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(VM& vm, Value item, Object const* options)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If options is not present, set options to undefined. // 1. If options is not present, set options to undefined.
// 2. Assert: Type(options) is Object or Undefined. // 2. Assert: Type(options) is Object or Undefined.
@ -179,7 +176,7 @@ ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(VM& vm, Value item
// k. Else, // k. Else,
else { else {
// i. Set offsetString to ? ToString(offsetString). // i. Set offsetString to ? ToString(offsetString).
offset_string = TRY(offset_string_value.to_string(global_object)); offset_string = TRY(offset_string_value.to_string(vm));
} }
// l. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options). // l. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
@ -191,7 +188,7 @@ ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(VM& vm, Value item
(void)TRY(to_temporal_overflow(vm, options)); (void)TRY(to_temporal_overflow(vm, options));
// b. Let string be ? ToString(item). // b. Let string be ? ToString(item).
auto string = TRY(item.to_string(global_object)); auto string = TRY(item.to_string(vm));
// c. Let result be ? ParseTemporalZonedDateTimeString(string). // c. Let result be ? ParseTemporalZonedDateTimeString(string).
auto parsed_result = TRY(parse_temporal_zoned_date_time_string(vm, string)); auto parsed_result = TRY(parse_temporal_zoned_date_time_string(vm, string));
@ -293,9 +290,6 @@ ThrowCompletionOr<ZonedDateTime*> create_temporal_zoned_date_time(VM& vm, BigInt
// 6.5.4 TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar, showTimeZone, showOffset [ , increment, unit, roundingMode ] ), https://tc39.es/proposal-temporal/#sec-temporal-temporalzoneddatetimetostring // 6.5.4 TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar, showTimeZone, showOffset [ , increment, unit, roundingMode ] ), https://tc39.es/proposal-temporal/#sec-temporal-temporalzoneddatetimetostring
ThrowCompletionOr<String> temporal_zoned_date_time_to_string(VM& vm, ZonedDateTime& zoned_date_time, Variant<StringView, u8> const& precision, StringView show_calendar, StringView show_time_zone, StringView show_offset, Optional<u64> increment, Optional<StringView> unit, Optional<StringView> rounding_mode) ThrowCompletionOr<String> temporal_zoned_date_time_to_string(VM& vm, ZonedDateTime& zoned_date_time, Variant<StringView, u8> const& precision, StringView show_calendar, StringView show_time_zone, StringView show_offset, Optional<u64> increment, Optional<StringView> unit, Optional<StringView> rounding_mode)
{ {
auto& realm = *vm.current_realm();
auto& global_object = realm.global_object();
// 1. If increment is not present, set increment to 1. // 1. If increment is not present, set increment to 1.
if (!increment.has_value()) if (!increment.has_value())
increment = 1; increment = 1;
@ -352,14 +346,14 @@ ThrowCompletionOr<String> temporal_zoned_date_time_to_string(VM& vm, ZonedDateTi
// 13. Else, // 13. Else,
else { else {
// a. Let timeZoneID be ? ToString(timeZone). // a. Let timeZoneID be ? ToString(timeZone).
auto time_zone_id = TRY(Value(&time_zone).to_string(global_object)); auto time_zone_id = TRY(Value(&time_zone).to_string(vm));
// b. Let timeZoneString be the string-concatenation of the code unit 0x005B (LEFT SQUARE BRACKET), timeZoneID, and the code unit 0x005D (RIGHT SQUARE BRACKET). // b. Let timeZoneString be the string-concatenation of the code unit 0x005B (LEFT SQUARE BRACKET), timeZoneID, and the code unit 0x005D (RIGHT SQUARE BRACKET).
time_zone_string = String::formatted("[{}]", time_zone_id); time_zone_string = String::formatted("[{}]", time_zone_id);
} }
// 14. Let calendarID be ? ToString(zonedDateTime.[[Calendar]]). // 14. Let calendarID be ? ToString(zonedDateTime.[[Calendar]]).
auto calendar_id = TRY(Value(&zoned_date_time.calendar()).to_string(global_object)); auto calendar_id = TRY(Value(&zoned_date_time.calendar()).to_string(vm));
// 15. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar). // 15. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
auto calendar_string = format_calendar_annotation(calendar_id, show_calendar); auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);

Some files were not shown because too many files have changed in this diff Show more