2020-09-20 19:24:44 +02:00
|
|
|
/*
|
2024-10-04 13:19:50 +02:00
|
|
|
* Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
|
2023-02-11 16:14:41 +00:00
|
|
|
* Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
|
2022-01-19 01:22:58 +01:00
|
|
|
* Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
|
2023-10-29 02:53:53 +01:00
|
|
|
* Copyright (c) 2023, networkException <networkexception@serenityos.org>
|
2020-09-20 19:24:44 +02:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-09-20 19:24:44 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2023-01-08 19:23:00 -05:00
|
|
|
#include <AK/DeprecatedFlyString.h>
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
#include <AK/Function.h>
|
2020-09-22 16:18:51 +02:00
|
|
|
#include <AK/HashMap.h>
|
2020-09-20 19:24:44 +02:00
|
|
|
#include <AK/RefCounted.h>
|
2020-11-08 12:48:16 +00:00
|
|
|
#include <AK/StackInfo.h>
|
2021-05-29 16:03:19 +04:30
|
|
|
#include <AK/Variant.h>
|
2023-10-29 02:53:53 +01:00
|
|
|
#include <LibJS/CyclicModule.h>
|
2020-09-20 19:24:44 +02:00
|
|
|
#include <LibJS/Heap/Heap.h>
|
2022-02-09 10:06:40 +00:00
|
|
|
#include <LibJS/Heap/MarkedVector.h>
|
2023-12-02 16:20:01 +01:00
|
|
|
#include <LibJS/ModuleLoading.h>
|
2020-10-13 23:49:19 +02:00
|
|
|
#include <LibJS/Runtime/CommonPropertyNames.h>
|
LibJS: Add a JS::Completion class and JS::ThrowCompletionOr<T> template
We decided that we want to move away from throwing exceptions in AOs
and regular functions implicitly and then returning some
default-constructed value (usually an empty JS::Value) - this requires
remembering to check for an exception at the call site, which is
error-prone. It's also awkward for return values that cannot be
default-constructed, e.g. MarkedValueList.
Instead, the thrown value should be part of the function return value.
The solution to this is moving closer to the spec and using something
they call "completion records":
https://tc39.es/ecma262/#sec-completion-record-specification-type
This has various advantages:
- It becomes crystal clear whether some AO can fail or not, and errors
need to be handled and values unwrapped explicitly (for that reason
compatibility with the TRY() macro is already built-in, and a similar
TRY_OR_DISCARD() macro has been added specifically for use in LibJS,
while the majority of functions doesn't return ThrowCompletionOr yet)
- We no longer need to mix "valid" and "invalid" values of various types
for the success and exception outcomes (e.g. null/non-null AK::String,
empty/non-empty JS::Value)
- Subsequently it's no longer possible to accidentally use an exception
outcome return value as a success outcome return value (e.g. any AO
that returns a numeric type would return 0 even after throwing an
exception, at least before we started making use of Optional for that)
- Eventually the VM will no longer need to store an exception, and
temporarily clearing an exception (e.g. to call a function) becomes
obsolete - instead, completions will simply propagate up to the caller
outside of LibJS, which then can deal with it in any way
- Similar to throw we'll be able to implement the functionality of
break, continue, and return using completions, which will lead to
easier to understand code and fewer workarounds - the current
unwinding mechanism is not even remotely similar to the spec's
approach
The spec's NormalCompletion and ThrowCompletion AOs have been
implemented as simple wrappers around the JS::Completion constructor.
UpdateEmpty has been implemented as a JS::Completion method.
There's also a new VM::throw_completion<T>() helper, which basically
works like VM::throw_exception<T>() - it creates a T object (usually a
JS::Error), and returns it wrapped in a JS::Completion of Type::Throw.
Two temporary usage patterns have emerged:
1. Callee already returns ThrowCompletionOr, but caller doesn't:
auto foo = TRY_OR_DISCARD(bar());
2. Caller already returns ThrowCompletionOr, but callee doesn't:
auto foo = bar();
if (auto* exception = vm.exception())
return throw_completion(exception->value());
Eventually all error handling and unwrapping can be done with just TRY()
or possibly even operator? in the future :^)
Co-authored-by: Andreas Kling <kling@serenityos.org>
2021-09-15 20:46:51 +01:00
|
|
|
#include <LibJS/Runtime/Completion.h>
|
2020-11-08 12:54:52 +00:00
|
|
|
#include <LibJS/Runtime/Error.h>
|
2020-09-27 15:18:55 +02:00
|
|
|
#include <LibJS/Runtime/ErrorTypes.h>
|
2021-09-14 18:21:07 +02:00
|
|
|
#include <LibJS/Runtime/ExecutionContext.h>
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
#include <LibJS/Runtime/Promise.h>
|
2020-09-27 15:18:55 +02:00
|
|
|
#include <LibJS/Runtime/Value.h>
|
2020-09-20 19:24:44 +02:00
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
2021-05-29 16:03:19 +04:30
|
|
|
class Identifier;
|
|
|
|
struct BindingPattern;
|
|
|
|
|
2023-10-14 19:10:55 -04:00
|
|
|
enum class HandledByHost {
|
|
|
|
Handled,
|
|
|
|
Unhandled,
|
|
|
|
};
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
class VM : public RefCounted<VM> {
|
|
|
|
public:
|
2021-09-08 22:58:36 +02:00
|
|
|
struct CustomData {
|
2022-03-14 10:25:06 -06:00
|
|
|
virtual ~CustomData() = default;
|
2022-09-08 00:13:39 +02:00
|
|
|
|
2024-05-17 17:09:20 -07:00
|
|
|
virtual void spin_event_loop_until(JS::SafeFunction<bool()> goal_condition) = 0;
|
2021-09-08 22:58:36 +02:00
|
|
|
};
|
|
|
|
|
2023-03-17 10:44:47 -04:00
|
|
|
static ErrorOr<NonnullRefPtr<VM>> create(OwnPtr<CustomData> = {});
|
2023-06-22 15:59:18 +02:00
|
|
|
~VM();
|
2020-09-20 19:24:44 +02:00
|
|
|
|
|
|
|
Heap& heap() { return m_heap; }
|
2022-04-01 20:58:27 +03:00
|
|
|
Heap const& heap() const { return m_heap; }
|
2020-09-20 19:24:44 +02:00
|
|
|
|
2023-06-22 15:59:18 +02:00
|
|
|
Bytecode::Interpreter& bytecode_interpreter();
|
|
|
|
|
2021-06-06 22:53:44 +02:00
|
|
|
void dump_backtrace() const;
|
|
|
|
|
2023-09-22 02:04:16 +02:00
|
|
|
void gather_roots(HashMap<Cell*, HeapRoot>&);
|
2020-09-21 13:47:33 +02:00
|
|
|
|
2023-04-13 01:14:45 +02:00
|
|
|
#define __JS_ENUMERATE(SymbolName, snake_name) \
|
|
|
|
NonnullGCPtr<Symbol> well_known_symbol_##snake_name() const \
|
|
|
|
{ \
|
|
|
|
return *m_well_known_symbols.snake_name; \
|
2022-08-20 09:48:43 +01:00
|
|
|
}
|
2020-09-22 16:18:51 +02:00
|
|
|
JS_ENUMERATE_WELL_KNOWN_SYMBOLS
|
|
|
|
#undef __JS_ENUMERATE
|
|
|
|
|
2023-02-26 16:09:02 -07:00
|
|
|
HashMap<String, GCPtr<PrimitiveString>>& string_cache()
|
2023-01-13 12:24:02 -05:00
|
|
|
{
|
|
|
|
return m_string_cache;
|
|
|
|
}
|
|
|
|
|
2023-12-16 17:49:34 +03:30
|
|
|
HashMap<ByteString, GCPtr<PrimitiveString>>& byte_string_cache()
|
2022-12-06 21:06:56 +00:00
|
|
|
{
|
2023-12-16 17:49:34 +03:30
|
|
|
return m_byte_string_cache;
|
2022-12-06 21:06:56 +00:00
|
|
|
}
|
2023-01-13 12:24:02 -05:00
|
|
|
|
2024-10-24 23:02:10 +02:00
|
|
|
HashMap<Utf16String, GCPtr<PrimitiveString>>& utf16_string_cache()
|
|
|
|
{
|
|
|
|
return m_utf16_string_cache;
|
|
|
|
}
|
|
|
|
|
2020-09-22 16:36:33 +02:00
|
|
|
PrimitiveString& empty_string() { return *m_empty_string; }
|
2023-01-13 12:24:02 -05:00
|
|
|
|
2020-10-22 17:43:48 +02:00
|
|
|
PrimitiveString& single_ascii_character_string(u8 character)
|
|
|
|
{
|
2021-02-23 20:42:32 +01:00
|
|
|
VERIFY(character < 0x80);
|
2020-10-22 17:43:48 +02:00
|
|
|
return *m_single_ascii_character_strings[character];
|
|
|
|
}
|
2020-09-22 16:36:33 +02:00
|
|
|
|
2023-02-16 12:55:22 -05:00
|
|
|
// This represents the list of errors from ErrorTypes.h whose messages are used in contexts which
|
|
|
|
// must not fail to allocate when they are used. For example, we cannot allocate when we raise an
|
|
|
|
// out-of-memory error, thus we pre-allocate that error string at VM creation time.
|
|
|
|
enum class ErrorMessage {
|
|
|
|
OutOfMemory,
|
|
|
|
|
|
|
|
// Keep this last:
|
|
|
|
__Count,
|
|
|
|
};
|
2023-02-16 14:09:11 -05:00
|
|
|
String const& error_message(ErrorMessage) const;
|
2023-02-16 12:55:22 -05:00
|
|
|
|
2021-08-13 12:59:57 -04:00
|
|
|
bool did_reach_stack_space_limit() const
|
|
|
|
{
|
2024-05-08 10:03:43 -04:00
|
|
|
#if defined(AK_OS_MACOS) && defined(HAS_ADDRESS_SANITIZER)
|
|
|
|
// We hit stack limits sooner on macOS 14 arm64 with ASAN enabled.
|
|
|
|
return m_stack_info.size_free() < 96 * KiB;
|
|
|
|
#else
|
2024-02-20 14:09:26 -05:00
|
|
|
return m_stack_info.size_free() < 32 * KiB;
|
2024-05-08 10:03:43 -04:00
|
|
|
#endif
|
2021-08-13 12:59:57 -04:00
|
|
|
}
|
|
|
|
|
2022-08-21 20:38:35 +01:00
|
|
|
// TODO: Rename this function instead of providing a second argument, now that the global object is no longer passed in.
|
|
|
|
struct CheckStackSpaceLimitTag { };
|
|
|
|
|
|
|
|
ThrowCompletionOr<void> push_execution_context(ExecutionContext& context, CheckStackSpaceLimitTag)
|
2020-09-27 15:18:55 +02:00
|
|
|
{
|
2020-11-08 12:54:52 +00:00
|
|
|
// Ensure we got some stack space left, so the next function call doesn't kill us.
|
2021-08-13 12:59:57 -04:00
|
|
|
if (did_reach_stack_space_limit())
|
2022-08-16 20:33:17 +01:00
|
|
|
return throw_completion<InternalError>(ErrorType::CallStackSizeExceeded);
|
2023-09-02 17:38:17 +02:00
|
|
|
push_execution_context(context);
|
2021-11-14 12:20:49 +00:00
|
|
|
return {};
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
2020-11-07 11:07:17 +01:00
|
|
|
|
2023-09-02 17:38:17 +02:00
|
|
|
void push_execution_context(ExecutionContext&);
|
|
|
|
void pop_execution_context();
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2022-12-07 00:12:07 +00:00
|
|
|
// https://tc39.es/ecma262/#running-execution-context
|
|
|
|
// At any point in time, there is at most one execution context per agent that is actually executing code.
|
|
|
|
// This is known as the agent's running execution context.
|
2023-12-18 17:21:29 -07:00
|
|
|
ExecutionContext& running_execution_context()
|
|
|
|
{
|
|
|
|
VERIFY(!m_execution_context_stack.is_empty());
|
|
|
|
return *m_execution_context_stack.last();
|
|
|
|
}
|
|
|
|
ExecutionContext const& running_execution_context() const
|
|
|
|
{
|
|
|
|
VERIFY(!m_execution_context_stack.is_empty());
|
|
|
|
return *m_execution_context_stack.last();
|
|
|
|
}
|
2022-12-07 00:12:07 +00:00
|
|
|
|
2022-12-07 00:12:23 +00:00
|
|
|
// https://tc39.es/ecma262/#execution-context-stack
|
|
|
|
// The execution context stack is used to track execution contexts.
|
2021-06-24 19:17:45 +02:00
|
|
|
Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
|
|
|
|
Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
|
2020-11-07 11:07:17 +01:00
|
|
|
|
2021-07-01 12:24:46 +02:00
|
|
|
Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
|
|
|
|
Environment* lexical_environment() { return running_execution_context().lexical_environment; }
|
2021-06-22 15:42:44 +02:00
|
|
|
|
2021-07-01 12:24:46 +02:00
|
|
|
Environment const* variable_environment() const { return running_execution_context().variable_environment; }
|
|
|
|
Environment* variable_environment() { return running_execution_context().variable_environment; }
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2021-09-11 20:55:11 +01:00
|
|
|
// https://tc39.es/ecma262/#current-realm
|
|
|
|
// The value of the Realm component of the running execution context is also called the current Realm Record.
|
|
|
|
Realm const* current_realm() const { return running_execution_context().realm; }
|
|
|
|
Realm* current_realm() { return running_execution_context().realm; }
|
|
|
|
|
2022-01-15 00:30:52 +01:00
|
|
|
// https://tc39.es/ecma262/#active-function-object
|
|
|
|
// The value of the Function component of the running execution context is also called the active function object.
|
|
|
|
FunctionObject const* active_function_object() const { return running_execution_context().function; }
|
|
|
|
FunctionObject* active_function_object() { return running_execution_context().function; }
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
bool in_strict_mode() const;
|
|
|
|
|
|
|
|
size_t argument_count() const
|
|
|
|
{
|
2021-06-24 19:17:45 +02:00
|
|
|
if (m_execution_context_stack.is_empty())
|
2020-09-27 15:18:55 +02:00
|
|
|
return 0;
|
2021-06-24 19:17:45 +02:00
|
|
|
return running_execution_context().arguments.size();
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Value argument(size_t index) const
|
|
|
|
{
|
2021-06-24 19:17:45 +02:00
|
|
|
if (m_execution_context_stack.is_empty())
|
2020-09-27 15:18:55 +02:00
|
|
|
return {};
|
2023-11-27 16:45:45 +01:00
|
|
|
return running_execution_context().argument(index);
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
|
2022-08-20 09:48:43 +01:00
|
|
|
Value this_value() const
|
2020-09-27 15:18:55 +02:00
|
|
|
{
|
2021-06-24 19:17:45 +02:00
|
|
|
return running_execution_context().this_value;
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
|
2022-08-21 15:12:43 +01:00
|
|
|
ThrowCompletionOr<Value> resolve_this_binding();
|
2021-06-25 11:40:03 +02:00
|
|
|
|
2023-07-07 22:48:11 -04:00
|
|
|
StackInfo const& stack_info() const { return m_stack_info; }
|
2020-11-08 12:48:16 +00:00
|
|
|
|
2023-02-11 16:14:41 +00:00
|
|
|
HashMap<String, NonnullGCPtr<Symbol>> const& global_symbol_registry() const { return m_global_symbol_registry; }
|
|
|
|
HashMap<String, NonnullGCPtr<Symbol>>& global_symbol_registry() { return m_global_symbol_registry; }
|
2022-12-06 21:02:06 +00:00
|
|
|
|
2021-06-12 17:32:54 +03:00
|
|
|
u32 execution_generation() const { return m_execution_generation; }
|
|
|
|
void finish_execution_generation() { ++m_execution_generation; }
|
|
|
|
|
2023-01-08 19:23:00 -05:00
|
|
|
ThrowCompletionOr<Reference> resolve_binding(DeprecatedFlyString const&, Environment* = nullptr);
|
|
|
|
ThrowCompletionOr<Reference> get_identifier_reference(Environment*, DeprecatedFlyString, bool strict, size_t hops = 0);
|
2020-09-27 15:18:55 +02:00
|
|
|
|
LibJS: Add a JS::Completion class and JS::ThrowCompletionOr<T> template
We decided that we want to move away from throwing exceptions in AOs
and regular functions implicitly and then returning some
default-constructed value (usually an empty JS::Value) - this requires
remembering to check for an exception at the call site, which is
error-prone. It's also awkward for return values that cannot be
default-constructed, e.g. MarkedValueList.
Instead, the thrown value should be part of the function return value.
The solution to this is moving closer to the spec and using something
they call "completion records":
https://tc39.es/ecma262/#sec-completion-record-specification-type
This has various advantages:
- It becomes crystal clear whether some AO can fail or not, and errors
need to be handled and values unwrapped explicitly (for that reason
compatibility with the TRY() macro is already built-in, and a similar
TRY_OR_DISCARD() macro has been added specifically for use in LibJS,
while the majority of functions doesn't return ThrowCompletionOr yet)
- We no longer need to mix "valid" and "invalid" values of various types
for the success and exception outcomes (e.g. null/non-null AK::String,
empty/non-empty JS::Value)
- Subsequently it's no longer possible to accidentally use an exception
outcome return value as a success outcome return value (e.g. any AO
that returns a numeric type would return 0 even after throwing an
exception, at least before we started making use of Optional for that)
- Eventually the VM will no longer need to store an exception, and
temporarily clearing an exception (e.g. to call a function) becomes
obsolete - instead, completions will simply propagate up to the caller
outside of LibJS, which then can deal with it in any way
- Similar to throw we'll be able to implement the functionality of
break, continue, and return using completions, which will lead to
easier to understand code and fewer workarounds - the current
unwinding mechanism is not even remotely similar to the spec's
approach
The spec's NormalCompletion and ThrowCompletion AOs have been
implemented as simple wrappers around the JS::Completion constructor.
UpdateEmpty has been implemented as a JS::Completion method.
There's also a new VM::throw_completion<T>() helper, which basically
works like VM::throw_exception<T>() - it creates a T object (usually a
JS::Error), and returns it wrapped in a JS::Completion of Type::Throw.
Two temporary usage patterns have emerged:
1. Callee already returns ThrowCompletionOr, but caller doesn't:
auto foo = TRY_OR_DISCARD(bar());
2. Caller already returns ThrowCompletionOr, but callee doesn't:
auto foo = bar();
if (auto* exception = vm.exception())
return throw_completion(exception->value());
Eventually all error handling and unwrapping can be done with just TRY()
or possibly even operator? in the future :^)
Co-authored-by: Andreas Kling <kling@serenityos.org>
2021-09-15 20:46:51 +01:00
|
|
|
// 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception
|
|
|
|
template<typename T, typename... Args>
|
2022-08-16 20:33:17 +01:00
|
|
|
Completion throw_completion(Args&&... args)
|
LibJS: Add a JS::Completion class and JS::ThrowCompletionOr<T> template
We decided that we want to move away from throwing exceptions in AOs
and regular functions implicitly and then returning some
default-constructed value (usually an empty JS::Value) - this requires
remembering to check for an exception at the call site, which is
error-prone. It's also awkward for return values that cannot be
default-constructed, e.g. MarkedValueList.
Instead, the thrown value should be part of the function return value.
The solution to this is moving closer to the spec and using something
they call "completion records":
https://tc39.es/ecma262/#sec-completion-record-specification-type
This has various advantages:
- It becomes crystal clear whether some AO can fail or not, and errors
need to be handled and values unwrapped explicitly (for that reason
compatibility with the TRY() macro is already built-in, and a similar
TRY_OR_DISCARD() macro has been added specifically for use in LibJS,
while the majority of functions doesn't return ThrowCompletionOr yet)
- We no longer need to mix "valid" and "invalid" values of various types
for the success and exception outcomes (e.g. null/non-null AK::String,
empty/non-empty JS::Value)
- Subsequently it's no longer possible to accidentally use an exception
outcome return value as a success outcome return value (e.g. any AO
that returns a numeric type would return 0 even after throwing an
exception, at least before we started making use of Optional for that)
- Eventually the VM will no longer need to store an exception, and
temporarily clearing an exception (e.g. to call a function) becomes
obsolete - instead, completions will simply propagate up to the caller
outside of LibJS, which then can deal with it in any way
- Similar to throw we'll be able to implement the functionality of
break, continue, and return using completions, which will lead to
easier to understand code and fewer workarounds - the current
unwinding mechanism is not even remotely similar to the spec's
approach
The spec's NormalCompletion and ThrowCompletion AOs have been
implemented as simple wrappers around the JS::Completion constructor.
UpdateEmpty has been implemented as a JS::Completion method.
There's also a new VM::throw_completion<T>() helper, which basically
works like VM::throw_exception<T>() - it creates a T object (usually a
JS::Error), and returns it wrapped in a JS::Completion of Type::Throw.
Two temporary usage patterns have emerged:
1. Callee already returns ThrowCompletionOr, but caller doesn't:
auto foo = TRY_OR_DISCARD(bar());
2. Caller already returns ThrowCompletionOr, but callee doesn't:
auto foo = bar();
if (auto* exception = vm.exception())
return throw_completion(exception->value());
Eventually all error handling and unwrapping can be done with just TRY()
or possibly even operator? in the future :^)
Co-authored-by: Andreas Kling <kling@serenityos.org>
2021-09-15 20:46:51 +01:00
|
|
|
{
|
2022-08-16 20:33:17 +01:00
|
|
|
auto& realm = *current_realm();
|
2023-02-16 14:09:11 -05:00
|
|
|
auto completion = T::create(realm, forward<Args>(args)...);
|
|
|
|
|
2023-09-06 08:18:01 -04:00
|
|
|
return JS::throw_completion(completion);
|
LibJS: Add a JS::Completion class and JS::ThrowCompletionOr<T> template
We decided that we want to move away from throwing exceptions in AOs
and regular functions implicitly and then returning some
default-constructed value (usually an empty JS::Value) - this requires
remembering to check for an exception at the call site, which is
error-prone. It's also awkward for return values that cannot be
default-constructed, e.g. MarkedValueList.
Instead, the thrown value should be part of the function return value.
The solution to this is moving closer to the spec and using something
they call "completion records":
https://tc39.es/ecma262/#sec-completion-record-specification-type
This has various advantages:
- It becomes crystal clear whether some AO can fail or not, and errors
need to be handled and values unwrapped explicitly (for that reason
compatibility with the TRY() macro is already built-in, and a similar
TRY_OR_DISCARD() macro has been added specifically for use in LibJS,
while the majority of functions doesn't return ThrowCompletionOr yet)
- We no longer need to mix "valid" and "invalid" values of various types
for the success and exception outcomes (e.g. null/non-null AK::String,
empty/non-empty JS::Value)
- Subsequently it's no longer possible to accidentally use an exception
outcome return value as a success outcome return value (e.g. any AO
that returns a numeric type would return 0 even after throwing an
exception, at least before we started making use of Optional for that)
- Eventually the VM will no longer need to store an exception, and
temporarily clearing an exception (e.g. to call a function) becomes
obsolete - instead, completions will simply propagate up to the caller
outside of LibJS, which then can deal with it in any way
- Similar to throw we'll be able to implement the functionality of
break, continue, and return using completions, which will lead to
easier to understand code and fewer workarounds - the current
unwinding mechanism is not even remotely similar to the spec's
approach
The spec's NormalCompletion and ThrowCompletion AOs have been
implemented as simple wrappers around the JS::Completion constructor.
UpdateEmpty has been implemented as a JS::Completion method.
There's also a new VM::throw_completion<T>() helper, which basically
works like VM::throw_exception<T>() - it creates a T object (usually a
JS::Error), and returns it wrapped in a JS::Completion of Type::Throw.
Two temporary usage patterns have emerged:
1. Callee already returns ThrowCompletionOr, but caller doesn't:
auto foo = TRY_OR_DISCARD(bar());
2. Caller already returns ThrowCompletionOr, but callee doesn't:
auto foo = bar();
if (auto* exception = vm.exception())
return throw_completion(exception->value());
Eventually all error handling and unwrapping can be done with just TRY()
or possibly even operator? in the future :^)
Co-authored-by: Andreas Kling <kling@serenityos.org>
2021-09-15 20:46:51 +01:00
|
|
|
}
|
|
|
|
|
2024-07-17 09:55:20 -04:00
|
|
|
template<typename T>
|
|
|
|
Completion throw_completion(ErrorType type)
|
|
|
|
{
|
|
|
|
return throw_completion<T>(String::from_utf8_without_validation(type.message().bytes()));
|
|
|
|
}
|
|
|
|
|
2021-09-21 22:08:38 +03:00
|
|
|
template<typename T, typename... Args>
|
2022-08-16 20:33:17 +01:00
|
|
|
Completion throw_completion(ErrorType type, Args&&... args)
|
2021-09-21 22:08:38 +03:00
|
|
|
{
|
2024-07-17 09:55:20 -04:00
|
|
|
return throw_completion<T>(MUST(String::formatted(type.message(), forward<Args>(args)...)));
|
2021-09-21 22:08:38 +03:00
|
|
|
}
|
|
|
|
|
2021-06-22 13:30:48 +02:00
|
|
|
Value get_new_target();
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2023-07-11 23:07:12 -04:00
|
|
|
Object* get_import_meta();
|
|
|
|
|
2022-08-28 15:03:45 +01:00
|
|
|
Object& get_global_object();
|
2022-08-21 15:39:13 +01:00
|
|
|
|
2020-10-13 23:49:19 +02:00
|
|
|
CommonPropertyNames names;
|
2024-07-23 09:42:00 +02:00
|
|
|
struct {
|
|
|
|
GCPtr<PrimitiveString> number;
|
|
|
|
GCPtr<PrimitiveString> undefined;
|
|
|
|
GCPtr<PrimitiveString> object;
|
|
|
|
GCPtr<PrimitiveString> string;
|
|
|
|
GCPtr<PrimitiveString> symbol;
|
|
|
|
GCPtr<PrimitiveString> boolean;
|
|
|
|
GCPtr<PrimitiveString> bigint;
|
|
|
|
GCPtr<PrimitiveString> function;
|
|
|
|
} typeof_strings;
|
2020-10-13 23:49:19 +02:00
|
|
|
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
void run_queued_promise_jobs();
|
2024-03-25 14:18:22 +01:00
|
|
|
void enqueue_promise_job(NonnullGCPtr<HeapFunction<ThrowCompletionOr<Value>()>> job, Realm*);
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
|
2021-06-15 22:16:17 +03:00
|
|
|
void run_queued_finalization_registry_cleanup_jobs();
|
|
|
|
void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
|
|
|
|
|
2022-02-06 03:46:45 +00:00
|
|
|
void promise_rejection_tracker(Promise&, Promise::RejectionOperation) const;
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
|
2021-06-27 22:38:42 +02:00
|
|
|
Function<void()> on_call_stack_emptied;
|
2022-02-06 03:46:45 +00:00
|
|
|
Function<void(Promise&)> on_promise_unhandled_rejection;
|
|
|
|
Function<void(Promise&)> on_promise_rejection_handled;
|
2024-06-11 07:07:07 +01:00
|
|
|
Function<void(Object const&, PropertyKey const&)> on_unimplemented_property_access;
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
|
2021-09-08 22:58:36 +02:00
|
|
|
CustomData* custom_data() { return m_custom_data; }
|
|
|
|
|
2021-10-03 14:52:53 +02:00
|
|
|
void save_execution_context_stack();
|
2024-01-18 12:49:35 -07:00
|
|
|
void clear_execution_context_stack();
|
2021-10-03 14:52:53 +02:00
|
|
|
void restore_execution_context_stack();
|
|
|
|
|
2022-01-19 01:22:58 +01:00
|
|
|
// Do not call this method unless you are sure this is the only and first module to be loaded in this vm.
|
2023-06-15 12:36:57 +02:00
|
|
|
ThrowCompletionOr<void> link_and_eval_module(Badge<Bytecode::Interpreter>, SourceTextModule& module);
|
2022-01-19 01:22:58 +01:00
|
|
|
|
2022-01-17 14:48:22 +01:00
|
|
|
ScriptOrModule get_active_script_or_module() const;
|
|
|
|
|
2023-10-29 02:53:53 +01:00
|
|
|
// NOTE: The host defined implementation described in the web spec https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule
|
|
|
|
// currently references proposal-import-attributes.
|
|
|
|
// Our implementation of this proposal is outdated however, as such we try to adapt the proposal and living standard
|
|
|
|
// to match our implementation for now.
|
|
|
|
// 16.2.1.8 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload ), https://tc39.es/proposal-import-attributes/#sec-HostLoadImportedModule
|
2023-12-02 22:56:47 +01:00
|
|
|
Function<void(ImportedModuleReferrer, ModuleRequest const&, GCPtr<GraphLoadingState::HostDefined>, ImportedModulePayload)> host_load_imported_module;
|
2022-01-18 19:14:25 +01:00
|
|
|
|
2023-07-17 21:15:55 -04:00
|
|
|
Function<HashMap<PropertyKey, Value>(SourceTextModule&)> host_get_import_meta_properties;
|
2022-01-18 19:14:25 +01:00
|
|
|
Function<void(Object*, SourceTextModule const&)> host_finalize_import_meta;
|
|
|
|
|
2023-12-16 17:49:34 +03:30
|
|
|
Function<Vector<ByteString>()> host_get_supported_import_attributes;
|
2022-01-27 02:44:03 +01:00
|
|
|
|
2023-12-02 22:56:47 +01:00
|
|
|
void set_dynamic_imports_allowed(bool value) { m_dynamic_imports_allowed = value; }
|
2022-01-18 19:39:36 +01:00
|
|
|
|
2022-02-06 03:46:45 +00:00
|
|
|
Function<void(Promise&, Promise::RejectionOperation)> host_promise_rejection_tracker;
|
2023-11-27 12:56:20 +01:00
|
|
|
Function<ThrowCompletionOr<Value>(JobCallback&, Value, ReadonlySpan<Value>)> host_call_job_callback;
|
2022-02-06 03:46:45 +00:00
|
|
|
Function<void(FinalizationRegistry&)> host_enqueue_finalization_registry_cleanup_job;
|
2024-03-25 14:18:22 +01:00
|
|
|
Function<void(NonnullGCPtr<HeapFunction<ThrowCompletionOr<Value>()>>, Realm*)> host_enqueue_promise_job;
|
2024-03-12 03:49:13 +01:00
|
|
|
Function<JS::NonnullGCPtr<JobCallback>(FunctionObject&)> host_make_job_callback;
|
2022-04-22 19:10:27 +01:00
|
|
|
Function<ThrowCompletionOr<void>(Realm&)> host_ensure_can_compile_strings;
|
2022-08-14 00:51:32 +02:00
|
|
|
Function<ThrowCompletionOr<void>(Object&)> host_ensure_can_add_private_element;
|
2023-10-14 19:10:55 -04:00
|
|
|
Function<ThrowCompletionOr<HandledByHost>(ArrayBuffer&, size_t)> host_resize_array_buffer;
|
2024-09-08 11:15:07 -04:00
|
|
|
Function<void(StringView)> host_unrecognized_date_string;
|
2024-10-23 18:15:19 +13:00
|
|
|
Function<ThrowCompletionOr<NonnullGCPtr<ShadowRealm>>(Realm&, NonnullOwnPtr<ExecutionContext>, ShadowRealm&)> host_initialize_shadow_realm;
|
2022-02-06 03:46:45 +00:00
|
|
|
|
2023-11-01 00:39:28 +01:00
|
|
|
Vector<StackTraceElement> stack_trace() const;
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
private:
|
2023-03-17 10:21:51 -04:00
|
|
|
using ErrorMessages = AK::Array<String, to_underlying(ErrorMessage::__Count)>;
|
|
|
|
|
|
|
|
struct WellKnownSymbols {
|
|
|
|
#define __JS_ENUMERATE(SymbolName, snake_name) \
|
|
|
|
GCPtr<Symbol> snake_name;
|
|
|
|
JS_ENUMERATE_WELL_KNOWN_SYMBOLS
|
|
|
|
#undef __JS_ENUMERATE
|
|
|
|
};
|
|
|
|
|
|
|
|
VM(OwnPtr<CustomData>, ErrorMessages);
|
2020-09-20 19:24:44 +02:00
|
|
|
|
2023-12-02 22:56:47 +01:00
|
|
|
void load_imported_module(ImportedModuleReferrer, ModuleRequest const&, GCPtr<GraphLoadingState::HostDefined>, ImportedModulePayload);
|
2023-12-06 11:14:41 +01:00
|
|
|
ThrowCompletionOr<void> link_and_eval_module(CyclicModule&);
|
2022-01-19 01:22:58 +01:00
|
|
|
|
2023-03-17 10:21:51 -04:00
|
|
|
void set_well_known_symbols(WellKnownSymbols well_known_symbols) { m_well_known_symbols = move(well_known_symbols); }
|
|
|
|
|
2023-02-26 16:09:02 -07:00
|
|
|
HashMap<String, GCPtr<PrimitiveString>> m_string_cache;
|
2023-12-16 17:49:34 +03:30
|
|
|
HashMap<ByteString, GCPtr<PrimitiveString>> m_byte_string_cache;
|
2024-10-24 23:02:10 +02:00
|
|
|
HashMap<Utf16String, GCPtr<PrimitiveString>> m_utf16_string_cache;
|
2021-10-02 01:36:57 +02:00
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
Heap m_heap;
|
2020-09-22 16:18:51 +02:00
|
|
|
|
2021-06-24 19:17:45 +02:00
|
|
|
Vector<ExecutionContext*> m_execution_context_stack;
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2021-10-03 14:52:53 +02:00
|
|
|
Vector<Vector<ExecutionContext*>> m_saved_execution_context_stacks;
|
|
|
|
|
2020-11-08 12:48:16 +00:00
|
|
|
StackInfo m_stack_info;
|
|
|
|
|
2022-12-06 20:58:15 +00:00
|
|
|
// GlobalSymbolRegistry, https://tc39.es/ecma262/#table-globalsymbolregistry-record-fields
|
2023-02-11 16:14:41 +00:00
|
|
|
HashMap<String, NonnullGCPtr<Symbol>> m_global_symbol_registry;
|
2020-09-22 16:18:51 +02:00
|
|
|
|
2024-03-25 14:18:22 +01:00
|
|
|
Vector<NonnullGCPtr<HeapFunction<ThrowCompletionOr<Value>()>>> m_promise_jobs;
|
LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)
The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.
Implemented functions are:
- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()
For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].
Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.
This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.
I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.
[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-01 22:13:29 +02:00
|
|
|
|
2023-02-26 16:09:02 -07:00
|
|
|
Vector<GCPtr<FinalizationRegistry>> m_finalization_registry_cleanup_jobs;
|
2021-06-15 22:16:17 +03:00
|
|
|
|
2023-02-26 16:09:02 -07:00
|
|
|
GCPtr<PrimitiveString> m_empty_string;
|
|
|
|
GCPtr<PrimitiveString> m_single_ascii_character_strings[128] {};
|
2023-03-17 10:21:51 -04:00
|
|
|
ErrorMessages m_error_messages;
|
2022-01-19 01:22:58 +01:00
|
|
|
|
|
|
|
struct StoredModule {
|
2023-12-02 16:20:01 +01:00
|
|
|
ImportedModuleReferrer referrer;
|
2023-12-16 17:49:34 +03:30
|
|
|
ByteString filename;
|
|
|
|
ByteString type;
|
2022-09-05 14:31:25 +02:00
|
|
|
Handle<Module> module;
|
2022-01-19 01:22:58 +01:00
|
|
|
bool has_once_started_linking { false };
|
|
|
|
};
|
|
|
|
|
2023-12-16 17:49:34 +03:30
|
|
|
StoredModule* get_stored_module(ImportedModuleReferrer const& script_or_module, ByteString const& filename, ByteString const& type);
|
2022-01-19 01:22:58 +01:00
|
|
|
|
|
|
|
Vector<StoredModule> m_loaded_modules;
|
2020-09-22 16:36:33 +02:00
|
|
|
|
2023-03-17 10:21:51 -04:00
|
|
|
WellKnownSymbols m_well_known_symbols;
|
2020-11-28 16:02:27 +01:00
|
|
|
|
2021-06-12 17:32:54 +03:00
|
|
|
u32 m_execution_generation { 0 };
|
2021-09-08 22:58:36 +02:00
|
|
|
|
|
|
|
OwnPtr<CustomData> m_custom_data;
|
2023-06-22 15:59:18 +02:00
|
|
|
|
|
|
|
OwnPtr<Bytecode::Interpreter> m_bytecode_interpreter;
|
2023-12-02 22:56:47 +01:00
|
|
|
|
|
|
|
bool m_dynamic_imports_allowed { false };
|
2020-09-20 19:24:44 +02:00
|
|
|
};
|
|
|
|
|
2023-08-08 07:05:26 +02:00
|
|
|
template<typename GlobalObjectType, typename... Args>
|
|
|
|
[[nodiscard]] static NonnullOwnPtr<ExecutionContext> create_simple_execution_context(VM& vm, Args&&... args)
|
|
|
|
{
|
|
|
|
auto root_execution_context = MUST(Realm::initialize_host_defined_realm(
|
|
|
|
vm,
|
|
|
|
[&](Realm& realm_) -> GlobalObject* {
|
|
|
|
return vm.heap().allocate_without_realm<GlobalObjectType>(realm_, forward<Args>(args)...);
|
|
|
|
},
|
|
|
|
nullptr));
|
|
|
|
return root_execution_context;
|
|
|
|
}
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
}
|