Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / web_idl / promise.lucb

#==============================================================================================
#
#   promise - WebIDL promises: creating, resolving, rejecting and reacting to JS promises
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/WebIDL/Promise.cpp (lines 1-342) and Promise.h (lines 1-41).
#       A WebIDL::Promise is a JS::PromiseCapability over a JS Promise object. Before luce-js
#       these are the phase-1 stand-ins of DESIGN.md §3.6 (external/lib_js/promise,
#       promise_jobs): the steps below are the donor's, and the reactions run as microtasks
#       through the main thread VM's HostEnqueuePromiseJob. %Promise% is named by its realm
#       (there is no constructor object before phase 3). ReactionSteps cannot throw here (a
#       GC::Function's result cannot be fallible, DESIGN.md §2.7); phase 3 widens them.
#       WaitForAllResults, the cell "wait for all" keeps its results in, is here.
#
#       Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Promises ================================================================================

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:22 Web::WebIDL::create_promise.
## https://webidl.spec.whatwg.org/#a-new-promise
pub func idl_create_promise(realm: Realm*) -> JsPromiseCapability*:
    let vm = realm_vm(realm)

    # 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
    # (The constructor is named by its realm, see the header.)

    # Return ? NewPromiseCapability(constructor).
    # NOTE: When called with %Promise%, NewPromiseCapability can't throw.
    return js_new_promise_capability(vm, realm) else trap("MUST: NewPromiseCapability(%Promise%)")

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:35 Web::WebIDL::create_resolved_promise.
## https://webidl.spec.whatwg.org/#a-promise-resolved-with
pub func idl_create_resolved_promise(realm: Realm*, value: JsValue) -> JsPromiseCapability*:
    let vm = realm_vm(realm)

    # 1. Let value be the result of converting x to an ECMAScript value.

    # 2. Let constructor be realm.[[Intrinsics]].[[%Promise%]].

    # 3. Let promiseCapability be ? NewPromiseCapability(constructor).
    # NOTE: When called with %Promise%, NewPromiseCapability can't throw.
    let promise_capability = js_new_promise_capability(vm, realm) else trap("MUST: NewPromiseCapability(%Promise%)")

    # 4. Perform ! Call(promiseCapability.[[Resolve]], undefined, « value »).
    let arguments: JsValue[1] = [value]
    _ = js_call(vm, js_promise_capability_resolve(promise_capability), js_undefined(), arguments) else trap("MUST: Call(promiseCapability.[[Resolve]])")

    # 5. Return promiseCapability.
    return promise_capability

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:56 Web::WebIDL::create_rejected_promise.
## https://webidl.spec.whatwg.org/#a-promise-rejected-with
pub func idl_create_rejected_promise(realm: Realm*, reason: JsValue) -> JsPromiseCapability*:
    let vm = realm_vm(realm)

    # 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].

    # 2. Let promiseCapability be ? NewPromiseCapability(constructor).
    # NOTE: When called with %Promise%, NewPromiseCapability can't throw.
    let promise_capability = js_new_promise_capability(vm, realm) else trap("MUST: NewPromiseCapability(%Promise%)")

    # 3. Perform ! Call(promiseCapability.[[Reject]], undefined, « r »).
    let arguments: JsValue[1] = [reason]
    _ = js_call(vm, js_promise_capability_reject(promise_capability), js_undefined(), arguments) else trap("MUST: Call(promiseCapability.[[Reject]])")

    # 4. Return promiseCapability.
    return promise_capability

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:75 Web::WebIDL::resolve_promise.
## https://webidl.spec.whatwg.org/#resolve
pub func idl_resolve_promise(realm: Realm*, promise: JsPromiseCapability*, value: JsValue):
    let vm = realm_vm(realm)

    # 1. If x is not given, then let it be the undefined value.
    # NOTE: This is done via the default argument.

    # 2. Let value be the result of converting x to an ECMAScript value.
    # 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
    let arguments: JsValue[1] = [value]
    _ = js_call(vm, js_promise_capability_resolve(promise), js_undefined(), arguments) else trap("MUST: Call(p.[[Resolve]])")

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:88 Web::WebIDL::reject_promise.
## https://webidl.spec.whatwg.org/#reject
pub func idl_reject_promise(realm: Realm*, promise: JsPromiseCapability*, reason: JsValue):
    let vm = realm_vm(realm)

    # 1. Perform ! Call(p.[[Reject]], undefined, « r »).
    let arguments: JsValue[1] = [reason]
    _ = js_call(vm, js_promise_capability_reject(promise), js_undefined(), arguments) else trap("MUST: Call(p.[[Reject]])")

## The captures of react_to_promise's onFulfilledSteps and onRejectedSteps.
struct IdlReactToPromiseSteps:
    var realm: Realm*
    var callback: gc.Function1[JsValue, JsValue]*?

## react_to_promise's onFulfilledSteps, given argument V.
func idl_react_to_promise_on_fulfilled_steps(context: void*?, vm: Vm*) -> JsValue!:
    let captures = (IdlReactToPromiseSteps*)(context else trap("no captures"))
    # 1. Let value be the result of converting V to an IDL value of type T.
    let value = vm_argument(vm, 0)

    # 2. If there is a set of steps to be run if the promise was fulfilled, then let result be the result of performing them, given value if T is not undefined. Otherwise, let result be value.
    var result = value
    if let on_fulfilled_callback = captures.callback:
        result = ak.function1_call(&on_fulfilled_callback.function, value)

    # 3. Return result, converted to an ECMAScript value.
    return result

## react_to_promise's onRejectedSteps, given argument R.
func idl_react_to_promise_on_rejected_steps(context: void*?, vm: Vm*) -> JsValue!:
    let captures = (IdlReactToPromiseSteps*)(context else trap("no captures"))
    # 1. Let reason be the result of converting R to an IDL value of type any.
    let reason = vm_argument(vm, 0)

    # 2. If there is a set of steps to be run if the promise was rejected, then let result be the result of performing them, given reason. Otherwise, let result be a promise rejected with reason.
    if let on_rejected_callback = captures.callback:
        return ak.function1_call(&on_rejected_callback.function, reason)
    let result = js_value_from_object(js_promise_capability_promise(idl_create_rejected_promise(captures.realm, reason)))

    # 3. Return result, converted to an ECMAScript value.
    return result

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:97 Web::WebIDL::react_to_promise.
## https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled
pub func idl_react_to_promise(promise: JsPromiseCapability*, on_fulfilled_callback: gc.Function1[JsValue, JsValue]*?, on_rejected_callback: gc.Function1[JsValue, JsValue]*?) -> JsPromiseCapability*:
    let realm = js_object_shape_realm(js_promise_capability_promise(promise))
    let vm = realm_vm(realm)

    # 1. Let onFulfilledSteps be the following steps given argument V:
    let on_fulfilled_steps = new IdlReactToPromiseSteps(realm = realm, callback = on_fulfilled_callback) else trap("out of memory")

    # 2. Let onFulfilled be CreateBuiltinFunction(onFulfilledSteps, 1, "", « »):
    let on_fulfilled = js_native_function_create(realm, JsNativeFunctionBehaviour(call = idl_react_to_promise_on_fulfilled_steps, context = on_fulfilled_steps), 1, ak.utf16_fly_string_new())

    # 3. Let onRejectedSteps be the following steps given argument R:
    let on_rejected_steps = new IdlReactToPromiseSteps(realm = realm, callback = on_rejected_callback) else trap("out of memory")

    # 4. Let onRejected be CreateBuiltinFunction(onRejectedSteps, 1, "", « »):
    let on_rejected = js_native_function_create(realm, JsNativeFunctionBehaviour(call = idl_react_to_promise_on_rejected_steps, context = on_rejected_steps), 1, ak.utf16_fly_string_new())

    # 5. Let constructor be promise.[[Promise]].[[Realm]].[[Intrinsics]].[[%Promise%]].

    # 6. Let newCapability be ? NewPromiseCapability(constructor).
    # NOTE: When called with %Promise%, NewPromiseCapability can't throw.
    let new_capability = js_new_promise_capability(vm, realm) else trap("MUST: NewPromiseCapability(%Promise%)")

    # 7. Perform PerformPromiseThen(promise.[[Promise]], onFulfilled, onRejected, newCapability).
    let promise_object = as_js_promise((gc.Cell*)js_promise_capability_promise(promise))
    let value = js_promise_perform_then(promise_object, js_value_from_object((JsObject*)on_fulfilled), js_value_from_object((JsObject*)on_rejected), new_capability)
    assert(js_value_as_object(value) == js_promise_capability_promise(new_capability))

    # 8. Return newCapability.
    return new_capability

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:153 Web::WebIDL::upon_fulfillment.
## https://webidl.spec.whatwg.org/#upon-fulfillment
pub func idl_upon_fulfillment(promise: JsPromiseCapability*, steps: gc.Function1[JsValue, JsValue]*) -> JsPromiseCapability*:
    # 1. Return the result of reacting to promise:
    #    - If promise was fulfilled with value v, then:
    #      1. Perform steps with v.
    return idl_react_to_promise(promise, steps, none)

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:164 Web::WebIDL::upon_rejection.
## https://webidl.spec.whatwg.org/#upon-rejection
pub func idl_upon_rejection(promise: JsPromiseCapability*, steps: gc.Function1[JsValue, JsValue]*) -> JsPromiseCapability*:
    # 1. Return the result of reacting to promise:
    #    - If promise was rejected with reason r, then:
    #      1. Perform steps with r.
    return idl_react_to_promise(promise, none, steps)

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:174 Web::WebIDL::mark_promise_as_handled.
## https://webidl.spec.whatwg.org/#mark-a-promise-as-handled
pub func idl_mark_promise_as_handled(promise: JsPromiseCapability*):
    # To mark as handled a Promise<T> promise, set promise.[[Promise]].[[PromiseIsHandled]] to true.
    let promise_object = as_js_promise((gc.Cell*)js_promise_capability_promise(promise))
    js_promise_set_is_handled(promise_object)

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:181 Web::WebIDL::is_promise_fulfilled.
pub func idl_is_promise_fulfilled(promise: JsPromiseCapability*) -> bool:
    let promise_object = as_js_promise((gc.Cell*)js_promise_capability_promise(promise))
    return js_promise_state(promise_object) == JsPromiseState.fulfilled

# mark: Wait for all ============================================================================

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:191 Web::WebIDL::WaitForAllResults::WaitForAllResults.
pub func idl_wait_for_all_results_construct(this: IdlWaitForAllResults*, s: gc.Function1[const ak.Vector[JsValue]*, unit]*, t: usize):
    this.success_steps = s
    this.total = t

    # 8. Let result be a list containing total null values.
    ak.vector_ensure_capacity(&this.result, this.total)
    for i in 0..<this.total:
        ak.vector_unchecked_append_u(&this.result, js_null())

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:201 Web::WebIDL::WaitForAllResults::visit_edges (override).
pub func idl_wait_for_all_results_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (IdlWaitForAllResults*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t_2(visitor, this.success_steps)
    # visitor.visit(result): JS::Value is a GC::NanBoxedValue.
    gc.cell_visitor_visit_vector_nan_boxed_value(visitor, (const ak.Vector[gc.NanBoxedValue]*)&this.result)

## The captures of wait_for_all's rejectionHandlerSteps (`[rejected, failure_steps] mutable`).
struct IdlWaitForAllRejectionHandler:
    var rejected: bool
    var failure_steps: gc.Function1[JsValue, unit]*

## wait_for_all's rejectionHandlerSteps, given arg.
func idl_wait_for_all_rejection_handler_steps(context: void*?, vm: Vm*) -> JsValue!:
    let captures = (IdlWaitForAllRejectionHandler*)(context else trap("no captures"))
    # 1. If rejected is true, abort these steps.
    if captures.rejected:
        return js_undefined()

    # 2. Set rejected to true.
    captures.rejected = true

    # 3. Perform failureSteps given arg.
    ak.function1_call(&captures.failure_steps.function, vm_argument(vm, 0))

    return js_undefined()

## wait_for_all's microtask when total is 0: perform successSteps given « ».
func idl_wait_for_all_empty_success(context: void*?):
    let success_steps = (gc.Function1[const ak.Vector[JsValue]*, unit]*)(context else trap("no captures"))
    let empty: ak.Vector[JsValue] = ak.Vector[JsValue]()
    ak.function1_call(&success_steps.function, &empty)

## The captures of wait_for_all's fulfillmentHandler (`[results, promise_index]`).
struct IdlWaitForAllFulfillmentHandler:
    var results: IdlWaitForAllResults*
    var promise_index: usize

## wait_for_all's fulfillmentHandler, given arg.
func idl_wait_for_all_fulfillment_handler_steps(context: void*?, vm: Vm*) -> JsValue!:
    let captures = (IdlWaitForAllFulfillmentHandler*)(context else trap("no captures"))
    let results = captures.results
    let arg = vm_argument(vm, 0)

    # 1. Set result[promiseIndex] to arg.
    *ak.vector_at(&results.result, captures.promise_index) = arg

    # 2. Set fullfilledCount to fullfilledCount + 1.
    results.fulfilled_count += 1

    # 3. If fullfilledCount equals total, then perform successSteps given result.
    if results.fulfilled_count == results.total:
        ak.function1_call(&results.success_steps.function, &results.result)

    return js_undefined()

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:217 Web::WebIDL::wait_for_all.
## https://webidl.spec.whatwg.org/#wait-for-all
pub func idl_wait_for_all(realm: Realm*, promises: const JsPromiseCapability*[], success_steps: ak.Function1[const ak.Vector[JsValue]*, unit], failure_steps: ak.Function1[JsValue, unit]):
    let heap = realm_heap(realm)

    # FIXME: Fix spec typo, fullfilled --> fulfilled
    # 1. Let fullfilledCount be 0.
    # Handled later in WaitForAllResults

    # 2. Let rejected be false.
    # 3. Let rejectionHandlerSteps be the following steps given arg:
    let rejection_handler_steps = new IdlWaitForAllRejectionHandler(rejected = false, failure_steps = gc.create_function1(heap, failure_steps)) else trap("out of memory")

    # 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, 1, "", « »):
    let rejection_handler = js_native_function_create(realm, JsNativeFunctionBehaviour(call = idl_wait_for_all_rejection_handler_steps, context = rejection_handler_steps), 1, ak.utf16_fly_string_new())

    # 5. Let total be promises’s size.
    let total = promises.length

    # 6. If total is 0, then:
    if total == 0:
        # 1. Queue a microtask to perform successSteps given « ».
        let steps = gc.create_function1(heap, success_steps)
        html_queue_a_microtask(none, gc.create_function0(heap, ak.Function0[unit](call = idl_wait_for_all_empty_success, context = steps)))

        # 2. Return.
        return

    # 7. Let index be 0.
    var index: usize = 0

    # 8. Let result be a list containing total null values.
    # Handled in WaitForAllResults

    let results = realm_create_idl_wait_for_all_results(realm, gc.create_function1(heap, success_steps), total)

    # 9. For each promise of promises:
    for promise in promises:
        # 1. Let promiseIndex be index.
        let promise_index = index

        # FIXME: This should be fulfillmentHandlerSteps
        # 2. Let fulfillmentHandler be the following steps given arg:
        let fulfillment_handler_steps = new IdlWaitForAllFulfillmentHandler(results = results, promise_index = promise_index) else trap("out of memory")

        # 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, 1, "", « »):
        let fulfillment_handler = js_native_function_create(realm, JsNativeFunctionBehaviour(call = idl_wait_for_all_fulfillment_handler_steps, context = fulfillment_handler_steps), 1, ak.utf16_fly_string_new())

        # 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
        let promise_object = (JsPromise*)js_promise_capability_promise((JsPromiseCapability*)promise)
        _ = js_promise_perform_then(promise_object, js_value_from_object((JsObject*)fulfillment_handler), js_value_from_object((JsObject*)rejection_handler), none)

        # 5. Set index to index + 1.
        index += 1

## The captures of get_promise_for_wait_for_all's success and failure steps (`[&realm, promise]`).
struct IdlGetPromiseForWaitForAllSteps:
    var realm: Realm*
    var promise: JsPromiseCapability*

## get_promise_for_wait_for_all's successSteps, given results.
func idl_get_promise_for_wait_for_all_success(context: void*?, results: const ak.Vector[JsValue]*):
    let captures = (IdlGetPromiseForWaitForAllSteps*)(context else trap("no captures"))
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, captures.realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)

    # 1. Resolve promise with results.
    let sequence = js_array_create_from(captures.realm, ak.vector_span_const(results))
    idl_resolve_promise(captures.realm, captures.promise, js_value_from_object((JsObject*)sequence))

## get_promise_for_wait_for_all's failureSteps, given reason.
func idl_get_promise_for_wait_for_all_failure(context: void*?, reason: JsValue):
    let captures = (IdlGetPromiseForWaitForAllSteps*)(context else trap("no captures"))
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, captures.realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)

    # 1. Reject promise with reason.
    idl_reject_promise(captures.realm, captures.promise, reason)

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:301 Web::WebIDL::get_promise_for_wait_for_all.
## https://webidl.spec.whatwg.org/#waiting-for-all-promise
pub func idl_get_promise_for_wait_for_all(realm: Realm*, promises: const JsPromiseCapability*[]) -> JsPromiseCapability*:
    # 1. Let promise be a new promise of type Promise<sequence<T>> in realm.
    let promise = idl_create_promise(realm)

    # 2. Let successSteps be the following steps, given results:
    # 3. Let failureSteps be the following steps, given reason:
    let captures = new IdlGetPromiseForWaitForAllSteps(realm = realm, promise = promise) else trap("out of memory")
    let success_steps = ak.Function1[const ak.Vector[JsValue]*, unit](call = idl_get_promise_for_wait_for_all_success, context = captures)
    let failure_steps = ak.Function1[JsValue, unit](call = idl_get_promise_for_wait_for_all_failure, context = captures)

    # 4. Wait for all with promises, given successSteps and failureSteps.
    idl_wait_for_all(realm, promises, success_steps, failure_steps)

    # 5. Return promise.
    return promise

# mark: Non-spec, convenience methods ===========================================================

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:330 Web::WebIDL::create_rejected_promise_from_exception.
pub func idl_create_rejected_promise_from_exception(realm: Realm*, exception: IdlException) -> JsPromiseCapability*:
    let completion = bind_exception_to_throw_completion(realm_vm(realm), exception)
    return idl_create_rejected_promise(realm, js_completion_value(&completion))

## Ported from Libraries/LibWeb/WebIDL/Promise.cpp:336 Web::WebIDL::reject_promise_with_exception.
pub func idl_reject_promise_with_exception(realm: Realm*, promise: JsPromiseCapability*, exception: IdlException):
    let completion = bind_exception_to_throw_completion(realm_vm(realm), exception)
    idl_reject_promise(realm, promise, js_completion_value(&completion))