dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / docs / regions / r14.md
# Region r14: Bindings-lite, WebIDL, JS::Realm and JS::VM — what other regions need to know
Region r14 ports `Bindings/` (`PlatformObject`, `HostDefined`, `PrincipalHostDefined`,
`Intrinsics`, `MainThreadVM`, `ExceptionOrUtils`, the `Audio`/`Image`/`Option` legacy factory
functions, `Serializable`, `Transferable`, `AgentType`) and `WebIDL/` (`ExceptionOr`,
`DOMException` and its 31 named factories, `QuotaExceededError`, `AbstractOperations`,
`AsyncIterator`, `Buffers`, `CallbackType`, `ObservableArray`, `OverloadResolution`, `Promise`,
`Tracing`; `Types.h` and `CachedAttribute.h` have no functions), and the part of LibJS phase 1
needs: `JS::VM`, `JS::Realm`, `JS::ExecutionContext`, `JS::Cell::initialize` and the `JS::Value`
NaN-boxing constructors and tests. The stub fragment `stubs/stub_r14_bindings_webidl.lucb` is
gone.
## Fragments
| Fragment | Donor |
| --- | --- |
| `external/lib_js/vm` | `LibJS/Runtime/VM.cpp/.h` (the, create, gather_roots, heap, agent, the execution context stack, current_realm), `JS::Cell::vm/initialize/is_environment`, `JS::Value` (undefined, null, bool, double, the predicates, `as_double`, `to_number` of primitives), plus the pending-exception slot and the external roots (additions) |
| `external/lib_js/realm` | `LibJS/Runtime/Realm.cpp/.h` (`initialize_host_defined_realm`, `visit_edges`, accessors), `ExecutionContext::create/visit_edges` |
| `bindings/platform_object` | `Bindings/PlatformObject.cpp/.h`; `WEB_SET_PROTOTYPE_FOR_INTERFACE` |
| `bindings/host_defined`, `bindings/principal_host_defined`, `bindings/intrinsics` | the matching `.cpp/.h` |
| `bindings/main_thread_vm` | `Bindings/MainThreadVM.cpp/.h` |
| `bindings/exception_or_utils`, `bindings/serializable`, `bindings/transferable` | the matching headers |
| `bindings/{audio,image,option}_constructor` | the matching `.cpp/.h` |
| `web_idl/exception_or` | `WebIDL/ExceptionOr.h` |
| `web_idl/dom_exception`, `web_idl/quota_exceeded_error` | the matching `.cpp/.h` |
| `web_idl/abstract_operations`, `async_iterator`, `buffers`, `callback_type`, `observable_array`, `overload_resolution`, `promise`, `tracing` | the matching `.cpp/.h` |
| `bindings/tests_bindings`, `web_idl/tests_web_idl`, `web_idl/tests_convert_to_int_vectors` | tests (Ladybird has no unit tests for these files) |
`support.lucb` (`web_allocate_cell`, `web_initialize_cell`) is filled in too.
## What other regions must know
### Creating cells (`realm.create<T>`, `heap.allocate<T>`)
- The generated `realm_create_<class>(realm, …)` helpers work: `web_allocate_cell` takes a
zeroed cell from **the class's own cell allocator** (one per `ClassInfo`, created on first
use, with the finalize / must-survive flags its vtable implies: C++'s
`GC_DECLARE_ALLOCATOR`), sets the most-derived vtable and class id before the constructors run,
and defers GC; the constructor runs; `web_initialize_cell` ends the deferral and runs the
virtual `initialize(realm)`. Constructors therefore never set the cell's vtable, but they do
set the vtables of their **mixins** (C++'s secondary vptrs), as `DOMException`'s constructor
sets `this.serializable.vtable`.
- `heap.allocate<T>(…)` without a realm is `web_heap_allocate_cell(heap, &t_class)`, then the
constructor under `gc.heap_defer_gc`/`heap_undefer_gc`.
- A class's `initialize` override starts with `web_set_prototype_for_interface(base, realm,
BindInterfaceName.<name>)` (WEB_SET_PROTOTYPE_FOR_INTERFACE; a no-op until the JS wrapper exists)
and ends its `Base::initialize(realm)` chain at `js_cell_initialize_impl` (now ported, empty).
- **PlatformObject** gained `m_realm` (what `shape().realm()` answers) and `m_wrapper: JsValue`
(DESIGN.md §3.6); `bind_platform_object_construct_realm` sets them. Its `visit_edges` (JS::Object's)
is `bind_platform_object_visit_edges_impl`: **every platform object's `visit_edges` must call it
as its Base** (r19: EventTarget::visit_edges). The five generated vtables that inherited the
default (NodeList, SVGLength, SVGNumber, SVGTransform, SVGAnimatedEnumeration) now point at it.
- `bind_platform_object_wrapper(object)` is `JS::Value(platform_object)` (phase 3: traps).
### Realms and the VM
- `bind_create_a_new_javascript_realm(vm, create_global_object, create_global_this_value)` runs
InitializeHostDefinedRealm except its JS steps (JS intrinsics, global environment, default
bindings) and needs a `create_global_object` (the Window; without one it traps, P3). Then, as in
C++: `let intrinsics = realm_create_bind_intrinsics(realm, realm)` and
`realm_set_host_defined(realm, bind_principal_host_defined_create(eso, intrinsics, page)
.bind_host_defined())` (or `bind_host_defined_create(intrinsics)`).
- Realm/VM functions: `vm_the`, `vm_heap`, `vm_agent`, `vm_set_agent`,
`vm_push/pop/running_execution_context`, `vm_current_realm`, `realm_vm`, `realm_heap`,
`realm_global_object`, `realm_host_defined`, `realm_set_host_defined`,
`js_execution_context_create` / `js_execution_context_visit_edges` (an owner of an
execution context, e.g. the EnvironmentSettingsObject, visits it). New rows in `namemap.tsv`.
- `JS::Realm` is a cell (class `realm_class`, sharing JS::Cell's class id 1 until the generator
numbers it). `JS::VM` is on the C heap (reference counted in C++) and owns the `gc.Heap`; its
`gather_roots` reports the realms/functions on the execution context stack, the pending
exception and the **external roots**: `vm_keep_alive(vm, pointer)` keeps managed memory that
only unscanned memory refers to (module globals) alive. (`bind_initialize_main_thread_vm` no
longer keeps `Gfx::FontDatabase::the()` with it: the database and everything it keeps live in
the C heap, DESIGN.md §3.3 rule 7.)
- `bind_initialize_main_thread_vm` creates the agent through `html_similar_origin_window_agent_create`
(r29, still a stub: so it traps until r29 lands). The agent is owned by the VM, so
`bind_create_agent` allocates it under `with memory.heap:`; **r29**: its `GC::Root` /
`GC::RootVector` members (`event_loop`, `pending_mutation_observers`, `signal_slots`, …) live
outside the heap and must be real `gc.Root`s / be rooted (DESIGN.md §3.3 rule 4).
- The LibJS host hooks `initialize_main_thread_vm` installs (promise jobs, job callbacks, module
loading, …) are listed in place and come with luce-js in phase 3.
### WebIDL exceptions (DESIGN.md §2.10)
- The pending-exception slot is the VM's (`Vm.m_pending_exception`, a small cell the VM roots,
so a pending DOMException and a SimpleException's message String survive collections).
`idl_throw(exception) -> never!` keeps its signature (r15's call sites are unchanged); it stores
into `vm_the()`'s slot. The catcher takes it with `idl_take_pending_exception()` (DESIGN.md calls
it `webidl_take_pending_exception`) or `vm_take_pending_exception(vm)`.
`idl_throw_simple(type, message)` throws a SimpleException.
- `vm.throw_completion<JS::XError>(message)` is `vm_throw_completion(vm, .x_error, message)`: until
phase 3 the JS completion is represented by the SimpleException that converts to it, and the
function fails with `js_exception`.
- `TRY(throw_dom_exception_if_needed(vm, [&] { return f(); }))` is
`f() catch: try bind_throw_dom_exception_if_needed(vm)` (it converts the pending WebIDL
exception into a JS completion; P3 for SimpleException/DOMException).
- Formatting: `idl_dom_exception_to_string` ("[Name]: message"), `idl_exception_to_string`,
`idl_simple_exception_message`.
### Test helpers (any region's tests may use them)
`web_test_create_vm()` / `web_test_destroy_vm(vm)` (a VM that is the main thread VM for the
test; destroy collects and frees everything), `web_test_create_realm(vm)` (a realm whose global
object is a plain platform object, with intrinsics and a HostDefined: `realm_create_<class>`
works in it), and for GC tests `web_test_clobber_stack`, `web_test_alive`, `web_test_throw`
(see `bindings/tests_bindings.lucb`).
## Signature and type changes
- **Types filled by hand**: `Realm`, `Vm` (+ `JsPendingException`, `JsVmExternalRoots`),
`JsExecutionContext` (`function`, `realm`), `BindPlatformObject` (`m_realm`, `m_wrapper`, and its
vtable's `visit_edges`), the DOMException and QuotaExceededError vtables (WEB_PLATFORM_OBJECT's
`interface_name` / `implements_interface`), `BindUnforgeableKeyTraits` (hash and equality), the
five vtables above. The generator should emit WEB_PLATFORM_OBJECT's two overrides for every
class and route inherited `visit_edges` slots of platform objects to PlatformObject's.
- `js_cell_initialize_impl` and `js_cell_is_environment_impl` moved from `stubs/stub_closure.lucb`
to `external/lib_js/vm.lucb` (ported).
- `idl_pending_exception` (r15's module var) is gone: the slot is the VM's.
- `bind_create_agent` is private and answers `HtmlAgent*` (was `JsAgent*`, opaque).
- `bind_exception_to_throw_completion(vm, exception: IdlException)` (was `void*?`);
`bind_throw_dom_exception_if_needed(vm) -> never!` (was a template over the callable).
- `idl_convert_to_int(vm, value, type_: IdlIntegerType, enforce_range, clamp) -> f64!` (was a
template `[T] -> T!`, which a Luce generic cannot express: it needs T's limits): the new enum
`IdlIntegerType` names the eight instantiations; the answer is the integer as an exact f64, which
the caller converts as the C++ return statement does.
- `idl_invoke_callback_impl` is private and non-generic (answers `JsCompletion`).
- `idl_log_trace(vm, function: str)` (was `const u8*?`).
- `idl_get_legacy_code_for_name` is private; `idl_convert_ecmascript_type_to_idl_value` and
`idl_has_overload_with_argument_type_or_subtype_matching` stay public until their caller
(`resolve_overload`, P3) is ported (otherwise unused-function warnings).
- `module.lucb` imports `math`.
## Deviations and what is not ported yet
- **Phase 3 (luce-js)**: everything whose steps are operations on JS objects traps with
`unported (P3): …`: the legacy platform object internal methods, the wrapper,
the Audio/Image/Option constructors, ensure_web_prototype/constructor/namespace and unforgeable
functions, callbacks (call_user_object_operation, invoke_callback, construct), promises,
AsyncIterator's iteration, buffer sources, ObservableArray's array storage, overload resolution,
the JS string conversions, ToNumber of strings/objects, the ErrorData of DOMException,
`Web::throw_completion`, set_prototype_from_new_target. Each keeps its spec link and steps in place.
- **Structured serialization** (`serialization_steps` / `deserialization_steps` of DOMException
and QuotaExceededError) traps: `HTML::TransferDataEncoder/Decoder` are opaque.
- `active_script()` answers none: every execution context's ScriptOrModule is null before
scripts run.
- A VM may be created while another exists (tests); C++ allows one per process.
- **Donor quirk** (pinned in the test vectors): on AArch64, `AK::round_to<unsigned>(double)` uses
the signed `fcvtns`, so `[Clamp] unsigned long` saturates at 2^31 − 1 in the reference build.
ak's `rounding_round_to_f64_u32` (luce-browser-foundation) converts as x86-64 Ladybird and the
spec do; the 9 affected vectors expect that and say so.
## Tests
`bindings/tests_bindings.lucb` (13 tests) and `web_idl/tests_web_idl.lucb` (14 tests): the VM and
its execution context stack; create_a_new_javascript_realm; HostDefined/PrincipalHostDefined and
the intrinsics; realm.create (allocator per class, vtable, class id, zeroed fields, initialize,
DeferGC released); allocator finalize flags; PlatformObject's defaults; WEB_PLATFORM_OBJECT's
overrides; Transferable; UnforgeableKey traits; GC: the pending exception is a root (the
DOMException dies once taken), a realm on the execution context stack keeps its intrinsics and
global object, `vm_keep_alive` keeps a blob and what it points to; every DOMException legacy code
and named factory; the formatters; ExceptionOr propagation with webidl_exception; SimpleExceptions;
QuotaExceededError's constructor checks; ConvertToInt against 744 calls recorded from the
reference build (8 types × 31 inputs × {plain, [Clamp], [EnforceRange]}, including the TypeError
messages); ToNumber of primitives; IntegerPart; JS::modulo; LibJS's NaN-boxing bit patterns.
The reference values come from a local driver linked against the reference build's
`liblagom-web`/`liblagom-js` (kept in `.donors`-side scratch, not committed).