From 88814acbd39ba252167e48f48f5b938df142065b Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Thu, 16 Feb 2023 14:09:11 -0500 Subject: [PATCH] LibJS+Everywhere: Convert JS::Error to String This includes an Error::create overload to create an Error from a UTF-8 StringView. If creating a String from that view fails, the factory will return an OOM InternalError instead. VM::throw_completion can also make use of this overload via its perfect forwarding. --- .../BindingsGenerator/IDLGenerators.cpp | 2 +- Meta/Lagom/Wasm/js_repl.cpp | 31 ++++++++++------ Tests/LibJS/test262-runner.cpp | 12 +++++-- Tests/LibWasm/test-wasm.cpp | 34 ++++++++++-------- .../Spreadsheet/JSIntegration.cpp | 36 +++++++++---------- .../Applications/Spreadsheet/Spreadsheet.cpp | 2 +- Userland/Libraries/LibJS/AST.cpp | 6 ++-- Userland/Libraries/LibJS/Bytecode/Op.cpp | 26 +++++++------- .../LibJS/Contrib/Test262/$262Object.cpp | 2 +- .../LibJS/Runtime/AbstractOperations.cpp | 4 +-- .../AsyncFromSyncIteratorPrototype.cpp | 5 +-- .../Runtime/ECMAScriptFunctionObject.cpp | 2 +- Userland/Libraries/LibJS/Runtime/Error.cpp | 32 +++++++++++------ Userland/Libraries/LibJS/Runtime/Error.h | 27 +++++++------- .../LibJS/Runtime/ErrorPrototype.cpp | 2 +- .../LibJS/Runtime/FunctionConstructor.cpp | 6 ++-- Userland/Libraries/LibJS/Runtime/Promise.cpp | 4 +-- .../Libraries/LibJS/Runtime/ShadowRealm.cpp | 4 +-- Userland/Libraries/LibJS/Runtime/VM.cpp | 8 ++--- Userland/Libraries/LibJS/Runtime/VM.h | 11 ++++-- .../Libraries/LibTest/JavaScriptTestRunner.h | 2 +- .../Libraries/LibWeb/Bindings/FetchMethod.cpp | 2 +- .../LibWeb/Bindings/MainThreadVM.cpp | 2 +- Userland/Libraries/LibWeb/Fetch/Body.cpp | 2 +- .../Libraries/LibWeb/Fetch/FetchMethod.cpp | 2 +- .../Fetch/Infrastructure/HTTP/Bodies.cpp | 2 +- Userland/Libraries/LibWeb/HTML/Location.cpp | 2 +- .../LibWeb/HTML/Scripting/ClassicScript.cpp | 2 +- .../HTML/Scripting/ExceptionReporter.cpp | 2 +- Userland/Libraries/LibWeb/HTML/Window.cpp | 4 +-- .../WebAssemblyMemoryConstructor.cpp | 2 +- .../WebAssemblyMemoryPrototype.cpp | 2 +- .../LibWeb/WebAssembly/WebAssemblyObject.cpp | 27 +++++++------- .../WebAssemblyTableConstructor.cpp | 4 +-- .../WebAssembly/WebAssemblyTablePrototype.cpp | 6 ++-- Userland/Utilities/js.cpp | 30 +++++++++------- 36 files changed, 198 insertions(+), 151 deletions(-) diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp index a19261dbc4f..d0d053bed68 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp @@ -1216,7 +1216,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter // 19. Throw a TypeError. // FIXME: Replace the error message with something more descriptive. union_generator.append(R"~~~( - return vm.throw_completion("No union types matched"); + return vm.throw_completion("No union types matched"sv); )~~~"); } diff --git a/Meta/Lagom/Wasm/js_repl.cpp b/Meta/Lagom/Wasm/js_repl.cpp index 2db5097a213..5e1fa7ad9aa 100644 --- a/Meta/Lagom/Wasm/js_repl.cpp +++ b/Meta/Lagom/Wasm/js_repl.cpp @@ -107,7 +107,7 @@ static bool s_opt_bytecode = false; static bool s_as_module = false; static bool s_print_last_result = false; -static bool parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name) +static ErrorOr parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name) { enum class ReturnEarly { No, @@ -116,14 +116,14 @@ static bool parse_and_run(JS::Interpreter& interpreter, StringView source, Strin JS::ThrowCompletionOr result { JS::js_undefined() }; - auto run_script_or_module = [&](auto& script_or_module) { + auto run_script_or_module = [&](auto& script_or_module) -> ErrorOr { if (s_dump_ast) script_or_module->parse_node().dump(0); if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) { auto executable_result = JS::Bytecode::Generator::generate(script_or_module->parse_node()); if (executable_result.is_error()) { - result = g_vm->throw_completion(executable_result.error().to_deprecated_string()); + result = g_vm->throw_completion(TRY(executable_result.error().to_string())); return ReturnEarly::No; } @@ -161,10 +161,12 @@ static bool parse_and_run(JS::Interpreter& interpreter, StringView source, Strin auto hint = error.source_location_hint(source); if (!hint.is_empty()) displayln("{}", hint); - displayln("{}", error.to_deprecated_string()); - result = interpreter.vm().throw_completion(error.to_deprecated_string()); + + auto error_string = TRY(error.to_string()); + displayln("{}", error_string); + result = interpreter.vm().throw_completion(move(error_string)); } else { - auto return_early = run_script_or_module(script_or_error.value()); + auto return_early = TRY(run_script_or_module(script_or_error.value())); if (return_early == ReturnEarly::Yes) return true; } @@ -175,10 +177,12 @@ static bool parse_and_run(JS::Interpreter& interpreter, StringView source, Strin auto hint = error.source_location_hint(source); if (!hint.is_empty()) displayln("{}", hint); - displayln(error.to_deprecated_string()); - result = interpreter.vm().throw_completion(error.to_deprecated_string()); + + auto error_string = TRY(error.to_string()); + displayln("{}", error_string); + result = interpreter.vm().throw_completion(move(error_string)); } else { - auto return_early = run_script_or_module(module_or_error.value()); + auto return_early = TRY(run_script_or_module(module_or_error.value())); if (return_early == ReturnEarly::Yes) return true; } @@ -269,7 +273,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReplObject::print) { auto result = ::print(vm.argument(0)); if (result.is_error()) - return g_vm->throw_completion(DeprecatedString::formatted("Failed to print value: {}", result.error())); + return g_vm->throw_completion(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error()))); displayln(); @@ -388,5 +392,10 @@ extern "C" int initialize_repl(char const* time_zone) extern "C" bool execute(char const* source) { - return parse_and_run(*g_interpreter, { source, strlen(source) }, "REPL"sv); + if (auto result = parse_and_run(*g_interpreter, { source, strlen(source) }, "REPL"sv); result.is_error()) { + displayln("{}", result.error()); + return false; + } else { + return result.value(); + } } diff --git a/Tests/LibJS/test262-runner.cpp b/Tests/LibJS/test262-runner.cpp index a7fcba1e603..95d939520a9 100644 --- a/Tests/LibJS/test262-runner.cpp +++ b/Tests/LibJS/test262-runner.cpp @@ -91,9 +91,15 @@ static Result run_program(InterpreterT& interpreter, ScriptOrMo return visitor->parse_node(); }); - auto unit_result = JS::Bytecode::Generator::generate(program_node); - if (unit_result.is_error()) { - result = JS::throw_completion(JS::InternalError::create(interpreter.realm(), DeprecatedString::formatted("TODO({})", unit_result.error().to_deprecated_string()))); + auto& vm = interpreter.vm(); + + if (auto unit_result = JS::Bytecode::Generator::generate(program_node); unit_result.is_error()) { + if (auto error_string = unit_result.error().to_string(); error_string.is_error()) + result = vm.template throw_completion(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)); + else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error()) + result = vm.template throw_completion(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)); + else + result = JS::throw_completion(JS::InternalError::create(interpreter.realm(), error_string.release_value())); } else { auto unit = unit_result.release_value(); auto optimization_level = s_enable_bytecode_optimizations ? JS::Bytecode::Interpreter::OptimizationLevel::Optimize : JS::Bytecode::Interpreter::OptimizationLevel::Default; diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp index 29c7c701397..233f9f90f5c 100644 --- a/Tests/LibWasm/test-wasm.cpp +++ b/Tests/LibWasm/test-wasm.cpp @@ -15,20 +15,26 @@ TEST_ROOT("Userland/Libraries/LibWasm/Tests"); TESTJS_GLOBAL_FUNCTION(read_binary_wasm_file, readBinaryWasmFile) { auto& realm = *vm.current_realm(); + + auto error_code_to_string = [](int code) { + auto const* error_string = strerror(code); + return StringView { error_string, strlen(error_string) }; + }; + auto filename = TRY(vm.argument(0).to_deprecated_string(vm)); auto file = Core::File::open(filename, Core::File::OpenMode::Read); if (file.is_error()) - return vm.throw_completion(strerror(file.error().code())); + return vm.throw_completion(error_code_to_string(file.error().code())); auto file_size = file.value()->size(); if (file_size.is_error()) - return vm.throw_completion(strerror(file_size.error().code())); + return vm.throw_completion(error_code_to_string(file_size.error().code())); auto array = TRY(JS::Uint8Array::create(realm, file_size.value())); auto read = file.value()->read(array->data()); if (read.is_error()) - return vm.throw_completion(strerror(read.error().code())); + return vm.throw_completion(error_code_to_string(read.error().code())); return JS::Value(array); } @@ -57,7 +63,7 @@ public: linker.link(spec_test_namespace()); auto link_result = linker.finish(); if (link_result.is_error()) - return vm.throw_completion("Link failed"); + return vm.throw_completion("Link failed"sv); auto result = machine().instantiate(*instance->m_module, link_result.release_value()); if (result.is_error()) return vm.throw_completion(result.release_error().error); @@ -103,7 +109,7 @@ TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule) auto& realm = *vm.current_realm(); auto* object = TRY(vm.argument(0).to_object(vm)); if (!is(object)) - return vm.throw_completion("Expected a Uint8Array argument to parse_webassembly_module"); + return vm.throw_completion("Expected a Uint8Array argument to parse_webassembly_module"sv); auto& array = static_cast(*object); FixedMemoryStream stream { array.data() }; auto result = Wasm::Module::parse(stream); @@ -133,11 +139,11 @@ TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays) { auto* lhs = TRY(vm.argument(0).to_object(vm)); if (!is(lhs)) - return vm.throw_completion("Expected a TypedArray"); + return vm.throw_completion("Expected a TypedArray"sv); auto& lhs_array = static_cast(*lhs); auto* rhs = TRY(vm.argument(1).to_object(vm)); if (!is(rhs)) - return vm.throw_completion("Expected a TypedArray"); + return vm.throw_completion("Expected a TypedArray"sv); auto& rhs_array = static_cast(*rhs); return JS::Value(lhs_array.viewed_array_buffer()->buffer() == rhs_array.viewed_array_buffer()->buffer()); } @@ -157,7 +163,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export) auto this_value = vm.this_value(); auto* object = TRY(this_value.to_object(vm)); if (!is(object)) - return vm.throw_completion("Not a WebAssemblyModule"); + return vm.throw_completion("Not a WebAssemblyModule"sv); auto instance = static_cast(object); for (auto& entry : instance->module_instance().exports()) { if (entry.name() == name) { @@ -175,10 +181,10 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export) [&](const auto& ref) -> JS::Value { return JS::Value(static_cast(ref.address.value())); }); }); } - return vm.throw_completion(DeprecatedString::formatted("'{}' does not refer to a function or a global", name)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("'{}' does not refer to a function or a global", name))); } } - return vm.throw_completion(DeprecatedString::formatted("'{}' could not be found", name)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("'{}' could not be found", name))); } JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) @@ -187,16 +193,16 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) Wasm::FunctionAddress function_address { address }; auto function_instance = WebAssemblyModule::machine().store().get(function_address); if (!function_instance) - return vm.throw_completion("Invalid function address"); + return vm.throw_completion("Invalid function address"sv); Wasm::FunctionType const* type { nullptr }; function_instance->visit([&](auto& value) { type = &value.type(); }); if (!type) - return vm.throw_completion("Invalid function found at given address"); + return vm.throw_completion("Invalid function found at given address"sv); Vector arguments; if (type->parameters().size() + 1 > vm.argument_count()) - return vm.throw_completion(DeprecatedString::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count())); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count()))); size_t index = 1; for (auto& param : type->parameters()) { auto argument = vm.argument(index++); @@ -238,7 +244,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) auto result = WebAssemblyModule::machine().invoke(function_address, arguments); if (result.is_trap()) - return vm.throw_completion(DeprecatedString::formatted("Execution trapped: {}", result.trap().reason)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Execution trapped: {}", result.trap().reason))); if (result.values().is_empty()) return JS::js_null(); diff --git a/Userland/Applications/Spreadsheet/JSIntegration.cpp b/Userland/Applications/Spreadsheet/JSIntegration.cpp index 5544e6e1db3..4e175e31457 100644 --- a/Userland/Applications/Spreadsheet/JSIntegration.cpp +++ b/Userland/Applications/Spreadsheet/JSIntegration.cpp @@ -193,14 +193,14 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_real_cell_contents) auto sheet_object = static_cast(this_object); if (vm.argument_count() != 1) - return vm.throw_completion("Expected exactly one argument to get_real_cell_contents()"); + return vm.throw_completion("Expected exactly one argument to get_real_cell_contents()"sv); auto name_value = vm.argument(0); if (!name_value.is_string()) - return vm.throw_completion("Expected a String argument to get_real_cell_contents()"); + return vm.throw_completion("Expected a String argument to get_real_cell_contents()"sv); auto position = sheet_object->m_sheet.parse_cell_name(TRY(name_value.as_string().deprecated_string())); if (!position.has_value()) - return vm.throw_completion("Invalid cell name"); + return vm.throw_completion("Invalid cell name"sv); auto const* cell = sheet_object->m_sheet.at(position.value()); if (!cell) @@ -222,18 +222,18 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::set_real_cell_contents) auto sheet_object = static_cast(this_object); if (vm.argument_count() != 2) - return vm.throw_completion("Expected exactly two arguments to set_real_cell_contents()"); + return vm.throw_completion("Expected exactly two arguments to set_real_cell_contents()"sv); auto name_value = vm.argument(0); if (!name_value.is_string()) - return vm.throw_completion("Expected the first argument of set_real_cell_contents() to be a String"); + return vm.throw_completion("Expected the first argument of set_real_cell_contents() to be a String"sv); auto position = sheet_object->m_sheet.parse_cell_name(TRY(name_value.as_string().deprecated_string())); if (!position.has_value()) - return vm.throw_completion("Invalid cell name"); + return vm.throw_completion("Invalid cell name"sv); auto new_contents_value = vm.argument(1); if (!new_contents_value.is_string()) - return vm.throw_completion("Expected the second argument of set_real_cell_contents() to be a String"); + return vm.throw_completion("Expected the second argument of set_real_cell_contents() to be a String"sv); auto& cell = sheet_object->m_sheet.ensure(position.value()); auto new_contents = TRY(new_contents_value.as_string().deprecated_string()); @@ -253,10 +253,10 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::parse_cell_name) auto sheet_object = static_cast(this_object); if (vm.argument_count() != 1) - return vm.throw_completion("Expected exactly one argument to parse_cell_name()"); + return vm.throw_completion("Expected exactly one argument to parse_cell_name()"sv); auto name_value = vm.argument(0); if (!name_value.is_string()) - return vm.throw_completion("Expected a String argument to parse_cell_name()"); + return vm.throw_completion("Expected a String argument to parse_cell_name()"sv); auto position = sheet_object->m_sheet.parse_cell_name(TRY(name_value.as_string().deprecated_string())); if (!position.has_value()) return JS::js_undefined(); @@ -273,7 +273,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::current_cell_position) auto& realm = *vm.current_realm(); if (vm.argument_count() != 0) - return vm.throw_completion("Expected no arguments to current_cell_position()"); + return vm.throw_completion("Expected no arguments to current_cell_position()"sv); auto* this_object = TRY(vm.this_value().to_object(vm)); @@ -297,7 +297,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::current_cell_position) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_index) { if (vm.argument_count() != 1) - return vm.throw_completion("Expected exactly one argument to column_index()"); + return vm.throw_completion("Expected exactly one argument to column_index()"sv); auto column_name = vm.argument(0); if (!column_name.is_string()) @@ -314,7 +314,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_index) auto& sheet = sheet_object->m_sheet; auto column_index = sheet.column_index(column_name_str); if (!column_index.has_value()) - return vm.throw_completion(DeprecatedString::formatted("'{}' is not a valid column", column_name_str)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("'{}' is not a valid column", column_name_str))); return JS::Value((i32)column_index.value()); } @@ -322,7 +322,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_index) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_arithmetic) { if (vm.argument_count() != 2) - return vm.throw_completion("Expected exactly two arguments to column_arithmetic()"); + return vm.throw_completion("Expected exactly two arguments to column_arithmetic()"sv); auto column_name = vm.argument(0); if (!column_name.is_string()) @@ -342,7 +342,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_arithmetic) auto& sheet = sheet_object->m_sheet; auto new_column = sheet.column_arithmetic(column_name_str, offset_number); if (!new_column.has_value()) - return vm.throw_completion(DeprecatedString::formatted("'{}' is not a valid column", column_name_str)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("'{}' is not a valid column", column_name_str))); return JS::PrimitiveString::create(vm, new_column.release_value()); } @@ -350,7 +350,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::column_arithmetic) JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_column_bound) { if (vm.argument_count() != 1) - return vm.throw_completion("Expected exactly one argument to get_column_bound()"); + return vm.throw_completion("Expected exactly one argument to get_column_bound()"sv); auto column_name = vm.argument(0); if (!column_name.is_string()) @@ -366,7 +366,7 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_column_bound) auto& sheet = sheet_object->m_sheet; auto maybe_column_index = sheet.column_index(column_name_str); if (!maybe_column_index.has_value()) - return vm.throw_completion(DeprecatedString::formatted("'{}' is not a valid column", column_name_str)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("'{}' is not a valid column", column_name_str))); auto bounds = sheet.written_data_bounds(*maybe_column_index); return JS::Value(bounds.row); @@ -396,10 +396,10 @@ void WorkbookObject::visit_edges(Visitor& visitor) JS_DEFINE_NATIVE_FUNCTION(WorkbookObject::sheet) { if (vm.argument_count() != 1) - return vm.throw_completion("Expected exactly one argument to sheet()"); + return vm.throw_completion("Expected exactly one argument to sheet()"sv); auto name_value = vm.argument(0); if (!name_value.is_string() && !name_value.is_number()) - return vm.throw_completion("Expected a String or Number argument to sheet()"); + return vm.throw_completion("Expected a String or Number argument to sheet()"sv); auto* this_object = TRY(vm.this_value().to_object(vm)); diff --git a/Userland/Applications/Spreadsheet/Spreadsheet.cpp b/Userland/Applications/Spreadsheet/Spreadsheet.cpp index 7dc6b222825..a0175e9aa24 100644 --- a/Userland/Applications/Spreadsheet/Spreadsheet.cpp +++ b/Userland/Applications/Spreadsheet/Spreadsheet.cpp @@ -172,7 +172,7 @@ JS::ThrowCompletionOr Sheet::evaluate(StringView source, Cell* on_beh name); if (script_or_error.is_error()) - return interpreter().vm().throw_completion(script_or_error.error().first().to_deprecated_string()); + return interpreter().vm().throw_completion(TRY_OR_THROW_OOM(interpreter().vm(), script_or_error.error().first().to_string())); return interpreter().run(script_or_error.value()); } diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index 4d22fc73d54..7c4ad5ac130 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -3525,7 +3525,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const if (!options_value.is_undefined()) { // a. If Type(options) is not Object, if (!options_value.is_object()) { - auto error = TypeError::create(realm, DeprecatedString::formatted(ErrorType::NotAnObject.message(), "ImportOptions")); + auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "ImportOptions"))); // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). MUST(call(vm, *promise_capability->reject(), js_undefined(), error)); @@ -3541,7 +3541,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const if (!assertion_object.is_undefined()) { // i. If Type(assertionsObj) is not Object, if (!assertion_object.is_object()) { - auto error = TypeError::create(realm, DeprecatedString::formatted(ErrorType::NotAnObject.message(), "ImportOptionsAssertions")); + auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "ImportOptionsAssertions"))); // 1. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). MUST(call(vm, *promise_capability->reject(), js_undefined(), error)); @@ -3566,7 +3566,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const // 3. If Type(value) is not String, then if (!value.is_string()) { - auto error = TypeError::create(realm, DeprecatedString::formatted(ErrorType::NotAString.message(), "Import Assertion option value")); + auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAString.message(), "Import Assertion option value"))); // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). MUST(call(vm, *promise_capability->reject(), js_undefined(), error)); diff --git a/Userland/Libraries/LibJS/Bytecode/Op.cpp b/Userland/Libraries/LibJS/Bytecode/Op.cpp index 75631b05fc6..9349e97dd31 100644 --- a/Userland/Libraries/LibJS/Bytecode/Op.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Op.cpp @@ -320,17 +320,17 @@ ThrowCompletionOr NewRegExp::execute_impl(Bytecode::Interpreter& interpret return {}; } -#define JS_DEFINE_NEW_BUILTIN_ERROR_OP(ErrorName) \ - ThrowCompletionOr New##ErrorName::execute_impl(Bytecode::Interpreter& interpreter) const \ - { \ - auto& vm = interpreter.vm(); \ - auto& realm = *vm.current_realm(); \ - interpreter.accumulator() = ErrorName::create(realm, interpreter.current_executable().get_string(m_error_string)); \ - return {}; \ - } \ - DeprecatedString New##ErrorName::to_deprecated_string_impl(Bytecode::Executable const& executable) const \ - { \ - return DeprecatedString::formatted("New" #ErrorName " {} (\"{}\")", m_error_string, executable.string_table->get(m_error_string)); \ +#define JS_DEFINE_NEW_BUILTIN_ERROR_OP(ErrorName) \ + ThrowCompletionOr New##ErrorName::execute_impl(Bytecode::Interpreter& interpreter) const \ + { \ + auto& vm = interpreter.vm(); \ + auto& realm = *vm.current_realm(); \ + interpreter.accumulator() = MUST_OR_THROW_OOM(ErrorName::create(realm, interpreter.current_executable().get_string(m_error_string))); \ + return {}; \ + } \ + DeprecatedString New##ErrorName::to_deprecated_string_impl(Bytecode::Executable const& executable) const \ + { \ + return DeprecatedString::formatted("New" #ErrorName " {} (\"{}\")", m_error_string, executable.string_table->get(m_error_string)); \ } JS_ENUMERATE_NEW_BUILTIN_ERROR_OPS(JS_DEFINE_NEW_BUILTIN_ERROR_OP) @@ -446,7 +446,7 @@ ThrowCompletionOr CreateVariable::execute_impl(Bytecode::Interpreter& inte // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us. // Instead of crashing in there, we'll just raise an exception here. if (TRY(vm.lexical_environment()->has_binding(name))) - return vm.throw_completion(DeprecatedString::formatted("Lexical environment already has binding '{}'", name)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name))); if (m_is_immutable) vm.lexical_environment()->create_immutable_binding(vm, name, vm.in_strict_mode()); @@ -929,7 +929,7 @@ ThrowCompletionOr GetObjectPropertyIterator::execute_impl(Bytecode::Interp auto& realm = *vm.current_realm(); auto iterated_object_value = vm.this_value(); if (!iterated_object_value.is_object()) - return vm.throw_completion("Invalid state for GetObjectPropertyIterator.next"); + return vm.throw_completion("Invalid state for GetObjectPropertyIterator.next"sv); auto& iterated_object = iterated_object_value.as_object(); auto result_object = Object::create(realm, nullptr); diff --git a/Userland/Libraries/LibJS/Contrib/Test262/$262Object.cpp b/Userland/Libraries/LibJS/Contrib/Test262/$262Object.cpp index d0911ba6d5d..0c066502e81 100644 --- a/Userland/Libraries/LibJS/Contrib/Test262/$262Object.cpp +++ b/Userland/Libraries/LibJS/Contrib/Test262/$262Object.cpp @@ -98,7 +98,7 @@ JS_DEFINE_NATIVE_FUNCTION($262Object::eval_script) auto& error = script_or_error.error()[0]; // b. Return Completion { [[Type]]: throw, [[Value]]: error, [[Target]]: empty }. - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } // 5. Let status be ScriptEvaluation(s). diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp index 070ea5664bd..0096735ae48 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp @@ -602,7 +602,7 @@ ThrowCompletionOr perform_eval(VM& vm, Value x, CallerMode strict_caller, // b. If script is a List of errors, throw a SyntaxError exception. if (parser.has_errors()) { auto& error = parser.errors()[0]; - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } bool strict_eval = false; @@ -704,7 +704,7 @@ ThrowCompletionOr perform_eval(VM& vm, Value x, CallerMode strict_caller, if (auto* bytecode_interpreter = Bytecode::Interpreter::current()) { auto executable_result = Bytecode::Generator::generate(program); if (executable_result.is_error()) - return vm.throw_completion(ErrorType::NotImplemented, executable_result.error().to_deprecated_string()); + return vm.throw_completion(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string())); auto executable = executable_result.release_value(); executable->name = "eval"sv; diff --git a/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp b/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp index 1cc4dfafb43..7ace3110025 100644 --- a/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp @@ -137,7 +137,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::return_) // 11. If Type(result) is not Object, then if (!result.is_object()) { - auto error = TypeError::create(realm, DeprecatedString::formatted(ErrorType::NotAnObject.message(), "SyncIteratorReturnResult")); + auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "SyncIteratorReturnResult"))); // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). MUST(call(vm, *promise_capability->reject(), js_undefined(), error)); // b. Return promiseCapability.[[Promise]]. @@ -185,7 +185,8 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::throw_) // 11. If Type(result) is not Object, then if (!result.is_object()) { - auto error = TypeError::create(realm, DeprecatedString::formatted(ErrorType::NotAnObject.message(), "SyncIteratorThrowResult")); + auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "SyncIteratorThrowResult"))); + // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). MUST(call(vm, *promise_capability->reject(), js_undefined(), error)); diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index abb2790ab69..b6be28e1e90 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -824,7 +824,7 @@ Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() auto compile = [&](auto& node, auto kind, auto name) -> ThrowCompletionOr> { auto executable_result = Bytecode::Generator::generate(node, kind); if (executable_result.is_error()) - return vm.throw_completion(ErrorType::NotImplemented, executable_result.error().to_deprecated_string()); + return vm.throw_completion(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string())); auto bytecode_executable = executable_result.release_value(); bytecode_executable->name = name; diff --git a/Userland/Libraries/LibJS/Runtime/Error.cpp b/Userland/Libraries/LibJS/Runtime/Error.cpp index 6d11909d544..b793faef7cf 100644 --- a/Userland/Libraries/LibJS/Runtime/Error.cpp +++ b/Userland/Libraries/LibJS/Runtime/Error.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include namespace JS { @@ -19,15 +20,20 @@ NonnullGCPtr Error::create(Realm& realm) return realm.heap().allocate(realm, *realm.intrinsics().error_prototype()).release_allocated_value_but_fixme_should_propagate_errors(); } -NonnullGCPtr Error::create(Realm& realm, DeprecatedString const& message) +NonnullGCPtr Error::create(Realm& realm, String message) { auto& vm = realm.vm(); auto error = Error::create(realm); u8 attr = Attribute::Writable | Attribute::Configurable; - error->define_direct_property(vm.names.message, PrimitiveString::create(vm, message), attr); + error->define_direct_property(vm.names.message, PrimitiveString::create(vm, move(message)), attr); return error; } +ThrowCompletionOr> Error::create(Realm& realm, StringView message) +{ + return create(realm, TRY_OR_THROW_OOM(realm.vm(), String::from_utf8(message))); +} + Error::Error(Object& prototype) : Object(ConstructWithPrototypeTag::Tag, prototype) { @@ -73,9 +79,10 @@ void Error::populate_stack() } } -DeprecatedString Error::stack_string() const +ThrowCompletionOr Error::stack_string(VM& vm) const { - StringBuilder stack_string_builder; + ThrowableStringBuilder stack_string_builder(vm); + // Note: We roughly follow V8's formatting // Note: The error's name and message get prepended by ErrorPrototype::stack // Note: We don't want to capture the global execution context, so we omit the last frame @@ -87,15 +94,15 @@ DeprecatedString Error::stack_string() const if (!frame.source_range.filename().is_empty() || frame.source_range.start.offset != 0 || frame.source_range.end.offset != 0) { if (function_name == ""sv) - stack_string_builder.appendff(" at {}:{}:{}\n", frame.source_range.filename(), frame.source_range.start.line, frame.source_range.start.column); + MUST_OR_THROW_OOM(stack_string_builder.appendff(" at {}:{}:{}\n", frame.source_range.filename(), frame.source_range.start.line, frame.source_range.start.column)); else - stack_string_builder.appendff(" at {} ({}:{}:{})\n", function_name, frame.source_range.filename(), frame.source_range.start.line, frame.source_range.start.column); + MUST_OR_THROW_OOM(stack_string_builder.appendff(" at {} ({}:{}:{})\n", function_name, frame.source_range.filename(), frame.source_range.start.line, frame.source_range.start.column)); } else { - stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? ""sv : function_name.view()); + MUST_OR_THROW_OOM(stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? ""sv : function_name.view())); } } - return stack_string_builder.to_deprecated_string(); + return stack_string_builder.to_string(); } #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \ @@ -104,15 +111,20 @@ DeprecatedString Error::stack_string() const return realm.heap().allocate(realm, *realm.intrinsics().snake_name##_prototype()).release_allocated_value_but_fixme_should_propagate_errors(); \ } \ \ - NonnullGCPtr ClassName::create(Realm& realm, DeprecatedString const& message) \ + NonnullGCPtr ClassName::create(Realm& realm, String message) \ { \ auto& vm = realm.vm(); \ auto error = ClassName::create(realm); \ u8 attr = Attribute::Writable | Attribute::Configurable; \ - error->define_direct_property(vm.names.message, PrimitiveString::create(vm, message), attr); \ + error->define_direct_property(vm.names.message, PrimitiveString::create(vm, move(message)), attr); \ return error; \ } \ \ + ThrowCompletionOr> ClassName::create(Realm& realm, StringView message) \ + { \ + return create(realm, TRY_OR_THROW_OOM(realm.vm(), String::from_utf8(message))); \ + } \ + \ ClassName::ClassName(Object& prototype) \ : Error(prototype) \ { \ diff --git a/Userland/Libraries/LibJS/Runtime/Error.h b/Userland/Libraries/LibJS/Runtime/Error.h index 0422003e167..26be07495fb 100644 --- a/Userland/Libraries/LibJS/Runtime/Error.h +++ b/Userland/Libraries/LibJS/Runtime/Error.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include #include @@ -24,11 +25,12 @@ class Error : public Object { public: static NonnullGCPtr create(Realm&); - static NonnullGCPtr create(Realm&, DeprecatedString const& message); + static NonnullGCPtr create(Realm&, String message); + static ThrowCompletionOr> create(Realm&, StringView message); virtual ~Error() override = default; - [[nodiscard]] DeprecatedString stack_string() const; + [[nodiscard]] ThrowCompletionOr stack_string(VM&) const; ThrowCompletionOr install_error_cause(Value options); @@ -45,16 +47,17 @@ private: // NOTE: Making these inherit from Error is not required by the spec but // our way of implementing the [[ErrorData]] internal slot, which is // used in Object.prototype.toString(). -#define DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName) \ - class ClassName final : public Error { \ - JS_OBJECT(ClassName, Error); \ - \ - public: \ - static NonnullGCPtr create(Realm&); \ - static NonnullGCPtr create(Realm&, DeprecatedString const& message); \ - \ - explicit ClassName(Object& prototype); \ - virtual ~ClassName() override = default; \ +#define DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName) \ + class ClassName final : public Error { \ + JS_OBJECT(ClassName, Error); \ + \ + public: \ + static NonnullGCPtr create(Realm&); \ + static NonnullGCPtr create(Realm&, String message); \ + static ThrowCompletionOr> create(Realm&, StringView message); \ + \ + explicit ClassName(Object& prototype); \ + virtual ~ClassName() override = default; \ }; #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \ diff --git a/Userland/Libraries/LibJS/Runtime/ErrorPrototype.cpp b/Userland/Libraries/LibJS/Runtime/ErrorPrototype.cpp index cc095b69ffa..a6a976f4739 100644 --- a/Userland/Libraries/LibJS/Runtime/ErrorPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/ErrorPrototype.cpp @@ -100,7 +100,7 @@ JS_DEFINE_NATIVE_FUNCTION(ErrorPrototype::stack_getter) if (!message.is_empty()) header = DeprecatedString::formatted("{}: {}", name, message); - return PrimitiveString::create(vm, DeprecatedString::formatted("{}\n{}", header, error.stack_string())); + return PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, String::formatted("{}\n{}", header, MUST_OR_THROW_OOM(error.stack_string(vm))))); } // B.1.2 set Error.prototype.stack ( value ), https://tc39.es/proposal-error-stacks/#sec-set-error.prototype-stack diff --git a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp index 1c4e137fa5e..12997aea773 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp @@ -178,7 +178,7 @@ ThrowCompletionOr FunctionConstructor::create_dynamic // 17. If parameters is a List of errors, throw a SyntaxError exception. if (parameters_parser.has_errors()) { auto error = parameters_parser.errors()[0]; - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } // 18. Let body be ParseText(StringToCodePoints(bodyString), bodySym). @@ -195,7 +195,7 @@ ThrowCompletionOr FunctionConstructor::create_dynamic // 19. If body is a List of errors, throw a SyntaxError exception. if (body_parser.has_errors()) { auto error = body_parser.errors()[0]; - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } // 20. NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example, new Function("/*", "*/ ) {") is not legal. @@ -209,7 +209,7 @@ ThrowCompletionOr FunctionConstructor::create_dynamic // 23. If expr is a List of errors, throw a SyntaxError exception. if (source_parser.has_errors()) { auto error = source_parser.errors()[0]; - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } // 24. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto). diff --git a/Userland/Libraries/LibJS/Runtime/Promise.cpp b/Userland/Libraries/LibJS/Runtime/Promise.cpp index 108c6e457c1..67f87b32fa0 100644 --- a/Userland/Libraries/LibJS/Runtime/Promise.cpp +++ b/Userland/Libraries/LibJS/Runtime/Promise.cpp @@ -71,7 +71,7 @@ Promise::ResolvingFunctions Promise::create_resolving_functions() // 6. Set resolve.[[AlreadyResolved]] to alreadyResolved. // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions - auto resolve_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) { + auto resolve_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) -> ThrowCompletionOr { dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise); auto& realm = *vm.current_realm(); @@ -97,7 +97,7 @@ Promise::ResolvingFunctions Promise::create_resolving_functions() dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise); // a. Let selfResolutionError be a newly created TypeError object. - auto self_resolution_error = TypeError::create(realm, "Cannot resolve promise with itself"); + auto self_resolution_error = MUST_OR_THROW_OOM(TypeError::create(realm, "Cannot resolve promise with itself"sv)); // b. Perform RejectPromise(promise, selfResolutionError). promise.reject(self_resolution_error); diff --git a/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp b/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp index f4e9368271f..9532ece8364 100644 --- a/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp +++ b/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp @@ -107,7 +107,7 @@ ThrowCompletionOr perform_shadow_realm_eval(VM& vm, StringView source_tex // b. If script is a List of errors, throw a SyntaxError exception. if (parser.has_errors()) { auto& error = parser.errors()[0]; - return vm.throw_completion(error.to_deprecated_string()); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, error.to_string())); } // c. If script Contains ScriptBody is false, return undefined. @@ -272,7 +272,7 @@ ThrowCompletionOr shadow_realm_import_value(VM& vm, DeprecatedString spec // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object). auto throw_type_error = NativeFunction::create(realm, {}, [](auto& vm) -> ThrowCompletionOr { - return vm.template throw_completion(TRY(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().deprecated_string())); + return vm.template throw_completion(TRY(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().utf8_string())); }); // 13. Return PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability). diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index 548cb867563..b85f6e6f163 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -90,7 +90,7 @@ VM::VM(OwnPtr custom_data) // If you are here because you want to enable dynamic module importing make sure it won't be a security problem // by checking the default implementation of HostImportModuleDynamically and creating your own hook or calling // vm.enable_default_host_import_module_dynamically_hook(). - promise->reject(Error::create(realm, ErrorType::DynamicImportNotAllowed.message())); + promise->reject(Error::create(realm, ErrorType::DynamicImportNotAllowed.message()).release_allocated_value_but_fixme_should_propagate_errors()); promise->perform_then( NativeFunction::create(realm, "", [](auto&) -> ThrowCompletionOr { @@ -154,10 +154,10 @@ VM::VM(OwnPtr custom_data) JS_ENUMERATE_WELL_KNOWN_SYMBOLS #undef __JS_ENUMERATE - m_error_messages[to_underlying(ErrorMessage::OutOfMemory)] = ErrorType::OutOfMemory.message(); + m_error_messages[to_underlying(ErrorMessage::OutOfMemory)] = String::from_utf8(ErrorType::OutOfMemory.message()).release_value_but_fixme_should_propagate_errors(); } -DeprecatedString const& VM::error_message(ErrorMessage type) const +String const& VM::error_message(ErrorMessage type) const { VERIFY(type < ErrorMessage::__Count); @@ -1001,7 +1001,7 @@ void VM::import_module_dynamically(ScriptOrModule referencing_script_or_module, // If there is no ScriptOrModule in any of the execution contexts if (referencing_script_or_module.has()) { // Throw an error for now - promise->reject(InternalError::create(realm, DeprecatedString::formatted(ErrorType::ModuleNotFoundNoReferencingScript.message(), module_request.module_specifier))); + promise->reject(InternalError::create(realm, String::formatted(ErrorType::ModuleNotFoundNoReferencingScript.message(), module_request.module_specifier).release_value_but_fixme_should_propagate_errors())); return; } } diff --git a/Userland/Libraries/LibJS/Runtime/VM.h b/Userland/Libraries/LibJS/Runtime/VM.h index b163921b3e1..4ba4b8ce5bd 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.h +++ b/Userland/Libraries/LibJS/Runtime/VM.h @@ -100,7 +100,7 @@ public: // Keep this last: __Count, }; - DeprecatedString const& error_message(ErrorMessage) const; + String const& error_message(ErrorMessage) const; bool did_reach_stack_space_limit() const { @@ -201,7 +201,12 @@ public: Completion throw_completion(Args&&... args) { auto& realm = *current_realm(); - return JS::throw_completion(T::create(realm, forward(args)...)); + auto completion = T::create(realm, forward(args)...); + + if constexpr (IsSame>>) + return JS::throw_completion(MUST_OR_THROW_OOM(completion)); + else + return JS::throw_completion(completion); } template @@ -296,7 +301,7 @@ private: PrimitiveString* m_empty_string { nullptr }; PrimitiveString* m_single_ascii_character_strings[128] {}; - AK::Array m_error_messages; + AK::Array m_error_messages; struct StoredModule { ScriptOrModule referencing_script_or_module; diff --git a/Userland/Libraries/LibTest/JavaScriptTestRunner.h b/Userland/Libraries/LibTest/JavaScriptTestRunner.h index a24ffe44c69..107f311524d 100644 --- a/Userland/Libraries/LibTest/JavaScriptTestRunner.h +++ b/Userland/Libraries/LibTest/JavaScriptTestRunner.h @@ -485,7 +485,7 @@ inline JSFileResult TestRunner::run_file_test(DeprecatedString const& test_path) if (is(error_object)) { auto& error_as_error = static_cast(error_object); detail_builder.append('\n'); - detail_builder.append(error_as_error.stack_string()); + detail_builder.append(error_as_error.stack_string(*g_vm).release_allocated_value_but_fixme_should_propagate_errors()); } test_case.details = detail_builder.to_deprecated_string(); diff --git a/Userland/Libraries/LibWeb/Bindings/FetchMethod.cpp b/Userland/Libraries/LibWeb/Bindings/FetchMethod.cpp index c533cdf4883..1d1a1c7db64 100644 --- a/Userland/Libraries/LibWeb/Bindings/FetchMethod.cpp +++ b/Userland/Libraries/LibWeb/Bindings/FetchMethod.cpp @@ -219,7 +219,7 @@ JS::ThrowCompletionOr fetch(JS::VM& vm) } return record_union_type; } - return vm.throw_completion("No union types matched"); + return vm.throw_completion("No union types matched"sv); }; Optional>, OrderedHashMap>> headers_value; if (!headers_property_value.is_nullish()) diff --git a/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp index ea2b368ac37..d6fd5a3e42f 100644 --- a/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp +++ b/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp @@ -68,7 +68,7 @@ JS::VM& main_thread_vm() vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr { // 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }. if (is(object) || is(object)) - return vm->throw_completion("Cannot add private elements to window or location object"); + return vm->throw_completion("Cannot add private elements to window or location object"sv); // 2. Return NormalCompletion(unused). return {}; diff --git a/Userland/Libraries/LibWeb/Fetch/Body.cpp b/Userland/Libraries/LibWeb/Fetch/Body.cpp index dff2ab65041..abe4dbc3b30 100644 --- a/Userland/Libraries/LibWeb/Fetch/Body.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Body.cpp @@ -148,7 +148,7 @@ JS::NonnullGCPtr consume_body(JS::Realm& realm, BodyMixin const& ob // 1. If object is unusable, then return a promise rejected with a TypeError. if (object.is_unusable()) { - auto promise_capability = WebIDL::create_rejected_promise(realm, JS::TypeError::create(realm, "Body is unusable"sv)); + auto promise_capability = WebIDL::create_rejected_promise(realm, JS::TypeError::create(realm, "Body is unusable"sv).release_allocated_value_but_fixme_should_propagate_errors()); return verify_cast(*promise_capability->promise().ptr()); } diff --git a/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp index 61e3bb00595..d42649cc077 100644 --- a/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp +++ b/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp @@ -100,7 +100,7 @@ JS::NonnullGCPtr fetch_impl(JS::VM& vm, RequestInfo const& input, R // 3. If response is a network error, then reject p with a TypeError and abort these steps. if (response->is_network_error()) { auto message = response->network_error_message().value_or("Response is a network error"sv); - WebIDL::reject_promise(vm, promise_capability, JS::TypeError::create(relevant_realm, message)); + WebIDL::reject_promise(vm, promise_capability, JS::TypeError::create(relevant_realm, message).release_allocated_value_but_fixme_should_propagate_errors()); return; } diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp index 15ce59f0372..dee3e3f54d1 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp @@ -52,7 +52,7 @@ JS::NonnullGCPtr Body::fully_read_as_promise() const return WebIDL::create_resolved_promise(realm, JS::PrimitiveString::create(vm, move(result))); } // Empty, Blob, FormData - return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv)); + return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv).release_allocated_value_but_fixme_should_propagate_errors()); } // https://fetch.spec.whatwg.org/#byte-sequence-as-a-body diff --git a/Userland/Libraries/LibWeb/HTML/Location.cpp b/Userland/Libraries/LibWeb/HTML/Location.cpp index 727b3ee9852..182b3067c7e 100644 --- a/Userland/Libraries/LibWeb/HTML/Location.cpp +++ b/Userland/Libraries/LibWeb/HTML/Location.cpp @@ -89,7 +89,7 @@ JS::ThrowCompletionOr Location::set_href(DeprecatedString const& new_href) // 2. Parse the given value relative to the entry settings object. If that failed, throw a TypeError exception. auto href_url = window.associated_document().parse_url(new_href); if (!href_url.is_valid()) - return vm.throw_completion(DeprecatedString::formatted("Invalid URL '{}'", new_href)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Invalid URL '{}'", new_href))); // 3. Location-object navigate given the resulting URL record. window.did_set_location_href({}, href_url); diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp b/Userland/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp index 40c2452f220..0701593cc61 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp +++ b/Userland/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp @@ -90,7 +90,7 @@ JS::Completion ClassicScript::run(RethrowErrors rethrow_errors, JS::GCPtr(m_error_to_rethrow.value().to_deprecated_string()); + evaluation_status = vm.throw_completion(TRY_OR_THROW_OOM(vm, m_error_to_rethrow.value().to_string())); } else { auto timer = Core::ElapsedTimer::start_new(); diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Userland/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp index db35df95eb5..499377bc4cc 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp +++ b/Userland/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp @@ -44,7 +44,7 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromi dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", value); } - console.report_exception(*JS::Error::create(realm, value.to_string_without_side_effects().release_value_but_fixme_should_propagate_errors().to_deprecated_string()), error_in_promise == ErrorInPromise::Yes); + console.report_exception(*JS::Error::create(realm, value.to_string_without_side_effects().release_value_but_fixme_should_propagate_errors()), error_in_promise == ErrorInPromise::Yes); } // https://html.spec.whatwg.org/#report-the-exception diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index 023bdaa8fc3..4d8f2978445 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -1725,7 +1725,7 @@ JS_DEFINE_NATIVE_FUNCTION(Window::scroll) if (!behavior_string_value.is_undefined()) behavior_string = TRY(behavior_string_value.to_deprecated_string(vm)); if (behavior_string != "smooth" && behavior_string != "auto") - return vm.throw_completion("Behavior is not one of 'smooth' or 'auto'"); + return vm.throw_completion("Behavior is not one of 'smooth' or 'auto'"sv); } else if (vm.argument_count() >= 2) { // We ignore arguments 2+ in line with behavior of Chrome and Firefox @@ -1788,7 +1788,7 @@ JS_DEFINE_NATIVE_FUNCTION(Window::scroll_by) auto behavior_string_value = TRY(options->get("behavior")); auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY(behavior_string_value.to_deprecated_string(vm)); if (behavior_string != "smooth" && behavior_string != "auto") - return vm.throw_completion("Behavior is not one of 'smooth' or 'auto'"); + return vm.throw_completion("Behavior is not one of 'smooth' or 'auto'"sv); ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto; // FIXME: Spec wants us to call scroll(options) here. diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryConstructor.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryConstructor.cpp index 21be84b7186..bdf68ff714f 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryConstructor.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryConstructor.cpp @@ -44,7 +44,7 @@ JS::ThrowCompletionOr> WebAssemblyMemoryConstructor auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::MemoryType { Wasm::Limits { initial, maximum } }); if (!address.has_value()) - return vm.throw_completion("Wasm Memory allocation failed"); + return vm.throw_completion("Wasm Memory allocation failed"sv); return MUST_OR_THROW_OOM(vm.heap().allocate(realm, realm, *address)); } diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryPrototype.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryPrototype.cpp index 41b24d3cc5c..7dda6f568f9 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryPrototype.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyMemoryPrototype.cpp @@ -34,7 +34,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyMemoryPrototype::grow) auto previous_size = memory->size() / Wasm::Constants::page_size; if (!memory->grow(page_count * Wasm::Constants::page_size)) - return vm.throw_completion("Memory.grow() grows past the stated limit of the memory instance"); + return vm.throw_completion("Memory.grow() grows past the stated limit of the memory instance"sv); return JS::Value(static_cast(previous_size)); } diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp index 7d6ad223905..6073622e929 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -119,7 +120,7 @@ JS::ThrowCompletionOr parse_module(JS::VM& vm, JS::Object* buffer_object auto& buffer = static_cast(*buffer_object); data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length()); } else { - return vm.throw_completion("Not a BufferSource"); + return vm.throw_completion("Not a BufferSource"sv); } FixedMemoryStream stream { data }; auto module_result = Wasm::Module::parse(stream); @@ -233,11 +234,11 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, if (import_.is_number() || import_.is_bigint()) { if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) { // FIXME: Throw a LinkError instead. - return vm.throw_completion("LinkError: Import resolution attempted to cast a Number to a BigInteger"); + return vm.throw_completion("LinkError: Import resolution attempted to cast a Number to a BigInteger"sv); } if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) { // FIXME: Throw a LinkError instead. - return vm.throw_completion("LinkError: Import resolution attempted to cast a BigInteger to a Number"); + return vm.throw_completion("LinkError: Import resolution attempted to cast a BigInteger to a Number"sv); } auto cast_value = TRY(to_webassembly_value(vm, import_, type.type())); address = s_abstract_machine.store().allocate({ type.type(), false }, cast_value); @@ -247,7 +248,7 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, // let globaladdr be v.[[Global]] // FIXME: Throw a LinkError instead - return vm.throw_completion("LinkError: Invalid value for global type"); + return vm.throw_completion("LinkError: Invalid value for global type"sv); } resolved_imports.set(import_name, Wasm::ExternValue { *address }); @@ -256,7 +257,7 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr { if (!import_.is_object() || !is(import_.as_object())) { // FIXME: Throw a LinkError instead - return vm.throw_completion("LinkError: Expected an instance of WebAssembly.Memory for a memory import"); + return vm.throw_completion("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv); } auto address = static_cast(import_.as_object()).address(); resolved_imports.set(import_name, Wasm::ExternValue { address }); @@ -265,7 +266,7 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, [&](Wasm::TableType const&) -> JS::ThrowCompletionOr { if (!import_.is_object() || !is(import_.as_object())) { // FIXME: Throw a LinkError instead - return vm.throw_completion("LinkError: Expected an instance of WebAssembly.Table for a table import"); + return vm.throw_completion("LinkError: Expected an instance of WebAssembly.Table for a table import"sv); } auto address = static_cast(import_.as_object()).address(); resolved_imports.set(import_name, Wasm::ExternValue { address }); @@ -274,7 +275,7 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, [&](auto const&) -> JS::ThrowCompletionOr { // FIXME: Implement these. dbgln("Unimplemented import of non-function attempted"); - return vm.throw_completion("LinkError: Not Implemented"); + return vm.throw_completion("LinkError: Not Implemented"sv); })); } } @@ -283,10 +284,10 @@ JS::ThrowCompletionOr WebAssemblyObject::instantiate_module(JS::VM& vm, auto link_result = linker.finish(); if (link_result.is_error()) { // FIXME: Throw a LinkError. - StringBuilder builder; - builder.append("LinkError: Missing "sv); - builder.join(' ', link_result.error().missing_imports); - return vm.throw_completion(builder.to_deprecated_string()); + JS::ThrowableStringBuilder builder(vm); + MUST_OR_THROW_OOM(builder.append("LinkError: Missing "sv)); + MUST_OR_THROW_OOM(builder.join(' ', link_result.error().missing_imports)); + return vm.throw_completion(MUST_OR_THROW_OOM(builder.to_string())); } auto instance_result = s_abstract_machine.instantiate(module, link_result.release_value()); @@ -327,7 +328,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::instantiate) } else if (is(buffer)) { module = &static_cast(buffer)->module(); } else { - auto error = JS::TypeError::create(realm, DeprecatedString::formatted("{} is not an ArrayBuffer or a Module", buffer->class_name())); + auto error = JS::TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("{} is not an ArrayBuffer or a Module", buffer->class_name()))); promise->reject(error); return promise; } @@ -447,7 +448,7 @@ JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress add auto result = WebAssemblyObject::s_abstract_machine.invoke(address, move(values)); // FIXME: Use the convoluted mapping of errors defined in the spec. if (result.is_trap()) - return vm.throw_completion(DeprecatedString::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason))); if (result.values().is_empty()) return JS::js_undefined(); diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp index faa157e5641..af31ce34d2c 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp @@ -57,7 +57,7 @@ JS::ThrowCompletionOr> WebAssemblyTableConstructor: maximum = TRY(maximum_value.to_u32(vm)); if (maximum.has_value() && maximum.value() < initial) - return vm.throw_completion("maximum should be larger than or equal to initial"); + return vm.throw_completion("maximum should be larger than or equal to initial"sv); auto value_value = TRY(descriptor->get("value")); auto reference_value = TRY([&]() -> JS::ThrowCompletionOr { @@ -71,7 +71,7 @@ JS::ThrowCompletionOr> WebAssemblyTableConstructor: auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::TableType { *reference_type, Wasm::Limits { initial, maximum } }); if (!address.has_value()) - return vm.throw_completion("Wasm Table allocation failed"); + return vm.throw_completion("Wasm Table allocation failed"sv); auto& table = *WebAssemblyObject::s_abstract_machine.store().get(*address); for (auto& element : table.elements()) diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTablePrototype.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTablePrototype.cpp index 3309a1f7f7b..5301f60dcdf 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTablePrototype.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTablePrototype.cpp @@ -47,7 +47,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyTablePrototype::grow) auto& reference = reference_value.value().get(); if (!table->grow(delta, reference)) - return vm.throw_completion("Failed to grow table"); + return vm.throw_completion("Failed to grow table"sv); return JS::Value(static_cast(initial_size)); } @@ -66,7 +66,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyTablePrototype::get) return JS::js_undefined(); if (table->elements().size() <= index) - return vm.throw_completion("Table element index out of range"); + return vm.throw_completion("Table element index out of range"sv); auto& ref = table->elements()[index]; if (!ref.has_value()) @@ -90,7 +90,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyTablePrototype::set) return JS::js_undefined(); if (table->elements().size() <= index) - return vm.throw_completion("Table element index out of range"); + return vm.throw_completion("Table element index out of range"sv); auto value_value = vm.argument(1); auto reference_value = TRY([&]() -> JS::ThrowCompletionOr { diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp index 13ee8ba5795..b41979278ca 100644 --- a/Userland/Utilities/js.cpp +++ b/Userland/Utilities/js.cpp @@ -207,14 +207,14 @@ static ErrorOr parse_and_run(JS::Interpreter& interpreter, StringView sour JS::ThrowCompletionOr result { JS::js_undefined() }; - auto run_script_or_module = [&](auto& script_or_module) { + auto run_script_or_module = [&](auto& script_or_module) -> ErrorOr { if (s_dump_ast) script_or_module->parse_node().dump(0); if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) { auto executable_result = JS::Bytecode::Generator::generate(script_or_module->parse_node()); if (executable_result.is_error()) { - result = g_vm->throw_completion(executable_result.error().to_deprecated_string()); + result = g_vm->throw_completion(TRY(executable_result.error().to_string())); return ReturnEarly::No; } @@ -253,10 +253,12 @@ static ErrorOr parse_and_run(JS::Interpreter& interpreter, StringView sour auto hint = error.source_location_hint(source); if (!hint.is_empty()) outln("{}", hint); - outln("{}", error.to_deprecated_string()); - result = interpreter.vm().throw_completion(error.to_deprecated_string()); + + auto error_string = TRY(error.to_string()); + outln("{}", error_string); + result = interpreter.vm().throw_completion(move(error_string)); } else { - auto return_early = run_script_or_module(script_or_error.value()); + auto return_early = TRY(run_script_or_module(script_or_error.value())); if (return_early == ReturnEarly::Yes) return true; } @@ -267,10 +269,12 @@ static ErrorOr parse_and_run(JS::Interpreter& interpreter, StringView sour auto hint = error.source_location_hint(source); if (!hint.is_empty()) outln("{}", hint); - outln(error.to_deprecated_string()); - result = interpreter.vm().throw_completion(error.to_deprecated_string()); + + auto error_string = TRY(error.to_string()); + outln("{}", error_string); + result = interpreter.vm().throw_completion(move(error_string)); } else { - auto return_early = run_script_or_module(module_or_error.value()); + auto return_early = TRY(run_script_or_module(module_or_error.value())); if (return_early == ReturnEarly::Yes) return true; } @@ -335,7 +339,7 @@ static JS::ThrowCompletionOr load_ini_impl(JS::VM& vm) auto filename = TRY(vm.argument(0).to_deprecated_string(vm)); auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read); if (file_or_error.is_error()) - return vm.throw_completion(DeprecatedString::formatted("Failed to open '{}': {}", filename, file_or_error.error())); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Failed to open '{}': {}", filename, file_or_error.error()))); auto config_file = MUST(Core::ConfigFile::open(filename, file_or_error.release_value())); auto object = JS::Object::create(realm, realm.intrinsics().object_prototype()); @@ -355,11 +359,11 @@ static JS::ThrowCompletionOr load_json_impl(JS::VM& vm) auto filename = TRY(vm.argument(0).to_string(vm)); auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read); if (file_or_error.is_error()) - return vm.throw_completion(DeprecatedString::formatted("Failed to open '{}': {}", filename, file_or_error.error())); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Failed to open '{}': {}", filename, file_or_error.error()))); auto file_contents_or_error = file_or_error.value()->read_until_eof(); if (file_contents_or_error.is_error()) - return vm.throw_completion(DeprecatedString::formatted("Failed to read '{}': {}", filename, file_contents_or_error.error())); + return vm.throw_completion(TRY_OR_THROW_OOM(vm, String::formatted("Failed to read '{}': {}", filename, file_contents_or_error.error()))); auto json = JsonValue::from_string(file_contents_or_error.value()); if (json.is_error()) @@ -448,7 +452,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReplObject::print) { auto result = ::print(vm.argument(0)); if (result.is_error()) - return g_vm->throw_completion(DeprecatedString::formatted("Failed to print value: {}", result.error())); + return g_vm->throw_completion(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error()))); outln(); @@ -482,7 +486,7 @@ JS_DEFINE_NATIVE_FUNCTION(ScriptObject::print) { auto result = ::print(vm.argument(0)); if (result.is_error()) - return g_vm->throw_completion(DeprecatedString::formatted("Failed to print value: {}", result.error())); + return g_vm->throw_completion(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error()))); outln();