Skip to content

Truly independent web browser

LibWeb: Skip the :has() walks of subtrees that carry no wanted key

Andreas Kling553adfa5c0a7
diff --git a/Documentation/Style/StyleEngine.md b/Documentation/Style/StyleEngine.md
index 49e14a65978..ed5d0feca71 100644
--- a/Documentation/Style/StyleEngine.md
+++ b/Documentation/Style/StyleEngine.md
@@ -57,7 +57,8 @@ After a document's first pass, each style update restyles only what its inputs c
**Invalidation** (`invalidation.rs`) maps every fact a compound tests to where that compound stands in its selector. A changed
element restyles itself where the fact is the subject's, and otherwise follows the combinators to the elements that can match.
A walk down the tree skips a subtree whose summary lacks the class or attribute name of each compound the walk looks for.
-`:has()` compounds find their anchors through their own queries. Reads that carry no structure, such as the selectors of an
+`:has()` compounds find their anchors through their own queries, and the walk that answers a `:has()` skips the subtrees
+whose summary lacks a name its argument requires. Reads that carry no structure, such as the selectors of an
`of` or the bounds of a `@scope`, restyle coarsely.
A restyled element's children restyle only where what they inherit changed. Custom properties move without a restyle
diff --git a/Libraries/LibWeb/Rust/src/css/selector_arena.rs b/Libraries/LibWeb/Rust/src/css/selector_arena.rs
index 167256f3a6d..073a2de3000 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_arena.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_arena.rs
@@ -502,6 +502,95 @@ pub(crate) struct SelectorArena {
_leases: AtomLeases,
}
+/// The classes and attribute names the elements a relative selector is matched by carry, as their bits in the Bloom
+/// summary of the keys a subtree carries: what a walk for the selector's witnesses asks the summaries for, to skip
+/// the subtrees that hold none.
+///
+/// The implicit anchor a relative selector ends in says where `numbers` holds them, and whether a class among them is
+/// not written in ASCII lowercase: one more than the index of the two, shifted over that flag, or zero for none.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct RelativeSubtreeKeys {
+ /// Those of every compound of the selector. The compounds match elements the leading combinator reaches from the
+ /// anchor, and elements below or beside those: all of them stand below the anchor, or below its parent where
+ /// the leading combinator is a sibling one.
+ pub(crate) chain: u64,
+ /// Those of the subject compound alone, which a witness itself carries.
+ pub(crate) subject: u64,
+}
+
+impl RelativeSubtreeKeys {
+ /// What the witnesses of the relative selector `selector` carry, and whether a class among it is not written in
+ /// ASCII lowercase: a document that folds its classes carries that one folded, under other bits.
+ fn of(selector: Selector<'_>) -> (Self, bool) {
+ let mut keys = Self::default();
+ let mut folds = false;
+ let mut current = selector;
+ loop {
+ if current.is_relative_anchor() {
+ return (keys, folds);
+ }
+ let (own, compound_folds) = Self::of_compound(&current.first_compound());
+ if current.at == selector.at {
+ keys.subject = own;
+ }
+ keys.chain |= own;
+ folds |= compound_folds;
+ match current.left() {
+ Some((
+ Combinator::Descendant
+ | Combinator::ImmediateChild
+ | Combinator::NextSibling
+ | Combinator::SubsequentSibling,
+ left,
+ )) => current = left,
+ _ => return (Self::default(), false),
+ }
+ }
+ }
+
+ /// The bits of the classes and attribute names every element matching `compound` carries, and whether a class
+ /// among them is not written in ASCII lowercase.
+ fn of_compound(compound: &CompoundRef<'_>) -> (u64, bool) {
+ use crate::css::style::index::{DispatchKey, subtree_key_bits};
+ let (mut keys, mut folds) = (0, false);
+ for simple in compound.simple_selectors.iter() {
+ match simple {
+ SimpleSelector::Class(name) => {
+ keys |= subtree_key_bits(DispatchKey::Class(name.name)).unwrap_or(0);
+ folds |= !name.is_ascii_lowercase;
+ }
+ // NB: An attribute written in ASCII lowercase in no namespace is carried under that name by every
+ // element matching it, as one of the name forms of the attribute it holds.
+ SimpleSelector::Attribute(attribute)
+ if attribute.qualified_name.name_is_ascii_lowercase
+ && matches!(
+ attribute.qualified_name.namespace_type,
+ NamespaceType::Default | NamespaceType::None
+ ) =>
+ {
+ keys |= subtree_key_bits(DispatchKey::AttributeName(attribute.qualified_name.name)).unwrap_or(0);
+ }
+ // NB: An element matches whichever alternative it carries the keys of, so it carries the bits all
+ // of them share. Only the subject of an alternative is the element: a compound left of a
+ // combinator is an ancestor's or a sibling's, which can stand anywhere.
+ SimpleSelector::PseudoClass(pseudo_class)
+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Is | PseudoClassType::Where) =>
+ {
+ let mut shared: Option<u64> = None;
+ for alternative in pseudo_class.argument_selector_list.iter() {
+ let (own, alternative_folds) = Self::of_compound(&alternative.first_compound());
+ shared = Some(shared.map_or(own, |shared| shared & own));
+ folds |= alternative_folds;
+ }
+ keys |= shared.unwrap_or(0);
+ }
+ _ => {}
+ }
+ }
+ (keys, folds)
+ }
+}
+
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<SelectorArena>();
@@ -1044,6 +1133,23 @@ impl<'a> Selector<'a> {
.map(|shape| (self.arena.serial, shape))
}
+ /// What the witnesses of the selector, a relative one, carry, for a document that does or does not fold its
+ /// classes as `folds_classes` says, or none where they are known to carry nothing.
+ #[must_use]
+ pub(crate) fn relative_subtree_keys(self, folds_classes: bool) -> Option<RelativeSubtreeKeys> {
+ let anchor = std::iter::successors(Some(self), |current| current.left().map(|(_, left)| left))
+ .find(|current| current.is_relative_anchor())?;
+ let noted = self.arena.components[anchor.at.0 as usize].data;
+ if noted == 0 || (folds_classes && noted & 1 != 0) {
+ return None;
+ }
+ let at = (noted >> 1) as usize - 1;
+ Some(RelativeSubtreeKeys {
+ chain: self.arena.numbers[at].cast_unsigned(),
+ subject: self.arena.numbers[at + 1].cast_unsigned(),
+ })
+ }
+
/// What tells the selector from any other of the process, for as long as the process lives.
#[must_use]
pub(crate) fn identity(self) -> (SelectorArenaSerial, ComponentOffset) {
@@ -2337,6 +2443,40 @@ impl SelectorArena {
}
self.mark_compound_lengths();
self.note_compound_facts();
+ self.note_relative_subtree_keys();
+ }
+
+ /// Note what the witnesses of each relative selector carry on the anchor it ends in, as [`RelativeSubtreeKeys`]
+ /// says.
+ fn note_relative_subtree_keys(&mut self) {
+ let mut noted = Vec::new();
+ let mut start = 0;
+ for index in 0..self.components.len() {
+ if self.components[index].bits.relation() != Relation::Leftmost {
+ continue;
+ }
+ // NB: The implicit anchor is a compound of one component.
+ if index > start && self.components[index].bits.kind() == ComponentKind::RelativeAnchor {
+ let (keys, folds) = RelativeSubtreeKeys::of(Selector {
+ arena: self,
+ at: ComponentOffset(index_u32(start)),
+ });
+ if keys.chain != 0 {
+ noted.push((index, keys, folds));
+ }
+ }
+ start = index + 1;
+ }
+ if noted.is_empty() {
+ return;
+ }
+ let mut numbers = std::mem::take(&mut self.numbers).into_vec();
+ numbers.reserve_exact(noted.len() * 2);
+ for (anchor, keys, folds) in noted {
+ self.components[anchor].data = ((index_u32(numbers.len()) + 1) << 1) | u32::from(folds);
+ numbers.extend([keys.chain.cast_signed(), keys.subject.cast_signed()]);
+ }
+ self.numbers = numbers.into_boxed_slice();
}
/// Write the length of each compound shorter than 16 components on its first component.
diff --git a/Libraries/LibWeb/Rust/src/css/style/component_matching.rs b/Libraries/LibWeb/Rust/src/css/style/component_matching.rs
index b6281810255..06c3780016a 100644
--- a/Libraries/LibWeb/Rust/src/css/style/component_matching.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/component_matching.rs
@@ -769,22 +769,83 @@ impl<S: SelectorSubject> SelectorEvaluator<S> {
if selector.is_relative_anchor() {
return Ok(false);
}
+ use super::selector::RelativeAxis;
let context = MatchContext {
logical_subject: false,
..context
};
- let outer = self.bindings.relative_anchor.replace(anchor);
- let outer_argument = std::mem::replace(&mut self.bindings.matching_relative_argument, true);
let (axis, below_the_axis) = relative_axis(selector);
let tree = self.subject.tree();
- let mut matched = Ok(false);
// The anchor stands outside the tree a `:host:has()` reads, whose root it walks from.
let axis = match (within == anchor, axis) {
- (false, _) => super::selector::RelativeAxis::Descendant,
+ (false, _) => RelativeAxis::Descendant,
(true, axis) => axis,
};
- super::selector_evaluation::walk_relative_axis(tree, axis, below_the_axis, within, |candidate| {
- match self.matches_from(selector, None, candidate, context) {
+ // NB: Every compound of the selector matches an element below the one the walk starts under. Where no
+ // element there carries what one of them tests for, the walk finds no witness.
+ let keys = match <S::Tree as SelectorTree>::SUMMARIZES_SUBTREE_KEYS {
+ true => selector.relative_subtree_keys(context.fold_ids_and_classes),
+ false => None,
+ };
+ if let Some(keys) = keys {
+ let above = match axis {
+ RelativeAxis::Descendant | RelativeAxis::Child => Some(within),
+ RelativeAxis::NextSibling
+ | RelativeAxis::FollowingSibling
+ | RelativeAxis::NextSiblingSubtree
+ | RelativeAxis::FollowingSiblingSubtree => tree.parent(anchor),
+ };
+ if above.is_some_and(|above| !tree.subtree_may_carry(above, keys.chain)) {
+ debug_assert!(
+ matches!(
+ self.find_relative_witness(selector, anchor, within, axis, below_the_axis, 0, context),
+ Ok(false)
+ ),
+ "the summary of the keys below an element lacks a key one of them carries"
+ );
+ return Ok(false);
+ }
+ }
+ let subject_keys = keys.map_or(0, |keys| keys.subject);
+ let matched = self.find_relative_witness(selector, anchor, within, axis, below_the_axis, subject_keys, context);
+ debug_assert!(
+ subject_keys == 0
+ || !matches!(matched, Ok(false))
+ || matches!(
+ self.find_relative_witness(selector, anchor, within, axis, below_the_axis, 0, context),
+ Ok(false)
+ ),
+ "the summary of the keys below an element lacks a key one of them carries"
+ );
+ matched
+ }
+
+ /// Whether a candidate along `axis` from `within` matches `selector`, a relative selector anchored at `anchor`.
+ /// The walk of a subtree goes below the elements whose descendants may carry `subject_keys`, the bits of the keys
+ /// of the subject compound in the summary of a subtree's keys, and below every element where they are 0.
+ #[allow(clippy::too_many_arguments)]
+ fn find_relative_witness(
+ &mut self,
+ selector: Selector<'_>,
+ anchor: S::Node,
+ within: S::Node,
+ axis: super::selector::RelativeAxis,
+ below_the_axis: bool,
+ subject_keys: u64,
+ context: MatchContext<'_>,
+ ) -> Answer<S> {
+ let tree = self.subject.tree();
+ let outer = self.bindings.relative_anchor.replace(anchor);
+ let outer_argument = std::mem::replace(&mut self.bindings.matching_relative_argument, true);
+ let mut matched = Ok(false);
+ super::selector_evaluation::walk_relative_axis(
+ tree,
+ axis,
+ below_the_axis,
+ within,
+ // NB: A witness below an element is a descendant of it carrying what the subject compound tests for.
+ |element| subject_keys == 0 || tree.subtree_may_carry(element, subject_keys),
+ |candidate| match self.matches_from(selector, None, candidate, context) {
Ok(true) => {
matched = Ok(true);
false
@@ -794,8 +855,8 @@ impl<S: SelectorSubject> SelectorEvaluator<S> {
matched = Err(incomplete);
false
}
- }
- });
+ },
+ );
self.bindings.relative_anchor = outer;
self.bindings.matching_relative_argument = outer_argument;
matched
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs
index fe779232b64..ef2dfea7685 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs
@@ -1800,7 +1800,17 @@ impl Projection {
/// [`subtree_key_bits`], as the last transaction committed them.
#[must_use]
pub(in crate::css::style) fn subtree_keys(&self, node: StyleNodeID) -> u64 {
- self.committed
+ self.subtree_keys_on(TransactionFactSide::After, node)
+ }
+
+ /// The summary [`Self::subtree_keys`] answers, of the tree on one side of the transaction being taken.
+ #[must_use]
+ pub(in crate::css::style) fn subtree_keys_on(&self, side: TransactionFactSide, node: StyleNodeID) -> u64 {
+ let generation = match side {
+ TransactionFactSide::Before => &self.before,
+ TransactionFactSide::After => &self.committed,
+ };
+ generation
.get(node.element_slot())
.map_or(u64::MAX, |row| row.subtree_keys)
}
@@ -2484,6 +2494,13 @@ impl SelectorTree for ProjectionTree<'_> {
self.projection.parent(node)
}
+ const SUMMARIZES_SUBTREE_KEYS: bool = true;
+
+ #[inline]
+ fn subtree_may_carry(self, node: StyleNodeID, keys: u64) -> bool {
+ self.projection.subtree_keys_on(self.side, node) & keys == keys
+ }
+
#[inline]
fn shadow_root_of(self, host: StyleNodeID) -> Option<StyleNodeID> {
self.projection.shadow_root_of(host)
diff --git a/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs b/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs
index b28bb49b6d8..e5c0a7c56ff 100644
--- a/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs
@@ -24,12 +24,14 @@ use super::tree::StyleNodeID;
use crate::css::css_tokenizer::TokenizerInput;
/// Visit the candidate witnesses of a relative selector along `axis` from `anchor` in `tree`, in tree
-/// order, until `visit` returns false.
+/// order, until `visit` returns false. A walk of a subtree goes below the elements `holds_below` says
+/// can hold a witness below them, and past the descendants of the others.
pub(crate) fn walk_relative_axis<T: SelectorTree>(
tree: T,
axis: RelativeAxis,
below_the_axis: bool,
anchor: T::Node,
+ holds_below: impl Fn(T::Node) -> bool,
mut visit: impl FnMut(T::Node) -> bool,
) {
// Visit the subtree of `root`, `root` itself included when `inclusive`, until `visit` returns false.
@@ -37,24 +39,31 @@ pub(crate) fn walk_relative_axis<T: SelectorTree>(
tree: T,
root: T::Node,
inclusive: bool,
+ holds_below: &impl Fn(T::Node) -> bool,
visit: &mut impl FnMut(T::Node) -> bool,
) -> bool {
if inclusive && !visit(root) {
return false;
}
- let mut descendant = tree.next_in_subtree(root, root);
- while let Some(candidate) = descendant {
+ let mut current = root;
+ loop {
+ let next = match holds_below(current) {
+ true => tree.next_in_subtree(current, root),
+ false => tree.next_after_subtree(current, root),
+ };
+ let Some(candidate) = next else {
+ return true;
+ };
if !visit(candidate) {
return false;
}
- descendant = tree.next_in_subtree(candidate, root);
+ current = candidate;
}
- true
}
let (first, every_sibling, subtree) = match axis {
RelativeAxis::Descendant => {
- visit_subtree(tree, anchor, false, &mut visit);
+ visit_subtree(tree, anchor, false, &holds_below, &mut visit);
return;
}
RelativeAxis::Child => (tree.first_child(anchor), true, false),
@@ -68,7 +77,7 @@ pub(crate) fn walk_relative_axis<T: SelectorTree>(
let mut sibling = first;
while let Some(candidate) = sibling {
let proceed = match subtree {
- true => visit_subtree(tree, candidate, !below_the_axis, &mut visit),
+ true => visit_subtree(tree, candidate, !below_the_axis, &holds_below, &mut visit),
false => visit(candidate),
};
if !proceed || !every_sibling {
@@ -122,6 +131,11 @@ pub(crate) trait SelectorTree: Copy {
if let Some(child) = self.first_child(node) {
return Some(child);
}
+ self.next_after_subtree(node, root)
+ }
+
+ /// The element after `node` and its descendants in tree order that is a descendant of `root`.
+ fn next_after_subtree(self, node: Self::Node, root: Self::Node) -> Option<Self::Node> {
let mut current = node;
while current != root {
if let Some(sibling) = self.next_sibling(current) {
@@ -132,6 +146,17 @@ pub(crate) trait SelectorTree: Copy {
None
}
+ /// Whether [`Self::subtree_may_carry`] rejects elements, so that a walk for the witnesses of a relative selector
+ /// has what they carry looked up at all.
+ const SUMMARIZES_SUBTREE_KEYS: bool = false;
+
+ /// Whether the descendants of `node` can possibly carry, between them, every class and attribute name whose
+ /// bits in the Bloom summary of the keys a subtree carries `keys` holds. A shortcut that can only skip work:
+ /// the default is the answer a walk of the descendants reaches without it.
+ fn subtree_may_carry(self, _node: Self::Node, _keys: u64) -> bool {
+ true
+ }
+
/// The slot an element is assigned to.
fn assigned_slot_of(self, _node: Self::Node) -> Option<Self::Node> {
None
diff --git a/Tests/LibWeb/Text/expected/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.txt b/Tests/LibWeb/Text/expected/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.txt
new file mode 100644
index 00000000000..d431a65d4ce
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.txt
@@ -0,0 +1,12 @@
+No element carries a key (BackCompat)
+ byClass: rgb(0, 0, 0)
+ byChain: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 0, 0)
+The keys arrived in another case (BackCompat)
+ byClass: rgb(0, 128, 0)
+ byChain: rgb(0, 128, 0)
+ byLaterSibling: rgb(0, 128, 0)
+The keys left (BackCompat)
+ byClass: rgb(0, 0, 0)
+ byChain: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/has-walk-skips-subtrees-that-carry-no-key.txt b/Tests/LibWeb/Text/expected/css/has-walk-skips-subtrees-that-carry-no-key.txt
new file mode 100644
index 00000000000..458e9d4f60b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/has-walk-skips-subtrees-that-carry-no-key.txt
@@ -0,0 +1,70 @@
+No element carries a key
+ byClass: rgb(0, 0, 0)
+ byAttribute: rgb(0, 0, 0)
+ byChain: rgb(0, 0, 0)
+ byChild: rgb(0, 0, 0)
+ byAlternatives: rgb(0, 0, 0)
+ byMixedCase: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 0, 0)
+ byNextSiblingSubtree: rgb(0, 0, 0)
+ byDeepWitness: rgb(0, 0, 0)
+ byInserted: rgb(0, 0, 0)
+ byMoved: rgb(0, 0, 0)
+ byOutside: rgb(0, 0, 0)
+ host: rgb(0, 0, 0)
+The keys arrived, some where no walk finds them
+ byClass: rgb(0, 128, 0)
+ byAttribute: rgb(0, 128, 0)
+ byChain: rgb(0, 128, 0)
+ byChild: rgb(0, 0, 0)
+ byAlternatives: rgb(0, 128, 0)
+ byMixedCase: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 0, 0)
+ byNextSiblingSubtree: rgb(0, 0, 0)
+ byDeepWitness: rgb(0, 0, 0)
+ byInserted: rgb(0, 128, 0)
+ byMoved: rgb(0, 0, 0)
+ byOutside: rgb(0, 128, 0)
+ host: rgb(0, 128, 0)
+The keys arrived where the walks find them
+ byClass: rgb(0, 128, 0)
+ byAttribute: rgb(0, 128, 0)
+ byChain: rgb(0, 128, 0)
+ byChild: rgb(0, 128, 0)
+ byAlternatives: rgb(0, 128, 0)
+ byMixedCase: rgb(0, 128, 0)
+ byLaterSibling: rgb(0, 128, 0)
+ byNextSiblingSubtree: rgb(0, 128, 0)
+ byDeepWitness: rgb(0, 128, 0)
+ byInserted: rgb(0, 128, 0)
+ byMoved: rgb(0, 128, 0)
+ byOutside: rgb(0, 128, 0)
+ host: rgb(0, 128, 0)
+The keys left
+ byClass: rgb(0, 0, 0)
+ byAttribute: rgb(0, 0, 0)
+ byChain: rgb(0, 0, 0)
+ byChild: rgb(0, 0, 0)
+ byAlternatives: rgb(0, 128, 0)
+ byMixedCase: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 128, 0)
+ byNextSiblingSubtree: rgb(0, 128, 0)
+ byDeepWitness: rgb(0, 0, 0)
+ byInserted: rgb(0, 0, 0)
+ byMoved: rgb(0, 0, 0)
+ byOutside: rgb(0, 0, 0)
+ host: rgb(0, 0, 0)
+Some keys came back
+ byClass: rgb(0, 0, 0)
+ byAttribute: rgb(0, 0, 0)
+ byChain: rgb(0, 128, 0)
+ byChild: rgb(0, 0, 0)
+ byAlternatives: rgb(0, 128, 0)
+ byMixedCase: rgb(0, 0, 0)
+ byLaterSibling: rgb(0, 128, 0)
+ byNextSiblingSubtree: rgb(0, 128, 0)
+ byDeepWitness: rgb(0, 128, 0)
+ byInserted: rgb(0, 0, 0)
+ byMoved: rgb(0, 0, 0)
+ byOutside: rgb(0, 128, 0)
+ host: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/input/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.html b/Tests/LibWeb/Text/input/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.html
new file mode 100644
index 00000000000..35fa9a2882a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/has-walk-folds-the-case-of-class-keys-in-quirks-mode.html
@@ -0,0 +1,41 @@
+<!DOCTYPE quirks>
+<script src="../include.js"></script>
+<style>
+ div {
+ color: rgb(0, 0, 0);
+ }
+ #byClass:has(.lateMixed),
+ #byChain:has(.lateOuter .lateInner),
+ #byLaterSibling:has(~ .lateLater) {
+ color: rgb(0, 128, 0);
+ }
+</style>
+<div id="byClass"><div><div></div></div></div>
+<div id="byChain"><div><div></div></div></div>
+<div id="byLaterSibling"></div>
+<div id="last"></div>
+<script>
+ // This document has no doctype: a class selector matches a class of another case.
+ test(() => {
+ const ids = ["byClass", "byChain", "byLaterSibling"];
+ const innermost = id => document.querySelector(`#${id} > div > div`);
+ const report = step => {
+ println(`${step} (${document.compatMode})`);
+ for (const id of ids)
+ println(` ${id}: ${getComputedStyle(document.getElementById(id)).color}`);
+ };
+
+ report("No element carries a key");
+
+ innermost("byClass").className = "latemixed";
+ innermost("byChain").className = "LATEINNER";
+ innermost("byChain").parentElement.className = "lateouter";
+ document.getElementById("last").className = "LateLater";
+ report("The keys arrived in another case");
+
+ innermost("byClass").className = "";
+ innermost("byChain").parentElement.className = "";
+ document.getElementById("last").className = "";
+ report("The keys left");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/has-walk-skips-subtrees-that-carry-no-key.html b/Tests/LibWeb/Text/input/css/has-walk-skips-subtrees-that-carry-no-key.html
new file mode 100644
index 00000000000..e33e50dc30d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/has-walk-skips-subtrees-that-carry-no-key.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ div {
+ color: rgb(0, 0, 0);
+ }
+ #byClass:has(.late-class),
+ #byAttribute:has([data-late]),
+ #byChain:has(.late-outer .late-inner),
+ #byChild:has(> .late-child),
+ #byAlternatives:has(:is(.late-one, .late-other)),
+ #byMixedCase:has(.lateMixed),
+ #byLaterSibling:has(~ .late-later),
+ #byNextSiblingSubtree:has(+ div .late-below-next),
+ #byDeepWitness:has(.late-deep),
+ #byInserted:has(.late-inserted),
+ #byMoved:has(.late-moved),
+ #byOutside:has(:is(.outside .late-inside)) {
+ color: rgb(0, 128, 0);
+ }
+</style>
+<div class="outside" id="tests">
+ <div id="byClass"><div><div></div></div></div>
+ <div id="byAttribute"><div><div></div></div></div>
+ <div id="byChain"><div><div class="late-inner"></div></div></div>
+ <div id="byChild"><div><div></div></div></div>
+ <div id="byAlternatives"><div><div></div></div></div>
+ <div id="byMixedCase"><div><div></div></div></div>
+ <div id="byLaterSibling"></div>
+ <div id="byNextSiblingSubtree"></div>
+ <div><div><div></div></div></div>
+ <div id="byDeepWitness"><div><div></div></div><div><div></div></div><div><div><div></div></div></div></div>
+ <div id="byInserted"><div></div></div>
+ <div id="byMoved"><div></div></div>
+ <div id="byOutside"><div><div></div></div></div>
+</div>
+<section id="host"></section>
+<script>
+ test(() => {
+ const ids = [
+ "byClass",
+ "byAttribute",
+ "byChain",
+ "byChild",
+ "byAlternatives",
+ "byMixedCase",
+ "byLaterSibling",
+ "byNextSiblingSubtree",
+ "byDeepWitness",
+ "byInserted",
+ "byMoved",
+ "byOutside",
+ ];
+ const host = document.getElementById("host");
+ const root = host.attachShadow({ mode: "open" });
+ root.innerHTML = `
+ <style>
+ :host { color: rgb(0, 0, 0); }
+ :host:has(.late-shadow) { color: rgb(0, 128, 0); }
+ </style>
+ <div><div></div></div>`;
+ const innermost = id => document.querySelector(`#${id} > div > div`);
+ const report = step => {
+ println(step);
+ for (const id of ids)
+ println(` ${id}: ${getComputedStyle(document.getElementById(id)).color}`);
+ println(` host: ${getComputedStyle(host).color}`);
+ };
+
+ report("No element carries a key");
+
+ innermost("byClass").className = "late-class";
+ innermost("byAttribute").setAttribute("data-late", "");
+ innermost("byChain").parentElement.className = "late-outer";
+ // NB: A grandchild is no child.
+ innermost("byChild").className = "late-child";
+ innermost("byAlternatives").className = "late-other";
+ innermost("byMixedCase").className = "latemixed";
+ // NB: An earlier sibling is no later one.
+ document.getElementById("byClass").classList.add("late-later");
+ // NB: The next sibling itself stands on the axis, not below it.
+ document.getElementById("byNextSiblingSubtree").nextElementSibling.className = "late-below-next";
+ const inserted = document.createElement("div");
+ inserted.className = "late-inserted";
+ document.getElementById("byInserted").firstElementChild.appendChild(inserted);
+ const moved = document.createElement("div");
+ moved.innerHTML = "<div><div class='late-moved'></div></div>";
+ document.body.appendChild(moved);
+ innermost("byOutside").className = "late-inside";
+ root.querySelector("div > div").className = "late-shadow";
+ report("The keys arrived, some where no walk finds them");
+
+ document.querySelector("#byChild > div").className = "late-child";
+ innermost("byMixedCase").className = "lateMixed";
+ document.getElementById("byNextSiblingSubtree").nextElementSibling.nextElementSibling.className = "late-later";
+ document.querySelector("#byNextSiblingSubtree + div > div > div").className = "late-below-next";
+ document.querySelector("#byDeepWitness > div:last-child > div > div").className = "late-deep";
+ document.getElementById("byMoved").firstElementChild.appendChild(moved);
+ report("The keys arrived where the walks find them");
+
+ innermost("byClass").className = "";
+ innermost("byAttribute").removeAttribute("data-late");
+ innermost("byChain").className = "";
+ document.querySelector("#byChild > div").className = "";
+ innermost("byAlternatives").className = "late-one";
+ innermost("byMixedCase").className = "";
+ document.querySelector("#byDeepWitness > div:last-child > div > div").className = "";
+ inserted.remove();
+ document.body.appendChild(moved);
+ document.getElementById("tests").className = "";
+ root.querySelector("div > div").className = "";
+ report("The keys left");
+
+ innermost("byChain").className = "late-inner";
+ document.querySelector("#byDeepWitness > div:first-child > div").className = "late-deep";
+ document.getElementById("tests").className = "outside";
+ root.querySelector("div").className = "late-shadow";
+ report("Some keys came back");
+ });
+</script>