Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / external / lib_js / vm.lucb

#==============================================================================================
#
#   vm - JS::VM, JS::Cell and the JS::Value seam of the web engine
#
#   DESCRIPTION:
#       LibJS is not ported (DESIGN.md §1.1, §3.6): luce-js takes its place in phase 3. What
#       LibWeb needs of JS::VM before scripting is ported from Libraries/LibJS/Runtime/VM.cpp/.h
#       here: the one VM of the process (VM::the), its heap with the roots the VM gathers, the
#       surrounding agent and the JavaScript execution context stack. The VM also holds the
#       pending exception of DESIGN.md §2.10: a function returning `WebIDL::ExceptionOr<T>` or
#       `JS::ThrowCompletionOr<T>` is `T!`, and it stores the exception in the VM before failing
#       with webidl_exception or js_exception; the catcher takes it with
#       vm_take_pending_exception. JS::Cell's initialize and vm() and the few JS::Value
#       constructors LibWeb uses before phase 3 complete the seam.
#
#       Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
#       Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: The VM ==================================================================================

## Ported from Libraries/LibJS/Runtime/VM.h:66 JS::VM::the.
pub func vm_the() -> Vm*:
    return vm_s_the else trap("JS::VM::the: no VM")

## Ported from Libraries/LibJS/Runtime/VM.cpp:42 JS::VM::create and VM.cpp:73 JS::VM::VM: a VM
## and its heap, on the C heap (the VM is reference counted in C++, never collected). The
## cached strings and well-known symbols are JS values (phase 3). Unlike C++, which allows one
## VM per process, a new VM may be created while another exists (the tests make several);
## VM::the is the newest.
pub func vm_create() -> Vm*:
    let storage = (new Vm[1] --- in memory.heap) else trap("out of memory")
    memory.set(u8[]((u8*)storage.data, memory.size_of(Vm)), 0)
    let vm = (Vm*)storage.data
    gc.heap_construct(&vm.m_heap, ak.Function1[gc.GcHashMap[gc.HeapRoot]*, unit](call = vm_gather_roots_callback, context = vm))
    vm_s_the = vm

    # Addition (DESIGN.md §2.10): the cell of the pending exception, a root of the VM.
    let cell = web_heap_allocate_cell(&vm.m_heap, &js_pending_exception_class)
    vm.m_pending_exception = (JsPendingException*)cell

    # Addition (DESIGN.md §3.3 rule 4): the external roots (vm_keep_alive).
    vm.m_external_roots.base.vtable = &js_vm_external_roots_vtable
    gc.conservative_vector_base_construct(&vm.m_external_roots.base, &vm.m_heap)

    # Default hook implementations. These can be overridden by the host, for example, LibWeb overrides the default hooks to place promise jobs on the microtask queue.
    vm.host_promise_rejection_tracker = vm_promise_rejection_tracker
    vm.host_call_job_callback = js_call_job_callback
    vm.host_enqueue_promise_job = vm_enqueue_promise_job
    vm.host_promise_job_queue_is_empty = vm_promise_job_queue_is_empty
    vm.host_make_job_callback = vm_default_make_job_callback
    return vm

## The VM destroyed: its process statics forgotten, every cell collected and finalized, the heap
## given back. C++ destroys its one VM with the process (the main thread VM is leaked on
## purpose); the tests make and destroy a VM per test, in one process (DESIGN.md §3.3 rule 7).
pub func vm_destroy(vm: Vm*):
    vm_forget_process_statics(vm)
    gc.conservative_vector_base_destroy(&vm.m_external_roots.base)
    gc.heap_destroy(vm_heap(vm))
    # The agent (region r29) outlives the heap's last collection: finalizers reach its event loop.
    if let agent = vm.m_agent:
        if let window_agent = as_if_html_similar_origin_window_agent(agent):
            html_similar_origin_window_agent_destroy(window_agent)
        vm.m_agent = none
    with memory.heap:
        ak.vector_clear(&vm.m_execution_context_stack)
        ak.vector_clear(&vm.m_promise_jobs)
    if vm_s_the == vm:
        vm_s_the = none
    if bind_s_main_thread_vm == vm:
        bind_s_main_thread_vm = none
    free(vm) in memory.heap

## Forgets LibWeb's statics that hold cells or a VM's state: function-local statics and
## singletons that live, in Ladybird, as long as the process and so as long as its one VM (each
## WebContent process, each test binary has one). Here a process may make several VMs one after
## another, so these belong to the VM they were made in and go with it; the next VM makes its
## own on first use, as a new process would. Their roots are released while the heap is still
## there. (The statics that keep nothing of a VM, such as the style values' static instances,
## live in the C heap for the process instead, DESIGN.md §3.3 rule 7.)
func vm_forget_process_statics(vm: Vm*):
    resource_loader_forget(vm_heap(vm))
    internal_css_realm_forget()
    css_forget_user_agent_stylesheets()
    html_input_element_forget_static_styles()
    html_batching_dispatcher_forget()
    file_api_blob_url_store_forget()

## The heap's gather_embedder_roots: the VM's gather_roots (the lambda of VM.cpp:74).
func vm_gather_roots_callback(context: void*?, roots: gc.GcHashMap[gc.HeapRoot]*):
    vm_gather_roots((Vm*)(context else trap("no VM")), roots)

## Ported from Libraries/LibJS/Runtime/VM.cpp:273 JS::VM::gather_roots: what the VM holds in the
## heap from outside it. The interned strings, symbols and finalization registries are phase 3;
## the execution contexts' cells, the promise jobs and the pending exception are here.
pub func vm_gather_roots(this: Vm*, roots: gc.GcHashMap[gc.HeapRoot]*):
    # Addition (DESIGN.md §2.10): the pending exception.
    if let pending_exception = this.m_pending_exception:
        gc.gc_hash_map_set(roots, (usize)pending_exception.cell(), gc.HeapRoot(type_ = gc.HeapRootType.vm))

    # gather_roots_from_execution_context_stack: each context's visit_edges, as roots.
    vm_gather_roots_from_execution_context_stack(&this.m_execution_context_stack, roots)

    for saved_stack in &ak.vector_span(&this.m_saved_execution_context_stacks):
        vm_gather_roots_from_execution_context_stack(saved_stack, roots)

    for job in ak.vector_span(&this.m_promise_jobs):
        gc.gc_hash_map_set(roots, (usize)job.cell(), gc.HeapRoot(type_ = gc.HeapRootType.vm))

## Ported from Libraries/LibJS/Runtime/VM.cpp:280 gather_roots_from_execution_context_stack (the
## lambda in JS::VM::gather_roots), for one stack.
func vm_gather_roots_from_execution_context_stack(stack: ak.Vector[JsExecutionContext*]*, roots: gc.GcHashMap[gc.HeapRoot]*):
    for execution_context in ak.vector_span(stack):
        if let function = execution_context.function:
            gc.gc_hash_map_set(roots, (usize)function, gc.HeapRoot(type_ = gc.HeapRootType.vm))
        if let realm = execution_context.realm:
            gc.gc_hash_map_set(roots, (usize)realm.cell(), gc.HeapRoot(type_ = gc.HeapRootType.vm))
        # The this value and the arguments of a call (added in region r19 for native functions).
        if let this_value = execution_context.this_value:
            vm_gather_value_root(roots, this_value)
        for argument in execution_context.arguments:
            vm_gather_value_root(roots, argument)

## A root for the cell a JS value holds, if it holds one.
func vm_gather_value_root(roots: gc.GcHashMap[gc.HeapRoot]*, value: JsValue):
    if gc.nan_boxed_value_is_cell(&value.nan_boxed_value):
        let cell = gc.nan_boxed_value_as_cell_const(&value.nan_boxed_value)
        gc.gc_hash_map_set(roots, (usize)cell, gc.HeapRoot(type_ = gc.HeapRootType.vm))

## Ported from Libraries/LibJS/Runtime/VM.h:68 JS::VM::heap.
pub func vm_heap(this: Vm*) -> gc.Heap*:
    return &this.m_heap

## Ported from Libraries/LibJS/Runtime/VM.h:412 JS::VM::agent.
pub func vm_agent(this: Vm*) -> HtmlAgent*?:
    return this.m_agent

## Ported from Libraries/LibJS/Runtime/VM.h:411 JS::VM::set_agent.
pub func vm_set_agent(this: Vm*, agent: HtmlAgent*):
    this.m_agent = agent

# mark: External roots (DESIGN.md §3.3 rule 4) ==================================================

## The vtable of the VM's external roots: a GC::ConservativeVector.
let js_vm_external_roots_vtable: gc.ConservativeVectorBaseVTable = gc.ConservativeVectorBaseVTable(class_info = &gc.conservative_vector_base_class, possible_values = js_vm_external_roots_possible_values_impl)

## The words the heap scans for the VM's external roots.
func js_vm_external_roots_possible_values_impl(base: gc.ConservativeVectorBase*) -> const u64[]:
    let this = (JsVmExternalRoots*)base
    return ak.vector_span_const(&this.values)

## Addition (DESIGN.md §3.3 rule 4): keep the managed memory `pointer` points into alive for as
## long as the VM lives. For managed memory that only memory outside the heap refers to (a
## module global, the C heap); a pointer to anything else is ignored by the scan.
pub func vm_keep_alive(this: Vm*, pointer: const void*):
    with memory.heap:
        ak.vector_append_t(&this.m_external_roots.values, (u64)(usize)pointer)

# mark: Promise jobs and the host hooks =========================================================

## The default host_make_job_callback (the lambda of VM.cpp:123): JS::make_job_callback.
func vm_default_make_job_callback(vm: Vm*, function_object: JsFunctionObject*) -> JsJobCallback*:
    return js_make_job_callback(function_object)

## The default host_promise_job_queue_is_empty (the lambda of VM.cpp:119).
func vm_promise_job_queue_is_empty(this: Vm*) -> bool:
    return ak.vector_is_empty(&this.m_promise_jobs)

## Ported from Libraries/LibJS/Runtime/VM.h:393 JS::VM::run_queued_promise_jobs.
pub func vm_run_queued_promise_jobs(this: Vm*):
    if ak.vector_is_empty(&this.m_promise_jobs):
        return
    vm_run_queued_promise_jobs_impl(this)

## Ported from Libraries/LibJS/Runtime/VM.cpp:460 JS::VM::run_queued_promise_jobs_impl.
func vm_run_queued_promise_jobs_impl(this: Vm*):
    while not ak.vector_is_empty(&this.m_promise_jobs):
        let job = ak.vector_take_first(&this.m_promise_jobs)
        _ = ak.function0_call(&job.function)

## Ported from Libraries/LibJS/Runtime/VM.cpp:473 JS::VM::enqueue_promise_job:
## 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
func vm_enqueue_promise_job(this: Vm*, job: JsPromiseJobFunction*, realm: Realm*?):
    # An implementation of HostEnqueuePromiseJob must conform to the requirements in 9.5 as well as the following:
    # - FIXME: If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.
    # - FIXME: Let scriptOrModule be GetActiveScriptOrModule() at the time HostEnqueuePromiseJob is invoked. If realm is not null, each time job is invoked the implementation must perform implementation-defined steps
    #          such that scriptOrModule is the active script or module at the time of job's invocation.
    # - Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
    with memory.heap:
        ak.vector_append_t(&this.m_promise_jobs, job)

## Ported from Libraries/LibJS/Runtime/VM.cpp:499 JS::VM::promise_rejection_tracker:
## 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
func vm_promise_rejection_tracker(this: Vm*, promise: JsPromise*, operation: JsPromiseRejectionOperation):
    match operation:
        .reject:
            # A promise was rejected without any handlers
            if let on_promise_unhandled_rejection = this.on_promise_unhandled_rejection:
                on_promise_unhandled_rejection(this, promise)
        .handle:
            # A handler was added to an already rejected promise
            if let on_promise_rejection_handled = this.on_promise_rejection_handled:
                on_promise_rejection_handled(this, promise)
        _:
            trap("VERIFY_NOT_REACHED")

## `vm.host_promise_rejection_tracker(promise, operation)`.
pub func vm_host_promise_rejection_tracker(this: Vm*, promise: JsPromise*, operation: JsPromiseRejectionOperation):
    let hook = this.host_promise_rejection_tracker else trap("VERIFY: host_promise_rejection_tracker")
    hook(this, promise, operation)

## `vm.host_call_job_callback(callback, this_value, arguments_list)`.
pub func vm_host_call_job_callback(this: Vm*, callback: JsJobCallback*, this_value: JsValue, arguments_list: const JsValue[]) -> JsValue!:
    let hook = this.host_call_job_callback else trap("VERIFY: host_call_job_callback")
    return try hook(this, callback, this_value, arguments_list)

## `vm.host_enqueue_promise_job(job, realm)`.
pub func vm_host_enqueue_promise_job(this: Vm*, job: JsPromiseJobFunction*, realm: Realm*?):
    let hook = this.host_enqueue_promise_job else trap("VERIFY: host_enqueue_promise_job")
    hook(this, job, realm)

## `vm.host_promise_job_queue_is_empty()`.
pub func vm_host_promise_job_queue_is_empty(this: Vm*) -> bool:
    let hook = this.host_promise_job_queue_is_empty else trap("VERIFY: host_promise_job_queue_is_empty")
    return hook(this)

## `vm.host_make_job_callback(callable)`.
pub func vm_host_make_job_callback(this: Vm*, callable: JsFunctionObject*) -> JsJobCallback*:
    let hook = this.host_make_job_callback else trap("VERIFY: host_make_job_callback")
    return hook(this, callable)

# mark: The execution context stack =============================================================

## Ported from Libraries/LibJS/Runtime/VM.h:221 JS::VM::push_execution_context. The stack's
## storage is on the C heap, as the VM; gather_roots reports what its contexts refer to. The
## running execution context is the top of the stack (the bytecode interpreter's caller frames
## and saved running contexts are phase 3).
pub func vm_push_execution_context(this: Vm*, context: JsExecutionContext*):
    with memory.heap:
        ak.vector_append_t(&this.m_execution_context_stack, context)

## Ported from Libraries/LibJS/Runtime/VM.h:232 JS::VM::pop_execution_context.
pub func vm_pop_execution_context(this: Vm*) -> JsExecutionContext*:
    assert(not ak.vector_is_empty(&this.m_execution_context_stack))
    return ak.vector_take_last(&this.m_execution_context_stack)

## Ported from Libraries/LibJS/Runtime/VM.h:247 JS::VM::running_execution_context.
pub func vm_running_execution_context(this: Vm*) -> JsExecutionContext*:
    assert(not ak.vector_is_empty(&this.m_execution_context_stack))
    return *ak.vector_last(&this.m_execution_context_stack)

## Ported from Libraries/LibJS/Runtime/VM.h:258 JS::VM::has_running_execution_context. The running
## execution context is the top of the stack (see vm_push_execution_context).
pub func vm_has_running_execution_context(this: Vm*) -> bool:
    return not ak.vector_is_empty(&this.m_execution_context_stack)

## Ported from Libraries/LibJS/Runtime/VM.cpp:532 JS::VM::save_execution_context_stack (added in
## region r21 for the HTML parser's microtask checkpoints). The saved stacks live on the C heap.
pub func vm_save_execution_context_stack(this: Vm*):
    with memory.heap:
        ak.vector_append_t(&this.m_saved_execution_context_stacks, this.m_execution_context_stack)
    this.m_execution_context_stack = ak.Vector[JsExecutionContext*]()

## Ported from Libraries/LibJS/Runtime/VM.cpp:542 JS::VM::clear_execution_context_stack.
pub func vm_clear_execution_context_stack(this: Vm*):
    ak.vector_clear_with_capacity(&this.m_execution_context_stack)

## Ported from Libraries/LibJS/Runtime/VM.cpp:549 JS::VM::restore_execution_context_stack.
pub func vm_restore_execution_context_stack(this: Vm*):
    let saved_stack = ak.vector_take_last(&this.m_saved_execution_context_stacks)
    this.m_execution_context_stack = saved_stack

## Ported from Libraries/LibJS/Runtime/VM.h:347 JS::VM::finish_execution_generation (added in region
## r29 for the microtask checkpoint's ClearKeptObjects()).
pub func vm_finish_execution_generation(this: Vm*):
    this.m_execution_generation +%= 1

## Ported from Libraries/LibJS/Runtime/VM.h:264 JS::VM::execution_context_stack.
pub func vm_execution_context_stack(this: Vm*) -> JsExecutionContext*[]:
    return ak.vector_span(&this.m_execution_context_stack)

## Ported from Libraries/LibJS/Runtime/VM.h:315 JS::VM::current_realm.
pub func vm_current_realm(this: Vm*) -> Realm*?:
    return vm_running_execution_context(this).realm

# mark: The pending exception (DESIGN.md §2.10) =================================================

## The VM's pending-exception cell (made with the VM).
func vm_pending_exception_cell(this: Vm*) -> JsPendingException*:
    return this.m_pending_exception else trap("the VM has no pending-exception cell")

## Addition (DESIGN.md §2.10): store `exception` as the VM's pending exception. A function
## returning `T!` calls this (through idl_throw or vm_throw_completion) right before failing.
pub func vm_set_pending_exception(this: Vm*, exception: IdlException):
    vm_pending_exception_cell(this).exception = exception

## Addition (DESIGN.md §2.10): whether an exception is pending.
pub func vm_has_pending_exception(this: Vm*) -> bool:
    return vm_pending_exception_cell(this).exception != none

## Addition (DESIGN.md §2.10): the pending exception, taken out of the VM. The caller of a
## failed `T!` (C++: `result.is_exception()` / `release_error()`) reads it here; it must be
## pending.
pub func vm_take_pending_exception(this: Vm*) -> IdlException:
    let cell = vm_pending_exception_cell(this)
    let exception = cell.exception else trap("no pending exception")
    cell.exception = none
    return exception

## The pending-exception cell's name.
func js_pending_exception_class_name_impl(this: gc.Cell*) -> ak.StringView:
    return ak.sv("PendingException")

## The pending-exception cell's edges: the DOMException it holds, or the value of a JS
## completion (a message String is a blob the cell's bytes point to, found by the conservative
## scan of the cell).
func js_pending_exception_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    gc.cell_visit_edges_impl(base, visitor)
    let this = (JsPendingException*)base
    if let exception = this.exception:
        match exception:
            .idl_dom_exception(dom_exception):
                gc.cell_visitor_visit_t_2(visitor, dom_exception)
            .js_completion(completion):
                js_visit_value(visitor, completion.m_value)
            _:
                return

## `vm.throw_completion<JS::ErrorType>(message)`: a JS error of a simple type thrown. Phase 1 has
## no JS Error objects, so the completion is represented by the WebIDL SimpleException that
## converts to it (Bindings::exception_to_throw_completion maps SimpleException{T, m} to exactly
## this call); phase 3 creates the Error object in luce-js. Fails with js_exception.
pub func vm_throw_completion(this: Vm*, type_: IdlSimpleExceptionType, message: ak.StringOrStringView) -> never!:
    vm_set_pending_exception(this, .idl_simple_exception(IdlSimpleException(type_ = type_, message = message)))
    error(js_exception, "")

# mark: JS::Cell ================================================================================

## Ported from Libraries/LibJS/Runtime/VM.h:583 JS::Cell::vm.
pub func js_cell_vm(this: JsCell*) -> Vm*:
    return vm_the()

## Ported from Libraries/LibJS/Heap/Cell.h:20 JS::Cell::initialize (virtual): nothing to do.
## (JS::Object::initialize, which PlatformObject inherits, only calls this.)
pub func js_cell_initialize_impl(this: JsCell*, arg0: Realm*):
    return

## Ported from Libraries/LibJS/Heap/Cell.h:22 JS::Cell::is_environment (virtual).
pub func js_cell_is_environment_impl(this: JsCell*) -> bool:
    return false

## `visitor.visit(GC::Ptr<JS::Object>)`: a JS object field visited. Before phase 3 the only
## objects LibWeb holds as JS::Object are cells (platform objects such as the Window), so the
## pointer is visited as a cell; phase 3 routes luce-js values through visit_js_value.
pub func js_visit_object(visitor: gc.CellVisitor*, object: JsObject*?):
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)object)

# mark: JS::Value ===============================================================================

## LibJS's UNDEFINED_TAG (Libraries/LibJS/Runtime/Value.h:52).
let js_undefined_tag: u64 = 0b110 | gc.base_tag

## LibJS's NULL_TAG (Libraries/LibJS/Runtime/Value.h:53).
let js_null_tag: u64 = 0b111 | gc.base_tag

## A value of the given encoding (GC::NanBoxedValue's union, built through its `encoded` member).
func js_value_from_encoded(encoded: u64) -> JsValue:
    var result = JsValue()
    result.nan_boxed_value.m_value.encoded = encoded
    return result

## Ported from Libraries/LibJS/Runtime/Value.h:530 JS::js_undefined.
pub func js_undefined() -> JsValue:
    return js_value_from_encoded(js_undefined_tag << gc.tag_shift)

## Ported from Libraries/LibJS/Runtime/Value.h:535 JS::js_null.
pub func js_null() -> JsValue:
    return js_value_from_encoded(js_null_tag << gc.tag_shift)

## Ported from Libraries/LibJS/Runtime/Value.h:100 JS::Value::is_undefined.
pub func js_value_is_undefined(this: JsValue) -> bool:
    return this.nan_boxed_value.m_value.encoded == js_undefined_tag << gc.tag_shift

## LibJS's BOOLEAN_TAG (Libraries/LibJS/Runtime/Value.h:54).
let js_boolean_tag: u64 = 0b001 | gc.base_tag

## LibJS's INT32_TAG (Libraries/LibJS/Runtime/Value.h:55).
let js_int32_tag: u64 = 0b010 | gc.base_tag

## Ported from Libraries/LibJS/Runtime/Value.h:209 JS::Value::Value(bool).
pub func js_value_from_bool(value: bool) -> JsValue:
    return js_value_from_encoded((js_boolean_tag << gc.tag_shift) | (1 if value else 0))

## Ported from Libraries/LibJS/Runtime/Value.h:221 JS::Value::Value(double): an integral value in
## the i32 range (but not -0) is stored as an int32, NaN as the canonical NaN.
pub func js_value_from_f64(value: f64) -> JsValue:
    let is_negative_zero = value == 0.0 and math.signbit(value)
    if value >= -2147483648.0 and value <= 2147483647.0 and math.trunc(value) == value and not is_negative_zero:
        return js_value_from_encoded((js_int32_tag << gc.tag_shift) | ((u64)(u32)(i32)value))
    if math.is_nan(value):
        return js_value_from_encoded(gc.canon_nan_bits)
    var result = JsValue()
    result.nan_boxed_value.m_value.as_double = value
    return result

## The 16-bit tag of a value (JS::Value::tag, Value.h:96).
func js_value_tag(this: JsValue) -> u64:
    return this.nan_boxed_value.m_value.encoded >> gc.tag_shift

## Ported from Libraries/LibJS/Runtime/Value.h:448 JS::Value::is_double.
pub func js_value_is_double(this: JsValue) -> bool:
    let encoded = this.nan_boxed_value.m_value.encoded
    return (encoded & gc.canon_nan_bits) != gc.canon_nan_bits or encoded == gc.canon_nan_bits

## Ported from Libraries/LibJS/Runtime/Value.h:449 JS::Value::is_int32.
pub func js_value_is_int32(this: JsValue) -> bool:
    return js_value_tag(this) == js_int32_tag

## Ported from Libraries/LibJS/Runtime/Value.h:102 JS::Value::is_number.
pub func js_value_is_number(this: JsValue) -> bool:
    return js_value_is_double(this) or js_value_is_int32(this)

## LibJS's OBJECT_TAG (Libraries/LibJS/Runtime/Value.h:36).
let js_object_tag: u64 = 0b001 | gc.is_cell_bit

## Ported from Libraries/LibJS/Runtime/Value.h:104 JS::Value::is_object.
pub func js_value_is_object(this: JsValue) -> bool:
    return js_value_tag(this) == js_object_tag

## Ported from Libraries/LibJS/Runtime/Value.h:105 JS::Value::is_boolean.
pub func js_value_is_boolean(this: JsValue) -> bool:
    return js_value_tag(this) == js_boolean_tag

## Ported from Libraries/LibJS/Runtime/Value.h:330 JS::Value::as_double.
pub func js_value_as_double(this: JsValue) -> f64:
    assert(js_value_is_number(this))
    if js_value_is_int32(this):
        return (f64)(i32)(u32)(this.nan_boxed_value.m_value.encoded & 0xFFFFFFFF)
    return this.nan_boxed_value.m_value.as_double

## Ported from Libraries/LibJS/Runtime/Value.h:101 JS::Value::is_null.
pub func js_value_is_null(this: JsValue) -> bool:
    return this.nan_boxed_value.m_value.encoded == js_null_tag << gc.tag_shift

## LibJS's IS_NULLISH_EXTRACT_PATTERN and IS_NULLISH_PATTERN (Libraries/LibJS/Runtime/Value.h:60).
let js_is_nullish_extract_pattern: u64 = 0xFFFE
let js_is_nullish_pattern: u64 = 0x7FFE

## Ported from Libraries/LibJS/Runtime/Value.h:109 JS::Value::is_nullish.
pub func js_value_is_nullish(this: JsValue) -> bool:
    return (js_value_tag(this) & js_is_nullish_extract_pattern) == js_is_nullish_pattern

## Ported from Libraries/LibJS/Runtime/Value.h:338 JS::Value::as_bool.
pub func js_value_as_bool(this: JsValue) -> bool:
    assert(js_value_is_boolean(this))
    return (this.nan_boxed_value.m_value.encoded & 1) != 0

## Ported from Libraries/LibJS/Runtime/Value.h:275 JS::Value::Value(Object const*) (and the
## tagged-pointer constructor of Value.h:492): an object value, or null for no object. Before
## phase 3 the JS objects LibWeb meets are cells (platform objects, native functions; DESIGN.md
## §3.6), so the value holds the cell itself, as LibJS's does; phase 3 maps a platform object to
## its wrapper here.
pub func js_value_from_object(object: JsObject*?) -> JsValue:
    let pointer = object else return js_null()
    return js_value_from_encoded((js_object_tag << gc.tag_shift) | ((u64)(usize)pointer & 0x0000ffffffffffff))

## Ported from Libraries/LibJS/Runtime/Value.h:344 JS::Value::as_object.
pub func js_value_as_object(this: JsValue) -> JsObject*:
    assert(js_value_is_object(this))
    return (JsObject*)gc.nan_boxed_value_as_cell_const(&this.nan_boxed_value)

## `visitor.visit(JS::Value)`: GC::Cell::Visitor::visit(NanBoxedValue), which visits the cell a
## value holds.
pub func js_visit_value(visitor: gc.CellVisitor*, value: JsValue):
    gc.cell_visitor_visit_nan_boxed_value(visitor, value.nan_boxed_value)

## Ported from Libraries/LibJS/Runtime/Value.cpp:779 JS::Value::to_number (to_number_slow_case):
## 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber. Strings, objects, symbols
## and BigInts are JS cells (phase 3).
pub func js_value_to_number(vm: Vm*, this: JsValue) -> JsValue!:
    # 1. If argument is a Number, return argument.
    if js_value_is_number(this):
        return this

    let tag = js_value_tag(this)
    # 3. If argument is undefined, return NaN.
    if tag == js_undefined_tag:
        return js_value_from_f64(math.nan)
    # 4. If argument is either null or false, return +0𝔽.
    if tag == js_null_tag:
        return js_value_from_f64(0.0)
    # 5. If argument is true, return 1𝔽.
    if tag == js_boolean_tag:
        return js_value_from_f64(1.0 if (this.nan_boxed_value.m_value.encoded & 1) != 0 else 0.0)
    # 2. If argument is either a Symbol or a BigInt, throw a TypeError exception.
    # 6. If argument is a String, return StringToNumber(argument).
    # 7.-10. Otherwise argument is an Object: ? ToNumber(? ToPrimitive(argument, number)).
    trap("unported (P3): JS::Value::to_number of a string, symbol, BigInt or object")