dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / bindings / main_thread_vm.lucb
#==============================================================================================
#
# main_thread_vm - Bindings::MainThreadVM: the process's VM, its agent, new JavaScript realms
#
# DESCRIPTION:
# Port of Libraries/LibWeb/Bindings/MainThreadVM.cpp (lines 1-809) and MainThreadVM.h
# (lines 1-44). initialize_main_thread_vm creates the VM and its surrounding agent;
# create_a_new_javascript_realm is how every Window (and the internal CSS realm) gets its
# realm; the mutation-observer microtask and the custom element reactions are the agent's.
# Of the host hooks initialize_main_thread_vm installs into LibJS, the promise ones
# (rejection tracking, job callbacks, promise jobs) are in main_thread_vm_host_hooks; the
# others (finalization registry cleanup, import.meta, module loading, private elements,
# string compilation, eval code, array buffer resizing) are callbacks of the JS engine:
# they are listed at their place and come with luce-js in phase 3.
#
# 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>
# Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: WebEngineCustomJobCallbackData ==========================================================
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.h:23 Web::Bindings::WebEngineCustomJobCallbackData::WebEngineCustomJobCallbackData.
pub func bind_web_engine_custom_job_callback_data_construct(this: BindWebEngineCustomJobCallbackData*, incumbent_settings: HtmlEnvironmentSettingsObject*, active_script_context: JsExecutionContext*?):
this.vtable = &bind_web_engine_custom_job_callback_data_vtable
this.incumbent_settings = incumbent_settings
this.active_script_context = active_script_context
# mark: The main thread VM ======================================================================
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:56 Web::Bindings::active_script.
## https://html.spec.whatwg.org/multipage/webappapis.html#active-script
pub func bind_active_script() -> HtmlScript*?:
# 1. Let record be GetActiveScriptOrModule().
# 2. If record is null, return null.
# 3. Return record.[[HostDefined]].
# The ScriptOrModule of every execution context is null until scripts run (phase 3), so
# record is null.
_ = bind_main_thread_vm()
return none
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:75 Web::Bindings::create_agent. The
## agent is owned by the VM (NonnullOwnPtr), so it lives on the C heap as the VM does.
func bind_create_agent(heap: gc.Heap*, type_: BindAgentType) -> HtmlAgent*:
with memory.heap:
match type_:
.similar_origin_window:
return html_similar_origin_window_agent_create(heap).html_agent()
.dedicated_worker, .shared_worker:
trap("unported (P4): HTML::WorkerAgent::create(heap, JS::Agent::CanBlock::Yes)")
.service_worker:
trap("unported (P4): HTML::WorkerAgent::create(heap, JS::Agent::CanBlock::No)")
_:
trap("VERIFY_NOT_REACHED")
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:91 Web::Bindings::initialize_main_thread_vm.
pub func bind_initialize_main_thread_vm(type_: BindAgentType):
assert(bind_s_main_thread_vm == none)
let vm = vm_create()
bind_s_main_thread_vm = vm
vm_set_agent(vm, bind_create_agent(vm_heap(vm), type_))
# on_unimplemented_property_access: dbgln("FIXME: Unimplemented IDL interface: '{}.{}'") for
# a property of a JS object (phase 3).
# NOTE: We intentionally leak the main thread JavaScript VM.
# This avoids doing an exhaustive garbage collection on process exit.
# (The VM is never freed in the port.)
# The host hooks of promises (HostPromiseRejectionTracker, HostCallJobCallback,
# HostEnqueuePromiseJob, host_promise_job_queue_is_empty, HostMakeJobCallback) run the
# phase-1 promises (DESIGN.md §3.6); see main_thread_vm_host_hooks.
bind_install_main_thread_vm_host_hooks(vm)
# The other host hooks are callbacks of the JS engine, installed with luce-js in phase 3:
# 8.1.6.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
# 8.1.6.2 HostEnsureCanCompileStrings(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(realm,-parameterstrings,-bodystring,-codestring,-compilationtype,-parameterargs,-bodyarg)
# 8.1.6.3 HostGetCodeForEval(argument), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetcodeforeval(argument)
# 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
# 8.1.6.7.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
# 8.1.6.7.2 HostGetSupportedImportAttributes(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
# 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload), https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule
# host_unrecognized_date_string, host_resize_array_buffer, host_grow_shared_array_buffer.
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:662 Web::Bindings::main_thread_vm.
pub func bind_main_thread_vm() -> Vm*:
return bind_s_main_thread_vm else trap("VERIFY: the main thread VM is initialized")
# mark: Mutation observers ======================================================================
## The captures of queue_mutation_observer_microtask's microtask (`[&surrounding_agent]`).
struct BindQueueMutationObserverMicrotaskNotify:
var surrounding_agent: HtmlSimilarOriginWindowAgent*
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:669 Web::Bindings::queue_mutation_observer_microtask.
## https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
pub func bind_queue_mutation_observer_microtask():
let vm = bind_main_thread_vm()
let agent = vm_agent(vm) else trap("VERIFY: the VM has an agent")
let surrounding_agent = as_html_similar_origin_window_agent(agent)
# 1. If the surrounding agent’s mutation observer microtask queued is true, then return.
if surrounding_agent.mutation_observer_microtask_queued:
return
# 2. Set the surrounding agent’s mutation observer microtask queued to true.
surrounding_agent.mutation_observer_microtask_queued = true
# 3. Queue a microtask to notify mutation observers.
let captures = (new BindQueueMutationObserverMicrotaskNotify(surrounding_agent = surrounding_agent)) else trap("out of memory")
html_queue_a_microtask(none, gc.create_function0[unit](vm_heap(vm), ak.Function0[unit](call = bind_notify_mutation_observers, context = captures)))
## The microtask of queue_mutation_observer_microtask.
## https://dom.spec.whatwg.org/#notify-mutation-observers
func bind_notify_mutation_observers(context: void*?):
let captures = (BindQueueMutationObserverMicrotaskNotify*)(context else trap("no captures"))
let surrounding_agent = captures.surrounding_agent
# 1. Set the surrounding agent’s mutation observer microtask queued to false.
surrounding_agent.mutation_observer_microtask_queued = false
# 2. Let notifySet be a clone of the surrounding agent’s pending mutation observers.
# 3. Empty the surrounding agent’s pending mutation observers.
var notify_set = surrounding_agent.pending_mutation_observers
surrounding_agent.pending_mutation_observers = ak.Vector[DomMutationObserver*]()
# 4. Let signalSet be a clone of the surrounding agent’s signal slots.
# 5. Empty the surrounding agent’s signal slots.
var signal_set = surrounding_agent.signal_slots
surrounding_agent.signal_slots = ak.Vector[HtmlSlotElement*]()
# 6. For each mo of notifySet:
for mutation_observer in ak.vector_span(¬ify_set):
# 1. Let records be a clone of mo’s record queue.
# 2. Empty mo’s record queue.
var records = dom_mutation_observer_take_records(mutation_observer)
# 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from
# node’s registered observer list.
for weak_node in ak.vector_span(dom_mutation_observer_node_list(mutation_observer)):
# FIXME: Is this correct?
let node = gc.weak_ptr(&weak_node) else continue
if let list = *dom_node_registered_observer_list(node):
_ = ak.vector_remove_all_matching(list, ak.Function1[const (DomRegisteredObserver*)*, bool](call = bind_is_transient_registered_observer_of, context = mutation_observer))
# 4. If records is not empty, then invoke mo’s callback with « records, mo » and "report", and with
# callback this value mo.
if not ak.vector_is_empty(&records):
# The records are wrapped in a JS Array and the callback is a JS function (phase 3).
trap("unported (P3): notify mutation observers: invoke the callback with a JS::Array of the records")
# 7. For each slot of signalSet, fire an event named slotchange, with its bubbles attribute set to true, at slot.
for slot in ak.vector_span(&signal_set):
var event_init = DomEventInit()
event_init.bubbles = true
_ = dom_event_target_dispatch_event(slot.dom_event_target(), dom_event_create(bind_platform_object_realm(slot.bind_platform_object()), html_event_names_slotchange, event_init))
## The predicate of notify mutation observers' remove_all_matching: a transient registered
## observer whose observer is the mutation observer `context`.
func bind_is_transient_registered_observer_of(context: void*?, registered_observer: const (DomRegisteredObserver*)*) -> bool:
let mutation_observer = (DomMutationObserver*)(context else trap("no captures"))
let observer = *registered_observer
return is_dom_transient_registered_observer(observer) and dom_registered_observer_observer(observer) == mutation_observer
# mark: Realms ==================================================================================
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:742 Web::Bindings::create_a_new_javascript_realm.
## https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
pub func bind_create_a_new_javascript_realm(vm: Vm*, create_global_object: ak.Function1[Realm*, JsObject*?], create_global_this_value: ak.Function1[Realm*, JsObject*?]) -> JsExecutionContext*:
# 1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.
# 2. Let realm execution context be the running JavaScript execution context.
let realm_execution_context = realm_initialize_host_defined_realm(vm, create_global_object, create_global_this_value) else trap("MUST: InitializeHostDefinedRealm")
# 3. Remove realm execution context from the JavaScript execution context stack.
let popped_execution_context = vm_pop_execution_context(vm)
assert(popped_execution_context == realm_execution_context)
# NO-OP: 4. Let realm be realm execution context's Realm component.
# NO-OP: 5. Set realm's agent to agent.
# FIXME: 6. If agent's agent cluster's cross-origin isolation mode is "none", then:
# 1. Let global be realm's global object.
# 2. Let status be ! global.[[Delete]]("SharedArrayBuffer").
# 3. Assert: status is true.
# 7. Return realm execution context.
return realm_execution_context
# mark: Custom elements =========================================================================
## Ported from Libraries/LibWeb/Bindings/MainThreadVM.cpp:765 Web::Bindings::invoke_custom_element_reactions.
## https://html.spec.whatwg.org/multipage/custom-elements.html#invoke-custom-element-reactions
pub func bind_invoke_custom_element_reactions(element_queue: ak.Vector[gc.Weak[DomElement]]*):
# 1. While queue is not empty:
while not ak.vector_is_empty(element_queue):
# 1. Let element be the result of dequeuing from queue.
let weak_element = ak.vector_take_first(element_queue)
let element = gc.weak_ptr(&weak_element) else continue
# 2. Let reactions be element's custom element reaction queue.
# 3. Repeat until reactions is empty:
let reactions = dom_element_custom_element_reaction_queue(element) else continue
while not ak.vector_is_empty(reactions):
# 1. Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:
let reaction = ak.vector_take_first(reactions)
match reaction:
.dom_custom_element_upgrade_reaction(custom_element_upgrade_reaction):
# -> upgrade reaction
# Upgrade element using reaction's custom element definition.
let definition = custom_element_upgrade_reaction.custom_element_definition else trap("upgrade reaction without a definition")
dom_element_upgrade_element(element, definition) catch:
# If this throws an exception, catch it, and report it for reaction's custom element definition's constructor's corresponding JavaScript object's associated realm's global object.
# FIXME: Should it be easier to get to report an exception from an IDL callback?
# (The constructor is a JS function; its realm is its shape's: phase 3.)
trap("unported (P3): report the exception of a custom element upgrade")
.dom_custom_element_callback_reaction(custom_element_callback_reaction):
# -> callback reaction
# Invoke reaction's callback function with reaction's arguments and "report", and callback this value set to element.
let callback = custom_element_callback_reaction.callback else trap("callback reaction without a callback")
_ = idl_invoke_callback_idl_exception_behavior(callback, bind_platform_object_wrapper(element.bind_platform_object()), IdlExceptionBehavior.report, ak.vector_span_const(&custom_element_callback_reaction.arguments))