Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / docs / regions / r15.md

# Region r15: DOM Node, ParentNode, ChildNode and the node operations — what other regions need to know

Region r15 ports `DOM::Node` (the tree algorithms of the DOM standard: insert, pre-insert,
append, remove, replace, move, clone, normalize, textContent, nodeValue, compareDocumentPosition,
isEqualNode, the namespace lookups, mutation records, the dirty flags and layout links, the
accessible name computation), `DOM::ParentNode`, the `ChildNode` and `NonDocumentTypeChildNode`
mixins and `NodeOperations` (`convert_nodes_to_single_node`). The stub fragment
`stubs/stub_r15_dom_node.lucb` is gone; every one of its 271 functions is ported. Each fragment's
header says what it holds and which donor lines it came from.

| Fragment | Donor |
| --- | --- |
| `dom/child_node` | `ChildNode.h` |
| `dom/node_1` | `Node.cpp` 81-566: unique ids, constructors, finalize/visit_edges, textContent, normalize, nodeValue, style scopes, shadow-including root, ensure-pre-insertion-validity |
| `dom/node_2` | `Node.cpp` 568-986: insert, pre-insert, append, pre-remove, live-range pre-remove, remove |
| `dom/node_3` | `Node.cpp` 987-1356: replace, clone, move |
| `dom/node_4` | `Node.cpp` 1357-1885: clone a single node, cloneNode, set_document, editing, layout links, get-the-parent, dirty flags, inserted/removed_from/moved_from, parents and flat-tree parents, childNodes |
| `dom/node_5` | `Node.cpp` 1886-2349: compareDocumentPosition, host-/shadow-including relations, ownerDocument, the JSON dump, scripting, replace all, serialize_fragment, unsafely_set_html, isSameNode/isEqualNode |
| `dom/node_6` | `Node.cpp` 2350-2833: namespaces, inertness, getRootNode, debug_description, length, layout-node/paintable accessors, (tree) mutation records, the child-list primitives |
| `dom/node_7` | `Node.cpp` 2834-3311: build_accessibility_tree, name_or_description |
| `dom/node_8` | `Node.cpp` 3312-3404 and the inline functions of `Node.h` |
| `dom/node_operations` | `NodeOperations.cpp` |
| `dom/non_document_type_child_node` | `NonDocumentTypeChildNode.h` |
| `dom/parent_node` | `ParentNode.cpp`, `ParentNode.h` |
| `dom/tests_node` | 26 focused tests (Ladybird has no unit tests for these files) |

`NodeType.h` is only the `DomNodeType` enum the skeleton already generated.

## Conventions other regions will meet

- **Throwing a WebIDL exception.** `support.lucb` gains `idl_throw(exception: IdlException) ->
  never!`, which stores the exception in `idl_pending_exception` and fails with
  `webidl_exception` (DESIGN.md §2.10). `return WebIDL::HierarchyRequestError::create(realm, "…"_utf16);`
  is `return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("…"))))`.
  The slot is a module `var` until region r14 gives `Vm` its pending-exception field; it holds a
  cell pointer outside the heap, so it must be taken before the next collection (r14 should root it).
- **TreeNode calls** go through the r13 functions on the embedded `tree_node`
  (`tree_node_parent(&node.tree_node)`, `tree_node_root(&node.tree_node)`, …). Plain
  `for_each_child` / `for_each_in_(inclusive_)subtree(_of_type)` walks are loops over the generated
  `dom_node_children` / `dom_node_subtree` / `dom_node_inclusive_subtree` iterators (DESIGN.md §2.9);
  `for_each_ancestor` is a `tree_node_parent` loop.
- **Lambdas** are a private function plus a capture struct named after the enclosing function
  (`DomNodeRemoveDescendantSteps`, …), passed as `ak.Function1[…](call = …, context = &captures)`;
  the escaping HTMLCollection filters allocate their captures with `new` (DESIGN.md §2.7).
- `Vector<GC::Root<Node>>` is `ak.Vector[DomNode*?]` throughout (as the skeleton chose).
- AK `Optional` comparisons have small private helpers (`dom_node_optional_fly_strings_equal`,
  `dom_node_optional_string_is`, …) since `ak.String`/`ak.FlyString` have no `==`.
- `s_node_directory` (the unique-id → node map) is updated under `with memory.heap:`: it is a
  C++ static on the C heap, so its storage stays out of the (unscanned-global) managed heap and its
  entries do not keep nodes alive (DESIGN.md §3.3 rule 4).
- `module.lucb` now imports `memory` and `web_infra` (the latter for `Infra::is_ascii_whitespace`).

## Signature and type changes

### This region's own functions (against the generated stubs)

- **ChildNode / NonDocumentTypeChildNode** are stateless CRTP helpers whose bodies only use
  `Node`, so they are functions on `Node` (DESIGN.md §2.5): `dom_child_node_before(this: DomNode*,
  nodes)`, `…_after`, `…_replace_with`, `…_remove_binding`, `…_viable_previous/next_sibling_for_insertion`;
  `dom_non_document_type_child_node_previous_element_sibling(this: DomNode*)` and the other seven.
  Element, CharacterData and DocumentType pass `x.dom_node()`. The generic `DomChildNode[T]` and
  `DomNonDocumentTypeChildNode[T]` structs of the types fragments are now unused.
- Templates over a class take a `ClassInfo` (DESIGN.md §2.4) and answer the root class:
  `dom_node_first_flat_tree_ancestor_of_type(this, class_info) -> DomNode*?` (and `_const`).
- Template callbacks: `dom_node_for_each_child_of_type_fallible(this, class_info, callback:
  func(void*?, DomNode*) -> ak.IterationDecision!, context: void*?) -> !` (a fallible callback
  cannot be an `ak.Function1` type argument); `dom_node_find_in_shadow_including_ancestry(this,
  predicate: ak.Function1[DomNode*, bool])`; `dom_parent_node_for_each_child(_const)(this,
  callback: ak.Function1[DomNode*, ak.IterationDecision])`.
- `dom_node_style_scope_const(this) -> CssStyleScope*` (was `CssStyleScope` by value; C++ `const&`).
- Unchanged but worth knowing: `dom_node_set_document_document` / `…_named_node_map` are the two
  Badge overloads, `dom_node_set_document_dom_document` the protected one; the Badge parameters of
  `set_layout_node`, `clear_layout_node_and_paintable`, `detach_layout_node` are gone.

### Types filled in `dom/types_node.lucb`

- `DomNodeChildrenChangedMetadata` (was opaque) is `{ type_: DomNodeChildrenChangedMetadataType,
  node: DomNode* }`, with the new enum `DomNodeChildrenChangedMetadataType` (`inserted`, `removal`,
  `mutation`). Regions overriding `children_changed` read `metadata.type_` / `metadata.node`.
- New `DomNodeDocumentPosition as u16` (`Node::DocumentPosition`); `compare_document_position`
  still answers `u16`.

### Other regions' stubs (signatures only, bodies untouched)

- **r13 TreeNode** (`stubs/stub_r13_top_level.lucb`): the `TreeNode const&` parameters, generated
  as `other: TreeNode[u8]`, are `other: const TreeNode[T]*` (`is_ancestor_of`,
  `is_inclusive_ancestor_of`, `is_descendant_of`, `is_inclusive_descendant_of`, `is_following`,
  `is_before`, `is_parent_of`); the `template<typename U>` queries take a `class_info: const
  ak.ClassInfo*` instead of `U` and answer `T*?` (`has_child_of_type`,
  `has_preceding/following_node_of_type_in_tree_order`, `first/last_child_of_type` and their
  `_const`, `first_ancestor_of_type` and `_const`). Callers write
  `tree_node_has_child_of_type(&node.tree_node, &dom_element_class)`. r13 must keep these shapes
  (or adjust r15's call sites when merging).
- **r17** `dom_document_for_each_node_iterator(this, callback: ak.Function1[DomNodeIterator*, unit])`.
- **r18** `dom_node_for_each_shadow_including_inclusive_descendant(this, callback:
  ak.Function1[DomNode*, TraversalDecision]) -> TraversalDecision` and
  `dom_node_for_each_shadow_including_descendant` likewise (the generic `TCallback` could not be
  called).
- **Outside the phase-1 closure** (added to `stubs/stub_closure.lucb` with trap bodies and to
  `docs/namemap.tsv`): `html_custom_element_registry_is_scoped`,
  `html_custom_element_registry_append_scoped_document`, `html_is_a_global_custom_element_registry`,
  `html_serialize_node_to_xml_string`, and the FlyString variables
  `html_custom_element_reaction_names_{connected,disconnected,connected_move}_callback`
  (zero until whoever ports CustomElementReactionNames interns them). Note that every insertion of
  an element with a custom element registry calls `is_scoped`, so the CustomElementRegistry
  accessors are needed as soon as documents get registries.

## Deviations and notes

- `HTML::relevant_similar_origin_window_agent(*this)` takes `JS::Object&`; with `JsObject` opaque
  until phase 3 the node is passed as `(JsObject*)this` (DESIGN.md §3.6). r29 should retype the
  `relevant_*` functions to take a platform object.
- `Node::queue_mutation_record`'s `DeferGC` uses `gc.cell_heap(this.cell())`.
- `Node::is_equal_node`'s `switch (node_type())` is an if-chain over `DomNodeType` (its `default:`
  is empty); compare_document_position's empty `if` (a FIXME) is kept as comments only.
- `ensure_pre_insertion_validity` and `replace_child` evaluate a few pure `has_*_of_type` queries
  before the `||` that would have short-circuited them; the results are the same.
- `Node::set_needs_layout_tree_update`'s `UPDATE_LAYOUT_DEBUG` block is ported behind the private
  `update_layout_debug` constant (0 in the reference build).

## Tests

`dom/tests_node.lucb` (26 tests, run by `./test.sh`, which now runs `luce-base test` on `web`)
builds nodes by hand (zeroed cells with vtable, class id, type and document) because constructing
cells needs r14's heap and realm, and writes the tree links directly because TreeNode is r13. They
pin: the NodeType values and type predicates, the default virtual answers, the unique-id directory
and finalize, ownerDocument, isSameNode/isEqualNode/compareDocumentPosition on the node itself,
connection and dirty flags (including `set_needs_style_update_internal` setting the flag whatever
its argument), layout-node and paintable links, the removing steps, textContent/nodeValue of
documents and doctypes, descendant text content and normalize without Text, length, the namespace
lookups of doctypes and fragments, children_as_vector, getElementById without elements, registered
observers, as_slottable, the ParentNode flag, find_in_shadow_including_ancestry, converting one
node, and ChildNode's nodes-contain check.

Once r13 (TreeNode), r14 (cell creation and DOMExceptions), r16-r18 (Element, Document,
CharacterData, ShadowRoot) land, the tree algorithms (append/insert/remove/replace/move, the
pre-insertion validity errors, compareDocumentPosition across a tree, normalize, cloning,
getElementById with elements, the ChildNode/ParentNode convenience methods) should get scenario
tests pinned to the reference build.