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.
This commit is contained in:
Timothy Flynn 2023-02-16 14:09:11 -05:00 committed by Tim Flynn
parent 153b793638
commit 88814acbd3
Notes: sideshowbarker 2024-07-17 02:38:39 +09:00
36 changed files with 198 additions and 151 deletions

View File

@ -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<JS::TypeError>("No union types matched");
return vm.throw_completion<JS::TypeError>("No union types matched"sv);
)~~~");
}

View File

@ -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<bool> 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<JS::Value> result { JS::js_undefined() };
auto run_script_or_module = [&](auto& script_or_module) {
auto run_script_or_module = [&](auto& script_or_module) -> ErrorOr<ReturnEarly> {
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<JS::InternalError>(executable_result.error().to_deprecated_string());
result = g_vm->throw_completion<JS::InternalError>(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<JS::SyntaxError>(error.to_deprecated_string());
auto error_string = TRY(error.to_string());
displayln("{}", error_string);
result = interpreter.vm().throw_completion<JS::SyntaxError>(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<JS::SyntaxError>(error.to_deprecated_string());
auto error_string = TRY(error.to_string());
displayln("{}", error_string);
result = interpreter.vm().throw_completion<JS::SyntaxError>(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<JS::InternalError>(DeprecatedString::formatted("Failed to print value: {}", result.error()));
return g_vm->throw_completion<JS::InternalError>(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();
}
}

View File

@ -91,9 +91,15 @@ static Result<void, TestError> 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<JS::InternalError>(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<JS::InternalError>(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;

View File

@ -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<JS::TypeError>(strerror(file.error().code()));
return vm.throw_completion<JS::TypeError>(error_code_to_string(file.error().code()));
auto file_size = file.value()->size();
if (file_size.is_error())
return vm.throw_completion<JS::TypeError>(strerror(file_size.error().code()));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>(strerror(read.error().code()));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>("Link failed");
return vm.throw_completion<JS::TypeError>("Link failed"sv);
auto result = machine().instantiate(*instance->m_module, link_result.release_value());
if (result.is_error())
return vm.throw_completion<JS::TypeError>(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<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"sv);
auto& array = static_cast<JS::Uint8Array&>(*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<JS::TypedArrayBase>(lhs))
return vm.throw_completion<JS::TypeError>("Expected a TypedArray");
return vm.throw_completion<JS::TypeError>("Expected a TypedArray"sv);
auto& lhs_array = static_cast<JS::TypedArrayBase&>(*lhs);
auto* rhs = TRY(vm.argument(1).to_object(vm));
if (!is<JS::TypedArrayBase>(rhs))
return vm.throw_completion<JS::TypeError>("Expected a TypedArray");
return vm.throw_completion<JS::TypeError>("Expected a TypedArray"sv);
auto& rhs_array = static_cast<JS::TypedArrayBase&>(*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<WebAssemblyModule>(object))
return vm.throw_completion<JS::TypeError>("Not a WebAssemblyModule");
return vm.throw_completion<JS::TypeError>("Not a WebAssemblyModule"sv);
auto instance = static_cast<WebAssemblyModule*>(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<double>(ref.address.value())); });
});
}
return vm.throw_completion<JS::TypeError>(DeprecatedString::formatted("'{}' does not refer to a function or a global", name));
return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("'{}' does not refer to a function or a global", name)));
}
}
return vm.throw_completion<JS::TypeError>(DeprecatedString::formatted("'{}' could not be found", name));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>("Invalid function address");
return vm.throw_completion<JS::TypeError>("Invalid function address"sv);
Wasm::FunctionType const* type { nullptr };
function_instance->visit([&](auto& value) { type = &value.type(); });
if (!type)
return vm.throw_completion<JS::TypeError>("Invalid function found at given address");
return vm.throw_completion<JS::TypeError>("Invalid function found at given address"sv);
Vector<Wasm::Value> arguments;
if (type->parameters().size() + 1 > vm.argument_count())
return vm.throw_completion<JS::TypeError>(DeprecatedString::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count()));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>(DeprecatedString::formatted("Execution trapped: {}", result.trap().reason));
return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Execution trapped: {}", result.trap().reason)));
if (result.values().is_empty())
return JS::js_null();

View File

@ -193,14 +193,14 @@ JS_DEFINE_NATIVE_FUNCTION(SheetGlobalObject::get_real_cell_contents)
auto sheet_object = static_cast<SheetGlobalObject*>(this_object);
if (vm.argument_count() != 1)
return vm.throw_completion<JS::TypeError>("Expected exactly one argument to get_real_cell_contents()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Expected a String argument to get_real_cell_contents()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Invalid cell name");
return vm.throw_completion<JS::TypeError>("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<SheetGlobalObject*>(this_object);
if (vm.argument_count() != 2)
return vm.throw_completion<JS::TypeError>("Expected exactly two arguments to set_real_cell_contents()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Expected the first argument of set_real_cell_contents() to be a String");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Invalid cell name");
return vm.throw_completion<JS::TypeError>("Invalid cell name"sv);
auto new_contents_value = vm.argument(1);
if (!new_contents_value.is_string())
return vm.throw_completion<JS::TypeError>("Expected the second argument of set_real_cell_contents() to be a String");
return vm.throw_completion<JS::TypeError>("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<SheetGlobalObject*>(this_object);
if (vm.argument_count() != 1)
return vm.throw_completion<JS::TypeError>("Expected exactly one argument to parse_cell_name()");
return vm.throw_completion<JS::TypeError>("Expected exactly one argument to parse_cell_name()"sv);
auto name_value = vm.argument(0);
if (!name_value.is_string())
return vm.throw_completion<JS::TypeError>("Expected a String argument to parse_cell_name()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Expected no arguments to current_cell_position()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Expected exactly one argument to column_index()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>(DeprecatedString::formatted("'{}' is not a valid column", column_name_str));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>("Expected exactly two arguments to column_arithmetic()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>(DeprecatedString::formatted("'{}' is not a valid column", column_name_str));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>("Expected exactly one argument to get_column_bound()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>(DeprecatedString::formatted("'{}' is not a valid column", column_name_str));
return vm.throw_completion<JS::TypeError>(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<JS::TypeError>("Expected exactly one argument to sheet()");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Expected a String or Number argument to sheet()");
return vm.throw_completion<JS::TypeError>("Expected a String or Number argument to sheet()"sv);
auto* this_object = TRY(vm.this_value().to_object(vm));

View File

@ -172,7 +172,7 @@ JS::ThrowCompletionOr<JS::Value> Sheet::evaluate(StringView source, Cell* on_beh
name);
if (script_or_error.is_error())
return interpreter().vm().throw_completion<JS::SyntaxError>(script_or_error.error().first().to_deprecated_string());
return interpreter().vm().throw_completion<JS::SyntaxError>(TRY_OR_THROW_OOM(interpreter().vm(), script_or_error.error().first().to_string()));
return interpreter().run(script_or_error.value());
}

View File

@ -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));

View File

@ -320,17 +320,17 @@ ThrowCompletionOr<void> NewRegExp::execute_impl(Bytecode::Interpreter& interpret
return {};
}
#define JS_DEFINE_NEW_BUILTIN_ERROR_OP(ErrorName) \
ThrowCompletionOr<void> 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<void> 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<void> 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<InternalError>(DeprecatedString::formatted("Lexical environment already has binding '{}'", name));
return vm.throw_completion<InternalError>(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<void> 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<InternalError>("Invalid state for GetObjectPropertyIterator.next");
return vm.throw_completion<InternalError>("Invalid state for GetObjectPropertyIterator.next"sv);
auto& iterated_object = iterated_object_value.as_object();
auto result_object = Object::create(realm, nullptr);

View File

@ -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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
}
// 5. Let status be ScriptEvaluation(s).

View File

@ -602,7 +602,7 @@ ThrowCompletionOr<Value> 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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
}
bool strict_eval = false;
@ -704,7 +704,7 @@ ThrowCompletionOr<Value> 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<InternalError>(ErrorType::NotImplemented, executable_result.error().to_deprecated_string());
return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
auto executable = executable_result.release_value();
executable->name = "eval"sv;

View File

@ -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));

View File

@ -824,7 +824,7 @@ Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
auto compile = [&](auto& node, auto kind, auto name) -> ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> {
auto executable_result = Bytecode::Generator::generate(node, kind);
if (executable_result.is_error())
return vm.throw_completion<InternalError>(ErrorType::NotImplemented, executable_result.error().to_deprecated_string());
return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
auto bytecode_executable = executable_result.release_value();
bytecode_executable->name = name;

View File

@ -10,6 +10,7 @@
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/ExecutionContext.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/ThrowableStringBuilder.h>
#include <LibJS/SourceRange.h>
namespace JS {
@ -19,15 +20,20 @@ NonnullGCPtr<Error> Error::create(Realm& realm)
return realm.heap().allocate<Error>(realm, *realm.intrinsics().error_prototype()).release_allocated_value_but_fixme_should_propagate_errors();
}
NonnullGCPtr<Error> Error::create(Realm& realm, DeprecatedString const& message)
NonnullGCPtr<Error> 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<NonnullGCPtr<Error>> 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<String> 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 == "<unknown>"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() ? "<unknown>"sv : function_name.view());
MUST_OR_THROW_OOM(stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? "<unknown>"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<ClassName>(realm, *realm.intrinsics().snake_name##_prototype()).release_allocated_value_but_fixme_should_propagate_errors(); \
} \
\
NonnullGCPtr<ClassName> ClassName::create(Realm& realm, DeprecatedString const& message) \
NonnullGCPtr<ClassName> 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<NonnullGCPtr<ClassName>> 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) \
{ \

View File

@ -8,6 +8,7 @@
#pragma once
#include <AK/DeprecatedFlyString.h>
#include <AK/String.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/SourceRange.h>
@ -24,11 +25,12 @@ class Error : public Object {
public:
static NonnullGCPtr<Error> create(Realm&);
static NonnullGCPtr<Error> create(Realm&, DeprecatedString const& message);
static NonnullGCPtr<Error> create(Realm&, String message);
static ThrowCompletionOr<NonnullGCPtr<Error>> create(Realm&, StringView message);
virtual ~Error() override = default;
[[nodiscard]] DeprecatedString stack_string() const;
[[nodiscard]] ThrowCompletionOr<String> stack_string(VM&) const;
ThrowCompletionOr<void> 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<ClassName> create(Realm&); \
static NonnullGCPtr<ClassName> 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<ClassName> create(Realm&); \
static NonnullGCPtr<ClassName> create(Realm&, String message); \
static ThrowCompletionOr<NonnullGCPtr<ClassName>> create(Realm&, StringView message); \
\
explicit ClassName(Object& prototype); \
virtual ~ClassName() override = default; \
};
#define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \

View File

@ -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

View File

@ -178,7 +178,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> 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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
}
// 18. Let body be ParseText(StringToCodePoints(bodyString), bodySym).
@ -195,7 +195,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> 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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(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<ECMAScriptFunctionObject*> 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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
}
// 24. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto).

View File

@ -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<Value> {
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);

View File

@ -107,7 +107,7 @@ ThrowCompletionOr<Value> 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<SyntaxError>(error.to_deprecated_string());
return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
}
// c. If script Contains ScriptBody is false, return undefined.
@ -272,7 +272,7 @@ ThrowCompletionOr<Value> 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<Value> {
return vm.template throw_completion<TypeError>(TRY(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().deprecated_string()));
return vm.template throw_completion<TypeError>(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).

View File

@ -90,7 +90,7 @@ VM::VM(OwnPtr<CustomData> 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<Value> {
@ -154,10 +154,10 @@ VM::VM(OwnPtr<CustomData> 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<Empty>()) {
// 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;
}
}

View File

@ -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>(args)...));
auto completion = T::create(realm, forward<Args>(args)...);
if constexpr (IsSame<decltype(completion), ThrowCompletionOr<NonnullGCPtr<T>>>)
return JS::throw_completion(MUST_OR_THROW_OOM(completion));
else
return JS::throw_completion(completion);
}
template<typename T, typename... Args>
@ -296,7 +301,7 @@ private:
PrimitiveString* m_empty_string { nullptr };
PrimitiveString* m_single_ascii_character_strings[128] {};
AK::Array<DeprecatedString, to_underlying(ErrorMessage::__Count)> m_error_messages;
AK::Array<String, to_underlying(ErrorMessage::__Count)> m_error_messages;
struct StoredModule {
ScriptOrModule referencing_script_or_module;

View File

@ -485,7 +485,7 @@ inline JSFileResult TestRunner::run_file_test(DeprecatedString const& test_path)
if (is<JS::Error>(error_object)) {
auto& error_as_error = static_cast<JS::Error&>(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();

View File

@ -219,7 +219,7 @@ JS::ThrowCompletionOr<JS::Value> fetch(JS::VM& vm)
}
return record_union_type;
}
return vm.throw_completion<JS::TypeError>("No union types matched");
return vm.throw_completion<JS::TypeError>("No union types matched"sv);
};
Optional<Variant<Vector<Vector<DeprecatedString>>, OrderedHashMap<DeprecatedString, DeprecatedString>>> headers_value;
if (!headers_property_value.is_nullish())

View File

@ -68,7 +68,7 @@ JS::VM& main_thread_vm()
vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
// 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
if (is<HTML::WindowProxy>(object) || is<HTML::Location>(object))
return vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object");
return vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
// 2. Return NormalCompletion(unused).
return {};

View File

@ -148,7 +148,7 @@ JS::NonnullGCPtr<JS::Promise> 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<JS::Promise>(*promise_capability->promise().ptr());
}

View File

@ -100,7 +100,7 @@ JS::NonnullGCPtr<JS::Promise> 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;
}

View File

@ -52,7 +52,7 @@ JS::NonnullGCPtr<WebIDL::Promise> 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

View File

@ -89,7 +89,7 @@ JS::ThrowCompletionOr<void> 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<JS::URIError>(DeprecatedString::formatted("Invalid URL '{}'", new_href));
return vm.throw_completion<JS::URIError>(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);

View File

@ -90,7 +90,7 @@ JS::Completion ClassicScript::run(RethrowErrors rethrow_errors, JS::GCPtr<JS::En
// 5. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.
if (m_error_to_rethrow.has_value()) {
evaluation_status = vm.throw_completion<JS::SyntaxError>(m_error_to_rethrow.value().to_deprecated_string());
evaluation_status = vm.throw_completion<JS::SyntaxError>(TRY_OR_THROW_OOM(vm, m_error_to_rethrow.value().to_string()));
} else {
auto timer = Core::ElapsedTimer::start_new();

View File

@ -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

View File

@ -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<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'");
return vm.throw_completion<JS::TypeError>("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.

View File

@ -44,7 +44,7 @@ JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> WebAssemblyMemoryConstructor
auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::MemoryType { Wasm::Limits { initial, maximum } });
if (!address.has_value())
return vm.throw_completion<JS::TypeError>("Wasm Memory allocation failed");
return vm.throw_completion<JS::TypeError>("Wasm Memory allocation failed"sv);
return MUST_OR_THROW_OOM(vm.heap().allocate<WebAssemblyMemoryObject>(realm, realm, *address));
}

View File

@ -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<JS::TypeError>("Memory.grow() grows past the stated limit of the memory instance");
return vm.throw_completion<JS::TypeError>("Memory.grow() grows past the stated limit of the memory instance"sv);
return JS::Value(static_cast<u32>(previous_size));
}

View File

@ -17,6 +17,7 @@
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/DataView.h>
#include <LibJS/Runtime/ThrowableStringBuilder.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibWasm/AbstractMachine/Interpreter.h>
#include <LibWasm/AbstractMachine/Validator.h>
@ -119,7 +120,7 @@ JS::ThrowCompletionOr<size_t> parse_module(JS::VM& vm, JS::Object* buffer_object
auto& buffer = static_cast<JS::DataView&>(*buffer_object);
data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
} else {
return vm.throw_completion<JS::TypeError>("Not a BufferSource");
return vm.throw_completion<JS::TypeError>("Not a BufferSource"sv);
}
FixedMemoryStream stream { data };
auto module_result = Wasm::Module::parse(stream);
@ -233,11 +234,11 @@ JS::ThrowCompletionOr<size_t> 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<JS::TypeError>("LinkError: Import resolution attempted to cast a Number to a BigInteger");
return vm.throw_completion<JS::TypeError>("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<JS::TypeError>("LinkError: Import resolution attempted to cast a BigInteger to a Number");
return vm.throw_completion<JS::TypeError>("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<size_t> WebAssemblyObject::instantiate_module(JS::VM& vm,
// let globaladdr be v.[[Global]]
// FIXME: Throw a LinkError instead
return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type");
return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type"sv);
}
resolved_imports.set(import_name, Wasm::ExternValue { *address });
@ -256,7 +257,7 @@ JS::ThrowCompletionOr<size_t> WebAssemblyObject::instantiate_module(JS::VM& vm,
[&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
if (!import_.is_object() || !is<WebAssemblyMemoryObject>(import_.as_object())) {
// FIXME: Throw a LinkError instead
return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import");
return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv);
}
auto address = static_cast<WebAssemblyMemoryObject const&>(import_.as_object()).address();
resolved_imports.set(import_name, Wasm::ExternValue { address });
@ -265,7 +266,7 @@ JS::ThrowCompletionOr<size_t> WebAssemblyObject::instantiate_module(JS::VM& vm,
[&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
if (!import_.is_object() || !is<WebAssemblyTableObject>(import_.as_object())) {
// FIXME: Throw a LinkError instead
return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import");
return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import"sv);
}
auto address = static_cast<WebAssemblyTableObject const&>(import_.as_object()).address();
resolved_imports.set(import_name, Wasm::ExternValue { address });
@ -274,7 +275,7 @@ JS::ThrowCompletionOr<size_t> WebAssemblyObject::instantiate_module(JS::VM& vm,
[&](auto const&) -> JS::ThrowCompletionOr<void> {
// FIXME: Implement these.
dbgln("Unimplemented import of non-function attempted");
return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented");
return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented"sv);
}));
}
}
@ -283,10 +284,10 @@ JS::ThrowCompletionOr<size_t> 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<JS::TypeError>(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<JS::TypeError>(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<WebAssemblyModuleObject>(buffer)) {
module = &static_cast<WebAssemblyModuleObject*>(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<JS::TypeError>(DeprecatedString::formatted("Wasm execution trapped (WIP): {}", result.trap().reason));
return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)));
if (result.values().is_empty())
return JS::js_undefined();

View File

@ -57,7 +57,7 @@ JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> WebAssemblyTableConstructor:
maximum = TRY(maximum_value.to_u32(vm));
if (maximum.has_value() && maximum.value() < initial)
return vm.throw_completion<JS::RangeError>("maximum should be larger than or equal to initial");
return vm.throw_completion<JS::RangeError>("maximum should be larger than or equal to initial"sv);
auto value_value = TRY(descriptor->get("value"));
auto reference_value = TRY([&]() -> JS::ThrowCompletionOr<Wasm::Value> {
@ -71,7 +71,7 @@ JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> 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<JS::TypeError>("Wasm Table allocation failed");
return vm.throw_completion<JS::TypeError>("Wasm Table allocation failed"sv);
auto& table = *WebAssemblyObject::s_abstract_machine.store().get(*address);
for (auto& element : table.elements())

View File

@ -47,7 +47,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyTablePrototype::grow)
auto& reference = reference_value.value().get<Wasm::Reference>();
if (!table->grow(delta, reference))
return vm.throw_completion<JS::RangeError>("Failed to grow table");
return vm.throw_completion<JS::RangeError>("Failed to grow table"sv);
return JS::Value(static_cast<u32>(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<JS::RangeError>("Table element index out of range");
return vm.throw_completion<JS::RangeError>("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<JS::RangeError>("Table element index out of range");
return vm.throw_completion<JS::RangeError>("Table element index out of range"sv);
auto value_value = vm.argument(1);
auto reference_value = TRY([&]() -> JS::ThrowCompletionOr<Wasm::Value> {

View File

@ -207,14 +207,14 @@ static ErrorOr<bool> parse_and_run(JS::Interpreter& interpreter, StringView sour
JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };
auto run_script_or_module = [&](auto& script_or_module) {
auto run_script_or_module = [&](auto& script_or_module) -> ErrorOr<ReturnEarly> {
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<JS::InternalError>(executable_result.error().to_deprecated_string());
result = g_vm->throw_completion<JS::InternalError>(TRY(executable_result.error().to_string()));
return ReturnEarly::No;
}
@ -253,10 +253,12 @@ static ErrorOr<bool> 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<JS::SyntaxError>(error.to_deprecated_string());
auto error_string = TRY(error.to_string());
outln("{}", error_string);
result = interpreter.vm().throw_completion<JS::SyntaxError>(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<bool> 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<JS::SyntaxError>(error.to_deprecated_string());
auto error_string = TRY(error.to_string());
outln("{}", error_string);
result = interpreter.vm().throw_completion<JS::SyntaxError>(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<JS::Value> 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<JS::Error>(DeprecatedString::formatted("Failed to open '{}': {}", filename, file_or_error.error()));
return vm.throw_completion<JS::Error>(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<JS::Value> 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<JS::Error>(DeprecatedString::formatted("Failed to open '{}': {}", filename, file_or_error.error()));
return vm.throw_completion<JS::Error>(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<JS::Error>(DeprecatedString::formatted("Failed to read '{}': {}", filename, file_contents_or_error.error()));
return vm.throw_completion<JS::Error>(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<JS::InternalError>(DeprecatedString::formatted("Failed to print value: {}", result.error()));
return g_vm->throw_completion<JS::InternalError>(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<JS::InternalError>(DeprecatedString::formatted("Failed to print value: {}", result.error()));
return g_vm->throw_completion<JS::InternalError>(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error())));
outln();