diff options
author | Linus Groh <mail@linusgroh.de> | 2021-04-01 22:13:29 +0200 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-04-02 10:47:40 +0200 |
commit | f418115f1bba2975d8cf8b086092b0df5ae507c9 (patch) | |
tree | bf16e3d655ac9c360ad8155655878bde16da7f66 /Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp | |
parent | 563712abcef5ca791bdbc09c4a02931fd709c7c9 (diff) | |
download | serenity-f418115f1bba2975d8cf8b086092b0df5ae507c9.zip |
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
Diffstat (limited to 'Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp')
-rw-r--r-- | Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp | 116 |
1 files changed, 116 insertions, 0 deletions
diff --git a/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp b/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp new file mode 100644 index 0000000000..53e61432e7 --- /dev/null +++ b/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2021, Linus Groh <mail@linusgroh.de> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <LibJS/Runtime/Error.h> +#include <LibJS/Runtime/MarkedValueList.h> +#include <LibJS/Runtime/NativeFunction.h> +#include <LibJS/Runtime/PromiseReaction.h> + +namespace JS { + +// 27.2.1.5 NewPromiseCapability, https://tc39.es/ecma262/#sec-newpromisecapability +PromiseCapability new_promise_capability(GlobalObject& global_object, Value constructor) +{ + auto& vm = global_object.vm(); + if (!constructor.is_constructor()) { + vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects()); + return {}; + } + + struct { + Value resolve { js_undefined() }; + Value reject { js_undefined() }; + } promise_capability_functions; + + auto* executor = NativeFunction::create(global_object, "", [&promise_capability_functions](auto& vm, auto& global_object) -> Value { + auto resolve = vm.argument(0); + auto reject = vm.argument(1); + // No idea what other engines say here. + if (!promise_capability_functions.resolve.is_undefined()) { + vm.template throw_exception<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes); + return {}; + } + if (!promise_capability_functions.resolve.is_undefined()) { + vm.template throw_exception<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes); + return {}; + } + promise_capability_functions.resolve = resolve; + promise_capability_functions.reject = reject; + return js_undefined(); + }); + executor->define_property(vm.names.length, Value(2)); + + MarkedValueList arguments(vm.heap()); + arguments.append(executor); + auto promise = vm.construct(constructor.as_function(), constructor.as_function(), move(arguments), global_object); + if (vm.exception()) + return {}; + + // I'm not sure if we could VERIFY(promise.is_object()) instead - the spec doesn't have this check... + if (!promise.is_object()) { + vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, promise.to_string_without_side_effects()); + return {}; + } + + if (!promise_capability_functions.resolve.is_function()) { + vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.resolve.to_string_without_side_effects()); + return {}; + } + if (!promise_capability_functions.reject.is_function()) { + vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.reject.to_string_without_side_effects()); + return {}; + } + + return { + &promise.as_object(), + &promise_capability_functions.resolve.as_function(), + &promise_capability_functions.reject.as_function(), + }; +} + +PromiseReaction::PromiseReaction(Type type, Optional<PromiseCapability> capability, Optional<JobCallback> handler) + : m_type(type) + , m_capability(move(capability)) + , m_handler(move(handler)) +{ +} + +void PromiseReaction::visit_edges(Cell::Visitor& visitor) +{ + Cell::visit_edges(visitor); + if (m_capability.has_value()) { + auto& capability = m_capability.value(); + visitor.visit(capability.promise); + visitor.visit(capability.resolve); + visitor.visit(capability.reject); + } + if (m_handler.has_value()) { + auto& handler = m_handler.value(); + visitor.visit(handler.callback); + } +} + +} |