Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / bindings / main_thread_vm_host_hooks.lucb

#==============================================================================================
#
#   main_thread_vm_host_hooks - the promise host hooks of the main thread VM
#
#   DESCRIPTION:
#       Port of the host hooks Libraries/LibWeb/Bindings/MainThreadVM.cpp (lines 133-360)
#       installs for promises: HostPromiseRejectionTracker, HostCallJobCallback,
#       HostEnqueuePromiseJob (promise jobs become microtasks), the promise job queue check and
#       HostMakeJobCallback. They run the phase-1 promises of DESIGN.md ยง3.6. The other hooks
#       (modules, eval, private elements, finalization registries, array buffers) come with
#       luce-js in phase 3. No script is active before phase 3, so the active script and the
#       running script are null and every ScriptOrModule is empty.
#
#       Copyright (c) 2021-2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
#       Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
#       Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Installing the hooks ====================================================================

## The promise host hooks of Bindings::initialize_main_thread_vm (MainThreadVM.cpp:133-360), set
## on `vm`. Addition: initialize_main_thread_vm calls it where C++ assigns them, and the tests'
## VMs (web_test_install_agent) get the same hooks.
pub func bind_install_main_thread_vm_host_hooks(vm: Vm*):
    # 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
    vm.host_promise_rejection_tracker = bind_host_promise_rejection_tracker

    # 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
    vm.host_call_job_callback = bind_host_call_job_callback

    # 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
    vm.host_enqueue_promise_job = bind_host_enqueue_promise_job
    vm.host_promise_job_queue_is_empty = bind_host_promise_job_queue_is_empty

    # 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
    vm.host_make_job_callback = bind_host_make_job_callback

# mark: HostPromiseRejectionTracker =============================================================

## The captures of the rejectionhandled task (`[&global, &promise]`).
struct BindRejectionHandledTask:
    var global_mixin: HtmlUniversalGlobalScopeMixin*
    var promise: JsPromise*

## The rejectionhandled task: fire an event named rejectionhandled at global, using
## PromiseRejectionEvent.
func bind_fire_rejectionhandled(context: void*?):
    let captures = (BindRejectionHandledTask*)(context else trap("no captures"))
    let global = html_universal_global_scope_mixin_this_impl(captures.global_mixin)
    # FIXME: This currently assumes that global is a WindowObject.
    let window = as_html_window((gc.Cell*)global)

    var event_init = html_promise_rejection_event_init_default()
    event_init.promise = (JsObject*)captures.promise
    event_init.reason = js_promise_result(captures.promise)
    let promise_rejection_event = html_promise_rejection_event_create(html_relevant_realm((JsObject*)global), html_event_names_rejectionhandled, event_init)
    _ = dom_event_target_dispatch_event(window.dom_event_target(), promise_rejection_event.dom_event())

## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:133 (host_promise_rejection_tracker):
## 8.1.5.3 HostPromiseRejectionTracker(promise, operation),
## https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
func bind_host_promise_rejection_tracker(vm: Vm*, promise: JsPromise*, operation: JsPromiseRejectionOperation):
    # 1. Let script be the running script.
    #    The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
    # (Every ScriptOrModule is empty before phase 3, so script is null.)

    # 2. If script is a classic script and script's muted errors is true, then return.
    # NOTE: is<T>() returns false if nullptr is passed.

    # 3. Let settingsObject be the current settings object.
    # 4. If script is not null, then set settings object to script's settings object.
    let settings_object = html_current_settings_object()

    # 5. Let global be settingsObject's global object.
    let global_mixin = html_environment_settings_object_universal_global_scope(settings_object)
    # (`global` is the mixin's this_impl(); the rejectionhandled task reads it.)

    match operation:
        # 6. If operation is "reject",
        .reject:
            # 1. Append promise to global's about-to-be-notified rejected promises list.
            html_universal_global_scope_mixin_push_onto_about_to_be_notified_rejected_promises_list(global_mixin, promise)
        # 7. If operation is "handle",
        .handle:
            # 1. If global's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
            let removed_about_to_be_notified_rejected_promise = html_universal_global_scope_mixin_remove_from_about_to_be_notified_rejected_promises_list(global_mixin, promise)
            if removed_about_to_be_notified_rejected_promise:
                return

            # 3. Remove promise from global's outstanding rejected promises weak set.
            let removed_outstanding_rejected_promise = html_universal_global_scope_mixin_remove_from_outstanding_rejected_promises_weak_set(global_mixin, promise)

            # 2. If global's outstanding rejected promises weak set does not contain promise, then return.
            # NOTE: This is done out of order because removed_outstanding_rejected_promise will be false if the promise wasn't in the set or true if it was and got removed.
            if not removed_outstanding_rejected_promise:
                return

            # 4. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
            #    with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
            let global = html_universal_global_scope_mixin_this_impl(global_mixin)
            let captures = new BindRejectionHandledTask(global_mixin = global_mixin, promise = promise) else trap("out of memory")
            _ = html_queue_global_task(HtmlTaskSource.dom_manipulation, (JsObject*)global, gc.create_function0(vm_heap(vm), ak.Function0[unit](call = bind_fire_rejectionhandled, context = captures)))
        _:
            trap("VERIFY_NOT_REACHED")

# mark: Job callbacks ===========================================================================

## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:208 (host_call_job_callback):
## 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList),
## https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
func bind_host_call_job_callback(vm: Vm*, callback: JsJobCallback*, this_value: JsValue, arguments_list: const JsValue[]) -> JsValue!:
    let callback_host_defined = (BindWebEngineCustomJobCallbackData*)(js_job_callback_custom_data(callback) else trap("as<WebEngineCustomJobCallbackData>: no custom data"))

    # 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]].
    let incumbent_settings = callback_host_defined.incumbent_settings

    # 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]].
    let script_execution_context = callback_host_defined.active_script_context

    # 3. Prepare to run a callback with incumbent settings.
    html_prepare_to_run_callback(incumbent_settings)

    # 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
    if let context = script_execution_context:
        vm_push_execution_context(vm, context)

    # 5. Let result be Call(callback.[[Callback]], V, argumentsList).
    let result = js_call(vm, js_job_callback_callback(callback), this_value, arguments_list) catch failure:
        # 6. and 7. below, then 8. Return result (a throw completion, still in the VM's slot).
        bind_host_call_job_callback_clean_up(vm, incumbent_settings, script_execution_context)
        error(failure.code, failure.message)

    bind_host_call_job_callback_clean_up(vm, incumbent_settings, script_execution_context)

    # 8. Return result.
    return result

## Steps 6 and 7 of HostCallJobCallback.
func bind_host_call_job_callback_clean_up(vm: Vm*, incumbent_settings: HtmlEnvironmentSettingsObject*, script_execution_context: JsExecutionContext*?):
    # 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
    if let context = script_execution_context:
        assert(vm_running_execution_context(vm) == context)
        _ = vm_pop_execution_context(vm)

    # 7. Clean up after running a callback with incumbent settings.
    html_clean_up_after_running_callback(incumbent_settings)

## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:338 (host_make_job_callback):
## 8.1.5.4.4 HostMakeJobCallback(callable),
## https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
func bind_host_make_job_callback(vm: Vm*, callable: JsFunctionObject*) -> JsJobCallback*:
    # 1. Let incumbent settings be the incumbent settings object.
    let incumbent_settings = html_incumbent_settings_object()

    # 2. Let active script be the active script.
    let script = bind_active_script()

    # 3. Let script execution context be null.
    let script_execution_context: JsExecutionContext*? = none

    # 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
    #    its Realm field set to active script's settings object's realm, and its ScriptOrModule set to active script's record.
    if script != none:
        trap("unported (P3): HostMakeJobCallback with an active script")

    # 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.
    let host_defined = new BindWebEngineCustomJobCallbackData(vtable = &bind_web_engine_custom_job_callback_data_vtable, class_id = 0, incumbent_settings = incumbent_settings, active_script_context = none) else trap("out of memory")
    bind_web_engine_custom_job_callback_data_construct(host_defined, incumbent_settings, script_execution_context)
    return js_job_callback_create(vm, callable, host_defined)

# mark: HostEnqueuePromiseJob ===================================================================

## The captures of HostEnqueuePromiseJob's microtask (`[&vm, job_settings, job, script_or_module]`).
struct BindPromiseJobMicrotask:
    var vm: Vm*
    var job_settings: HtmlEnvironmentSettingsObject*?
    var job: JsPromiseJobFunction*
    var script_or_module: JsScriptOrModule

## HostEnqueuePromiseJob's microtask: run the job prepared to run script.
func bind_run_promise_job(context: void*?):
    let captures = (BindPromiseJobMicrotask*)(context else trap("no captures"))
    let vm = captures.vm

    # The dummy execution context has to be kept up here to keep it alive for the duration of the function.
    # (It is managed memory, which the VM's execution context stack keeps while it is pushed.)

    if let job_settings = captures.job_settings:
        # 1. If job settings is not null, then prepare to run script with job settings.
        html_prepare_to_run_script(job_settings)

        # IMPLEMENTATION DEFINED: Additionally to preparing to run a script, we also prepare to run a callback here. This matches WebIDL's
        #                         invoke_callback() / call_user_object_operation() functions, and prevents a crash in host_make_job_callback()
        #                         when getting the incumbent settings object.
        html_prepare_to_run_callback(job_settings)

        # IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
        #                         Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
        html_environment_settings_object_realm_execution_context(job_settings).script_or_module = captures.script_or_module
    else:
        # FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
        #        This is because JS::NativeFunction::call excepts something to be on the execution context stack to be able to get the caller context to initialize the environment.
        #        Do note that the JS spec gives _no_ guarantee that the execution context stack has something on it if HostEnqueuePromiseJob was called with a null realm: https://tc39.es/ecma262/#job-preparedtoevaluatecode
        let dummy = js_execution_context_create()
        dummy.script_or_module = captures.script_or_module
        vm_push_execution_context(vm, dummy)

    # 2. Let result be job().
    let result = ak.function0_call(&captures.job.function)

    # 3. If job settings is not null, then clean up after running script with job settings.
    if let job_settings = captures.job_settings:
        # IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
        html_environment_settings_object_realm_execution_context(job_settings).script_or_module = JsScriptOrModule.empty

        # IMPLEMENTATION DEFINED: See comment above, we need to clean up the non-standard prepare_to_run_callback() call.
        html_clean_up_after_running_callback(job_settings)

        html_clean_up_after_running_script(job_settings)
    else:
        # Pop off the dummy execution context. See the above FIXME block about why this is done.
        _ = vm_pop_execution_context(vm)

    # 4. If result is an abrupt completion, then report the exception given by result.[[Value]].
    if js_completion_is_error(&result):
        let job_settings = captures.job_settings else trap("VERIFY: a failed promise job has job settings")
        html_report_exception_js_completion(result, html_environment_settings_object_realm(job_settings))

## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:266 (host_enqueue_promise_job):
## 8.1.5.4.3 HostEnqueuePromiseJob(job, realm),
## https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
func bind_host_enqueue_promise_job(vm: Vm*, job: JsPromiseJobFunction*, realm: Realm*?):
    # IMPLEMENTATION DEFINED: The JS spec says we must take implementation defined steps to make the currently active script or module at the time of HostEnqueuePromiseJob being invoked
    #                         also be the active script or module of the job at the time of its invocation.
    #                         This means taking it here now and passing it through to the lambda.
    # (GetActiveScriptOrModule is empty before phase 3.)
    let script_or_module = JsScriptOrModule.empty

    # 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
    var job_settings: HtmlEnvironmentSettingsObject*? = none
    if let job_realm = realm:
        job_settings = html_principal_realm_settings_object(job_realm)

    # 2. Queue a microtask to perform the following steps:
    # This instance of "queue a microtask" uses the "implied document". The best fit for "implied document" here is "If the task is being queued by or for a script, then return the script's settings object's responsible document."
    # Do note that "implied document" from the spec is handwavy and the spec authors are trying to get rid of it: https://github.com/whatwg/html/issues/4980
    let script = bind_active_script()
    if script != none:
        trap("unported (P3): HostEnqueuePromiseJob with an active script (its responsible document)")

    let heap = realm_heap(realm else trap("unreachable")) if realm != none else vm_heap(vm)
    let captures = new BindPromiseJobMicrotask(vm = vm, job_settings = job_settings, job = job, script_or_module = script_or_module) else trap("out of memory")
    html_queue_a_microtask(none, gc.create_function0(heap, ak.Function0[unit](call = bind_run_promise_job, context = captures)))

## The host_promise_job_queue_is_empty of MainThreadVM.cpp:334: the main thread event loop's
## microtask queue is empty.
func bind_host_promise_job_queue_is_empty(vm: Vm*) -> bool:
    return html_event_loop_microtask_queue_empty(html_main_thread_event_loop())