Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / docs / regions / r38.md

# Region r38: CSS selectors and the selector engine — what other regions need to know

Region r38 ports `CSS/PageSelector.cpp/.h`, `CSS/PseudoClassBitmap.h`, `CSS/Selector.cpp/.h` and
`CSS/SelectorEngine.cpp/.h` (the PseudoClass / PseudoElement data is css_data's, generated by
r12). The stub fragment `stubs/stub_r38_selectors.lucb` is gone; every one of its functions is
ported, plus the members of `Selector.h` the skeleton did not emit (below).

## Fragments

| Fragment | Donor |
| --- | --- |
| `css/page_selector` | `PageSelector.cpp` + `.h` |
| `css/pseudo_class_bitmap` | `PseudoClassBitmap.h` |
| `css/selector_1` | `Selector.h`'s inline members; `Selector.cpp` 1-332: construction, ancestor hashes, specificity |
| `css/selector_2` | `Selector.cpp` 334-979: serialization, `relative_to`, `absolutized`, the sibling invalidation distance, `adapt_nested_relative_selector_list`, `ANPlusBPattern` |
| `css/selector_engine_1` | `SelectorEngine.h`'s inline members; `SelectorEngine.cpp` 1-555: the :has() fast paths and cache, `traverse_up`, :lang(), relative selectors, attributes |
| `css/selector_engine_2` | 557-1078: sibling walks, the shadow-host block, :read-write, :open, :host, the meter states, `matches_pseudo_class` |
| `css/selector_engine_3` | 1079-1476: the rest of `matches_pseudo_class`'s switch (`matches_pseudo_class_forms`), `matches_namespace`, `matches_simple_selector` |
| `css/selector_engine_4` | 1478-1783: `matches_compound_selector`, `matches`, the fast path |
| `css/tests_selector_cases`, `tests_selector`, `tests_selector_engine_cases`, `tests_selector_engine` | tests (Ladybird has none for these files) |

## What other regions must know

### Selectors are blobs, passed by pointer

- A `CSS::Selector` (ref-counted in C++) is a managed blob made by `css_selector_create(compounds)`
  (`new`), handled as `CssSelector*`. The two C++ `mutable` caches (`m_specificity`,
  `m_sibling_invalidation_distance`) are written through a cast of the const receiver.
- **`Selector const&` is `const CssSelector*`** in every r38 function (DESIGN §2.2: const stays on
  value types passed by pointer). The :has() result cache keys on the selector's *address*
  (`HasResultCacheKey { &selector, &anchor }`), so a by-value `CssSelector` (as the generated
  stubs had it) would give every argument selector the same stack address. **r39, r42**: your
  stubs that take `selector: CssSelector` (`should_reject_with_ancestor_filter`,
  `collect_selector_insights`, `build_invalidation_sets_for_selector`, …) should do the same when
  ported; call r38 with the `CssSelector*` you hold.
- The other `const&` value types of the private engine functions (SimpleSelector,
  CompoundSelector, PseudoClassSelector, Attribute, QualifiedName) are `const T*`.
  `AbstractElement const&` stays by value (three words), as generated.

### New functions (namemap rows added, kind `function`)

- SimpleSelector's accessors: `css_selector_simple_selector_attribute`, `_pseudo_class`,
  `_pseudo_element`, `_name`, `_lowercase_name`, `_qualified_name` (each traps, as `Variant::get`
  VERIFYs, on another alternative; they return copies). r31 had a private
  `css_selector_simple_selector_pseudo_element` in `selector_parsing_1`; it is now r38's (public).
- `css_selector_simple_selector_serialize`, `css_selector_simple_selector_absolutized`,
  `css_selector_simple_selector_an_plus_b_pattern_matches` / `_serialize`.
- `selector_engine_has_result_cache_key_eq` (the defaulted `operator==`);
  `SelectorEngineHasResultCacheKeyTraits` (types file) forwards to it and to the ported hash.
- Closure stub `html_custom_state_set_has_state` (`stubs/stub_closure.lucb`, P3 trap: the states
  set is a JS::Set; no element has one before then, so `:state()` answers false).

### Signatures changed from the stubs

- `selector_engine_matches(selector: const CssSelector*, …)` and `selector_engine_fast_matches`;
  r15's `dom_scope_match_a_selectors_string` and r16's `Element::matches` / `closest` now pass
  the pointer (call sites edited).
- `css_selector_pseudo_element_selector_compound_selector -> CssSelector*` (was `CssSelector`, a
  copy of the `NonnullRefPtr<Selector>` target).
- The PseudoElementSelector constructors take `value` with C++'s default (`.empty`).
- Private (C++ `static`): `css_component_value_contains_nesting_selector` (takes
  `const ComponentValue*`), `css_can_selector_use_fast_matches`, `css_contains_invalid_contents_for_has`,
  `css_selector_collect_ancestor_hashes`, and every SelectorEngine function except `matches` and
  `fast_matches`.

### Types filled by hand

- `types_pseudo_class_bitmap`: `css_pseudo_class_bitmap_word_count` is a `let` with C++'s
  initializer (`(PseudoClass::__Count + 63) / 64` = 2; a module assert ties it to `m_bits: u64[2]`).
- `types_selector_engine`: `HasResultCacheKeyTraits::hash_of` / `equals` forward to the ported code.

### Cross-region fills (functions that trapped waiting for r38)

- r13's `dump_selector` / `dump_qualified_name` (`dump_2`) are complete.
- r17's `contains_named_namespace` (`dom/document_15`, used by `parse_or_cache_selector_list`)
  is complete, so `querySelector(All)`, `matches` and `closest` run end to end.

### Where matching stops (other regions' stubs)

- `:heading(n)` needs `HTMLHeadingElement::heading_level` (r27); `:modal` `HTMLDialogElement::is_modal`
  (r26); `:indeterminate`, `:read-write`, `:required`, `:optional`, `:default`, `:user-valid`,
  `:user-invalid` and `:open` on inputs reach r24's `HTMLInputElement` stubs; on select / textarea
  r25's; media pseudo-classes r27's `HTMLMediaElement`; meter states r25's.
- Namespaced type/attribute selectors with a style sheet (`style_sheet_for_rule`) reach r37's
  `CSSStyleSheet::namespace_uri` / `default_namespace_rule`.
- Building trees with the DOM's own entry points still traps in r42's style invalidation, and
  most HTML element constructors are r26/r27 stubs: the tests build trees by hand (below).

## Deviations and notes

- `matches_pseudo_class` (one 680-line C++ switch) is split: its cases from `:valid` on are
  `matches_pseudo_class_forms` (selector_engine_3), called from the switch, each case unchanged.
- The C++ lambdas are private functions named after their enclosing function (capture structs
  where they capture: `CssSelectorSpecificityCounts`, `SelectorEngineMatchesAttributeMatch`);
  `ScopeGuard`s are `defer`s; `fast_matches`' `backtrack_state` struct is two locals.
- `is_one_of` over the 46 case-insensitive HTML attribute names is a local array of the
  interned names.
- `language_range_matches_tag` walks the split vectors by index (C++ iterators).
- Donor behavior kept and pinned by a test: the fast path's descendant walk does not stop at a
  shadow host (`parent_element()`), where the full matcher's `traverse_up` does.

## Tests

- `tests_selector_cases` (105 cases) + `tests_selector`: a local oracle
  (`luce-browser-tools/oracles/luce-browser-engine/selector_engine`: `selectors.cpp` links the
  reference build's LibWeb objects as r31's, `selector_cases.txt`, `build.sh`,
  `gen_selector_cases.py`) runs `parse_selector` and prints, per selector, serialize, specificity
  (incl. the 255 clamp), the fast-match / ancestor-filter flags and the ancestor hashes, the
  sibling invalidation distance, the nesting / webkit / slotted / part flags, the target
  pseudo-element, the contained pseudo-classes and `dump_selector`; nested selectors
  (`adapt_nested_relative_selector_list`) absolutized against `:is(.p, #q)` and `:has(.y)` (the
  invalid-contents error); An+B patterns; @page selector lists; the ErrorReporter's errors.
  Focused tests: PseudoClassBitmap, PageSelector, PseudoElementSelector, `relative_to` and the
  caches.
- `tests_selector_engine_cases` (13 trees, 231 queries) + `tests_selector_engine`: the matching
  oracle (`gen_matching.py`, `matching_cases.txt`) runs a Text test through the reference build's
  `test-web --rebaseline` and records `querySelectorAll` results; the Luce test builds each tree
  by hand in a document shaped as the reference's (HTMLElement's constructor for each element,
  with the element classes `:root`, `:heading` and `:open` tell apart; the attribute list with
  id/class applied as `attribute_changed` does; raw tree insertion) and runs each query through
  the port's `ParentNode::querySelectorAll`. Covered: type/universal/id/class, every attribute
  match and case type (and the HTML case-insensitive attributes), first/last/only child and of
  type, :nth-*() with An+B and `of S`, :empty, :root, :scope, all combinators, :not/:is/:where,
  :has with every relative combinator, :lang ranges and inheritance, :defined, :open, the
  state pseudo-classes that are false in a static document, pseudo-elements, invalid and
  namespaced selectors. Focused tests pin the :has() result cache and its counters, the
  per-element involvement metadata, fast path vs full matcher (with backtracking), shadow hosts,
  pseudo-element targets, quirks-mode classes and RFC 4647 language ranges.

## Compiler issues

None found.