2020-09-20 19:24:44 +02:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
|
2021-04-22 22:51:19 +02:00
|
|
|
* Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
|
2021-10-03 14:16:10 +02:00
|
|
|
* Copyright (c) 2021, David Tuin <davidot@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
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
#include <AK/FlyString.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>
|
2020-09-20 19:24:44 +02:00
|
|
|
#include <LibJS/Heap/Heap.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>
|
|
|
|
#include <LibJS/Runtime/Exception.h>
|
2021-09-14 18:21:07 +02:00
|
|
|
#include <LibJS/Runtime/ExecutionContext.h>
|
2020-09-27 18:36:49 +02:00
|
|
|
#include <LibJS/Runtime/MarkedValueList.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;
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
enum class ScopeType {
|
|
|
|
None,
|
|
|
|
Function,
|
|
|
|
Block,
|
|
|
|
Try,
|
|
|
|
Breakable,
|
|
|
|
Continuable,
|
|
|
|
};
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
class VM : public RefCounted<VM> {
|
|
|
|
public:
|
2021-09-08 22:58:36 +02:00
|
|
|
struct CustomData {
|
|
|
|
virtual ~CustomData();
|
|
|
|
};
|
|
|
|
|
|
|
|
static NonnullRefPtr<VM> create(OwnPtr<CustomData> = {});
|
2020-09-20 19:24:44 +02:00
|
|
|
~VM();
|
|
|
|
|
|
|
|
Heap& heap() { return m_heap; }
|
|
|
|
const Heap& heap() const { return m_heap; }
|
|
|
|
|
|
|
|
Interpreter& interpreter();
|
|
|
|
Interpreter* interpreter_if_exists();
|
|
|
|
|
|
|
|
void push_interpreter(Interpreter&);
|
|
|
|
void pop_interpreter(Interpreter&);
|
|
|
|
|
2021-04-13 01:02:38 +02:00
|
|
|
Exception* exception() { return m_exception; }
|
|
|
|
void set_exception(Exception& exception) { m_exception = &exception; }
|
2020-09-21 15:28:09 +02:00
|
|
|
void clear_exception() { m_exception = nullptr; }
|
|
|
|
|
2021-06-06 22:53:44 +02:00
|
|
|
void dump_backtrace() const;
|
|
|
|
|
2020-09-21 13:36:32 +02:00
|
|
|
class InterpreterExecutionScope {
|
2020-09-20 19:24:44 +02:00
|
|
|
public:
|
2020-09-21 13:36:32 +02:00
|
|
|
InterpreterExecutionScope(Interpreter&);
|
|
|
|
~InterpreterExecutionScope();
|
2020-09-21 15:28:09 +02:00
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
private:
|
|
|
|
Interpreter& m_interpreter;
|
|
|
|
};
|
|
|
|
|
2020-09-21 13:47:33 +02:00
|
|
|
void gather_roots(HashTable<Cell*>&);
|
|
|
|
|
2020-09-22 16:18:51 +02:00
|
|
|
#define __JS_ENUMERATE(SymbolName, snake_name) \
|
|
|
|
Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
|
|
|
|
JS_ENUMERATE_WELL_KNOWN_SYMBOLS
|
|
|
|
#undef __JS_ENUMERATE
|
|
|
|
|
|
|
|
Symbol* get_global_symbol(const String& description);
|
|
|
|
|
2021-10-02 01:36:57 +02:00
|
|
|
HashMap<String, PrimitiveString*>& string_cache() { return m_string_cache; }
|
2020-09-22 16:36:33 +02:00
|
|
|
PrimitiveString& empty_string() { return *m_empty_string; }
|
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
|
|
|
|
2021-08-13 12:59:57 -04:00
|
|
|
bool did_reach_stack_space_limit() const
|
|
|
|
{
|
2021-09-05 20:34:06 +01:00
|
|
|
#ifdef HAS_ADDRESS_SANITIZER
|
2021-08-13 12:59:57 -04:00
|
|
|
return m_stack_info.size_free() < 32 * KiB;
|
2021-09-05 20:34:06 +01:00
|
|
|
#else
|
|
|
|
return m_stack_info.size_free() < 16 * KiB;
|
|
|
|
#endif
|
2021-08-13 12:59:57 -04:00
|
|
|
}
|
|
|
|
|
2021-06-24 19:17:45 +02:00
|
|
|
void push_execution_context(ExecutionContext& context, GlobalObject& global_object)
|
2020-09-27 15:18:55 +02:00
|
|
|
{
|
2021-02-23 20:42:32 +01:00
|
|
|
VERIFY(!exception());
|
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())
|
2021-09-05 20:13:06 +01:00
|
|
|
throw_exception<Error>(global_object, ErrorType::CallStackSizeExceeded);
|
2020-11-08 12:54:52 +00:00
|
|
|
else
|
2021-06-24 19:17:45 +02:00
|
|
|
m_execution_context_stack.append(&context);
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
2020-11-07 11:07:17 +01:00
|
|
|
|
2021-06-24 19:17:45 +02:00
|
|
|
void pop_execution_context()
|
2021-04-24 18:21:02 +02:00
|
|
|
{
|
2021-06-24 19:17:45 +02:00
|
|
|
m_execution_context_stack.take_last();
|
|
|
|
if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
|
2021-04-24 18:21:02 +02:00
|
|
|
on_call_stack_emptied();
|
|
|
|
}
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2021-06-24 19:17:45 +02:00
|
|
|
ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
|
|
|
|
ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
|
|
|
|
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; }
|
|
|
|
|
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 {};
|
2021-06-24 19:17:45 +02:00
|
|
|
auto& arguments = running_execution_context().arguments;
|
2020-09-27 15:18:55 +02:00
|
|
|
return index < arguments.size() ? arguments[index] : js_undefined();
|
|
|
|
}
|
|
|
|
|
|
|
|
Value this_value(Object& global_object) 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 &global_object;
|
2021-06-24 19:17:45 +02:00
|
|
|
return running_execution_context().this_value;
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
|
2021-06-25 11:40:03 +02:00
|
|
|
Value resolve_this_binding(GlobalObject&);
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
Value last_value() const { return m_last_value; }
|
2021-06-10 21:01:44 +02:00
|
|
|
void set_last_value(Badge<Bytecode::Interpreter>, Value value) { m_last_value = value; }
|
2020-09-27 16:56:58 +02:00
|
|
|
void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2020-11-08 12:48:16 +00:00
|
|
|
const StackInfo& stack_info() const { return m_stack_info; };
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
bool underscore_is_last_value() const { return m_underscore_is_last_value; }
|
|
|
|
void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
|
|
|
|
|
2021-06-12 17:32:54 +03:00
|
|
|
u32 execution_generation() const { return m_execution_generation; }
|
|
|
|
void finish_execution_generation() { ++m_execution_generation; }
|
|
|
|
|
2020-09-27 15:18:55 +02:00
|
|
|
void unwind(ScopeType type, FlyString label = {})
|
|
|
|
{
|
|
|
|
m_unwind_until = type;
|
2021-06-06 11:40:41 +02:00
|
|
|
m_unwind_until_label = move(label);
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
2021-04-13 01:04:32 +02:00
|
|
|
void stop_unwind()
|
|
|
|
{
|
|
|
|
m_unwind_until = ScopeType::None;
|
|
|
|
m_unwind_until_label = {};
|
|
|
|
}
|
2021-09-18 23:01:54 +02:00
|
|
|
bool should_unwind_until(ScopeType type, Vector<FlyString> const& labels) const
|
2020-09-27 15:18:55 +02:00
|
|
|
{
|
|
|
|
if (m_unwind_until_label.is_null())
|
|
|
|
return m_unwind_until == type;
|
2021-09-18 23:01:54 +02:00
|
|
|
return m_unwind_until == type && any_of(labels.begin(), labels.end(), [&](FlyString const& label) {
|
|
|
|
return m_unwind_until_label == label;
|
|
|
|
});
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
bool should_unwind() const { return m_unwind_until != ScopeType::None; }
|
|
|
|
|
2020-09-27 16:56:58 +02:00
|
|
|
ScopeType unwind_until() const { return m_unwind_until; }
|
2021-06-14 13:46:02 +03:00
|
|
|
FlyString unwind_until_label() const { return m_unwind_until_label; }
|
2020-09-27 16:56:58 +02:00
|
|
|
|
2021-07-02 21:54:56 +02:00
|
|
|
Reference resolve_binding(FlyString const&, Environment* = nullptr);
|
2021-10-07 01:06:21 +02:00
|
|
|
Reference get_identifier_reference(Environment*, FlyString, bool strict, size_t hops = 0);
|
2020-09-27 15:18:55 +02:00
|
|
|
|
|
|
|
template<typename T, typename... Args>
|
|
|
|
void throw_exception(GlobalObject& global_object, Args&&... args)
|
|
|
|
{
|
|
|
|
return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
|
|
|
|
}
|
|
|
|
|
2021-04-13 01:02:38 +02:00
|
|
|
void throw_exception(Exception&);
|
2020-09-27 15:18:55 +02:00
|
|
|
void throw_exception(GlobalObject& global_object, Value value)
|
|
|
|
{
|
2021-04-13 01:02:38 +02:00
|
|
|
return throw_exception(*heap().allocate<Exception>(global_object, value));
|
2020-09-27 15:18:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T, typename... Args>
|
|
|
|
void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
|
|
|
|
{
|
2020-10-04 13:55:20 +01:00
|
|
|
return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
|
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>
|
2021-09-21 22:08:38 +03:00
|
|
|
Completion throw_completion(GlobalObject& global_object, 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
|
|
|
{
|
2021-09-21 22:08:38 +03:00
|
|
|
auto* error = T::create(global_object, forward<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
|
|
|
// NOTE: This is temporary until we remove VM::exception().
|
|
|
|
throw_exception(global_object, error);
|
|
|
|
return JS::throw_completion(error);
|
|
|
|
}
|
|
|
|
|
2021-09-21 22:08:38 +03:00
|
|
|
template<typename T, typename... Args>
|
|
|
|
Completion throw_completion(GlobalObject& global_object, ErrorType type, Args&&... args)
|
|
|
|
{
|
|
|
|
return throw_completion<T>(global_object, String::formatted(type.message(), forward<Args>(args)...));
|
|
|
|
}
|
|
|
|
|
2021-06-27 21:48:34 +02:00
|
|
|
Value construct(FunctionObject&, FunctionObject& new_target, Optional<MarkedValueList> arguments);
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2021-04-18 17:08:14 +02:00
|
|
|
String join_arguments(size_t start_index = 0) const;
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2021-06-22 13:30:48 +02:00
|
|
|
Value get_new_target();
|
2020-09-27 15:18:55 +02:00
|
|
|
|
2020-09-27 18:36:49 +02:00
|
|
|
template<typename... Args>
|
2021-09-23 20:56:28 +03:00
|
|
|
[[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> call(FunctionObject& function, Value this_value, Args... args)
|
2020-09-27 18:36:49 +02:00
|
|
|
{
|
2020-12-20 16:09:48 -07:00
|
|
|
if constexpr (sizeof...(Args) > 0) {
|
LibJS: Implement [[Call]] and [[Construct]] internal slots properly
This patch implements:
- Spec compliant [[Call]] and [[Construct]] internal slots, as virtual
FunctionObject::internal_{call,construct}(). These effectively replace
the old virtual FunctionObject::{call,construct}(), but with several
advantages:
- Clear and consistent naming, following the object internal methods
- Use of completions
- internal_construct() returns an Object, and not Value! This has been
a source of confusion for a long time, since in the spec there's
always an Object returned but the Value return type in LibJS meant
that this could not be fully trusted and something could screw you
over.
- Arguments are passed explicitly in form of a MarkedValueList,
allowing manipulation (BoundFunction). We still put them on the
execution context as a lot of code depends on it (VM::arguments()),
but not from the Call() / Construct() AOs anymore, which now allows
for bypassing them and invoking [[Call]] / [[Construct]] directly.
Nothing but Call() / Construct() themselves do that at the moment,
but future additions to ECMA262 or already existing web specs might.
- Spec compliant, standalone Call() and Construct() AOs: currently the
closest we have is VM::{call,construct}(), but those try to cater to
all the different function object subclasses at once, resulting in a
horrible mess and calling AOs with functions they should never be
called with; most prominently PrepareForOrdinaryCall and
OrdinaryCallBindThis, which are only for ECMAScriptFunctionObject.
As a result this also contains an implicit optimization: we no longer
need to create a new function environment for NativeFunctions - which,
worth mentioning, is what started this whole crusade in the first place
:^)
2021-10-08 20:37:21 +01:00
|
|
|
MarkedValueList arguments_list { heap() };
|
|
|
|
(..., arguments_list.append(move(args)));
|
|
|
|
return call(function, this_value, move(arguments_list));
|
2020-09-27 18:36:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return call(function, this_value);
|
|
|
|
}
|
2020-09-27 17:24:14 +02:00
|
|
|
|
2020-10-13 23:49:19 +02:00
|
|
|
CommonPropertyNames names;
|
|
|
|
|
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();
|
|
|
|
void enqueue_promise_job(NativeFunction&);
|
|
|
|
|
2021-06-15 22:16:17 +03:00
|
|
|
void run_queued_finalization_registry_cleanup_jobs();
|
|
|
|
void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
|
|
|
|
|
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 promise_rejection_tracker(const Promise&, Promise::RejectionOperation) const;
|
|
|
|
|
2021-06-27 22:38:42 +02:00
|
|
|
Function<void()> on_call_stack_emptied;
|
|
|
|
Function<void(const Promise&)> on_promise_unhandled_rejection;
|
|
|
|
Function<void(const Promise&)> on_promise_rejection_handled;
|
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
|
|
|
|
LibJS: Implement [[Call]] and [[Construct]] internal slots properly
This patch implements:
- Spec compliant [[Call]] and [[Construct]] internal slots, as virtual
FunctionObject::internal_{call,construct}(). These effectively replace
the old virtual FunctionObject::{call,construct}(), but with several
advantages:
- Clear and consistent naming, following the object internal methods
- Use of completions
- internal_construct() returns an Object, and not Value! This has been
a source of confusion for a long time, since in the spec there's
always an Object returned but the Value return type in LibJS meant
that this could not be fully trusted and something could screw you
over.
- Arguments are passed explicitly in form of a MarkedValueList,
allowing manipulation (BoundFunction). We still put them on the
execution context as a lot of code depends on it (VM::arguments()),
but not from the Call() / Construct() AOs anymore, which now allows
for bypassing them and invoking [[Call]] / [[Construct]] directly.
Nothing but Call() / Construct() themselves do that at the moment,
but future additions to ECMA262 or already existing web specs might.
- Spec compliant, standalone Call() and Construct() AOs: currently the
closest we have is VM::{call,construct}(), but those try to cater to
all the different function object subclasses at once, resulting in a
horrible mess and calling AOs with functions they should never be
called with; most prominently PrepareForOrdinaryCall and
OrdinaryCallBindThis, which are only for ECMAScriptFunctionObject.
As a result this also contains an implicit optimization: we no longer
need to create a new function environment for NativeFunctions - which,
worth mentioning, is what started this whole crusade in the first place
:^)
2021-10-08 20:37:21 +01:00
|
|
|
ThrowCompletionOr<void> initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor);
|
2021-08-28 17:11:05 +02:00
|
|
|
|
2021-09-08 22:58:36 +02:00
|
|
|
CustomData* custom_data() { return m_custom_data; }
|
|
|
|
|
2021-09-22 12:44:56 +02:00
|
|
|
ThrowCompletionOr<void> destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object);
|
|
|
|
ThrowCompletionOr<void> binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object);
|
|
|
|
ThrowCompletionOr<void> binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object);
|
|
|
|
|
|
|
|
ThrowCompletionOr<Value> named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name);
|
|
|
|
|
2021-10-03 14:52:53 +02:00
|
|
|
void save_execution_context_stack();
|
|
|
|
void restore_execution_context_stack();
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
private:
|
2021-09-08 22:58:36 +02:00
|
|
|
explicit VM(OwnPtr<CustomData>);
|
2020-09-20 19:24:44 +02:00
|
|
|
|
2021-09-23 20:56:28 +03:00
|
|
|
[[nodiscard]] ThrowCompletionOr<Value> call_internal(FunctionObject&, Value this_value, Optional<MarkedValueList> arguments);
|
2020-09-27 18:36:49 +02:00
|
|
|
|
2021-10-24 16:01:24 +02:00
|
|
|
ThrowCompletionOr<Object*> copy_data_properties(Object& rest_object, Object const& source, HashTable<PropertyKey, PropertyNameTraits> const& seen_names, GlobalObject& global_object);
|
2021-09-22 12:44:56 +02:00
|
|
|
|
|
|
|
ThrowCompletionOr<void> property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object);
|
|
|
|
ThrowCompletionOr<void> iterator_binding_initialization(BindingPattern const& binding, Object* iterator, bool& iterator_done, Environment* environment, GlobalObject& global_object);
|
|
|
|
|
2020-09-21 15:28:09 +02:00
|
|
|
Exception* m_exception { nullptr };
|
|
|
|
|
2021-10-02 01:36:57 +02:00
|
|
|
HashMap<String, PrimitiveString*> m_string_cache;
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
Heap m_heap;
|
|
|
|
Vector<Interpreter*> m_interpreters;
|
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-09-27 15:18:55 +02:00
|
|
|
Value m_last_value;
|
|
|
|
ScopeType m_unwind_until { ScopeType::None };
|
|
|
|
FlyString m_unwind_until_label;
|
|
|
|
|
2020-11-08 12:48:16 +00:00
|
|
|
StackInfo m_stack_info;
|
|
|
|
|
2020-09-22 16:18:51 +02:00
|
|
|
HashMap<String, Symbol*> m_global_symbol_map;
|
|
|
|
|
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
|
|
|
Vector<NativeFunction*> m_promise_jobs;
|
|
|
|
|
2021-06-15 22:16:17 +03:00
|
|
|
Vector<FinalizationRegistry*> m_finalization_registry_cleanup_jobs;
|
|
|
|
|
2020-09-22 16:36:33 +02:00
|
|
|
PrimitiveString* m_empty_string { nullptr };
|
2020-10-22 17:43:48 +02:00
|
|
|
PrimitiveString* m_single_ascii_character_strings[128] {};
|
2020-09-22 16:36:33 +02:00
|
|
|
|
2020-09-22 16:18:51 +02:00
|
|
|
#define __JS_ENUMERATE(SymbolName, snake_name) \
|
|
|
|
Symbol* m_well_known_symbol_##snake_name { nullptr };
|
|
|
|
JS_ENUMERATE_WELL_KNOWN_SYMBOLS
|
|
|
|
#undef __JS_ENUMERATE
|
2020-11-28 16:02:27 +01: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
|
|
|
bool m_underscore_is_last_value { false };
|
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;
|
2020-09-20 19:24:44 +02:00
|
|
|
};
|
|
|
|
|
2020-09-27 18:36:49 +02:00
|
|
|
template<>
|
2021-09-23 20:56:28 +03:00
|
|
|
[[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
|
2020-09-27 18:36:49 +02:00
|
|
|
|
|
|
|
template<>
|
2021-09-23 20:56:28 +03:00
|
|
|
[[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
|
2020-09-27 18:36:49 +02:00
|
|
|
|
|
|
|
template<>
|
2021-09-23 20:56:28 +03:00
|
|
|
[[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
|
2020-09-27 18:36:49 +02:00
|
|
|
|
2021-03-21 17:20:07 +01:00
|
|
|
ALWAYS_INLINE Heap& Cell::heap() const
|
|
|
|
{
|
|
|
|
return HeapBlock::from_cell(this)->heap();
|
|
|
|
}
|
|
|
|
|
|
|
|
ALWAYS_INLINE VM& Cell::vm() const
|
|
|
|
{
|
|
|
|
return heap().vm();
|
|
|
|
}
|
|
|
|
|
2020-09-20 19:24:44 +02:00
|
|
|
}
|