Truly independent web browser
LibWeb: Resolve tree-counting functions in style queries
Callum Lawc1e54da64c25
diff --git a/Libraries/LibWeb/Rust/src/css/animation.rs b/Libraries/LibWeb/Rust/src/css/animation.rsindex 74c2de94912..fbd8448c5fe 100644--- a/Libraries/LibWeb/Rust/src/css/animation.rs+++ b/Libraries/LibWeb/Rust/src/css/animation.rs@@ -7065,12 +7065,16 @@ pub(crate) fn resolve_published_animation_declarations(direction,important_property_bitmap,);+ let style_query_dependencies = style_query_references.into_inner();+ resolved.uses_tree_counting_function |= style_query_dependencies+ .as_ref()+ .is_some_and(|dependencies| dependencies.sibling_position);resolved._base_urls = base_urls;PublishedAnimationDeclarations {resolved: Box::new(resolved),custom_properties,substitution_marks: substitution_marks.get(),- style_query_dependencies: style_query_references.into_inner(),+ style_query_dependencies,}}diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rsindex 6e247f31a24..e85fcfba503 100644--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs@@ -461,17 +461,17 @@ pub(crate) struct CascadeResolutionContext<'a> {pub(crate) custom_functions: &'a [crate::css::custom_properties::SubstitutionFunctionDefinition],pub(crate) custom_function_scope_identity: usize,pub(crate) custom_function_visibilities: &'a [crate::css::custom_properties::FfiSubstitutionFunctionVisibility],- /// Where the custom properties style queries read are kept, if anywhere.+ /// Where the custom properties and sibling position style queries read are kept, if anywhere.pub(crate) style_query_dependencies:Option<&'a mut Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>,}-/// What a `style()` query in a substitution resolves against, as the queried element's style-/// computes it: its lengths, and the color scheme and currentcolor its colors resolve with.+/// Length, tree-counting and color inputs used when evaluating style queries.#[repr(C)]#[derive(Clone, Copy)]pub struct FfiStyleQueryInputs {pub length: crate::css::style_compute::FfiLengthResolutionContext,+ pub tree_counting: Option<(u64, u64)>,/// A PreferredColorScheme code.pub color_scheme: u8,/// The packed currentcolor, as the C++ Color::value() packs it.diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex 8a3f2cfbfeb..194799247f2 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -909,7 +909,7 @@ struct ASFResolutionContext<'a> {/// The queried element's sibling count and index, which tree-counting functions in a style/// query resolve against, where they are known.style_query_tree_counting: Option<(u64, u64)>,- /// Where the custom properties a style query reads are noted, for the host to record.+ /// Where the custom properties and sibling position a style query reads are noted, for the host to record.style_query_dependencies: Option<&'a mut Option<Box<StyleQueryDependencies>>>,final_custom_properties: Option<&'a HashMap<Vec<u16>, RetainedStyleValueData>>,function_local_scopes: Vec<FunctionLocalScope>,@@ -922,28 +922,37 @@ impl ASFResolutionContext<'_> {dependencies.get_or_insert_default().note(name);}}++ fn note_style_query_sibling_position_dependency(&mut self) {+ if let Some(dependencies) = self.style_query_dependencies.as_deref_mut() {+ dependencies.get_or_insert_default().sibling_position = true;+ }+ }}-/// The custom properties style queries read in one resolution, which the host records as the-/// element's style query references.+/// The custom properties and sibling position style queries read in one resolution.#[derive(Clone, Default)]-pub(crate) struct StyleQueryDependencies(Vec<Vec<u16>>);+pub(crate) struct StyleQueryDependencies {+ names: Vec<Vec<u16>>,+ pub(crate) sibling_position: bool,+}impl StyleQueryDependencies {fn note(&mut self, name: &[u16]) {- if !self.0.iter().any(|noted| noted == name) {- self.0.push(name.to_vec());+ if !self.names.iter().any(|noted| noted == name) {+ self.names.push(name.to_vec());}}pub(crate) fn extend(&mut self, other: &Self) {+ self.sibling_position |= other.sibling_position;for name in other.names() {self.note(name);}}pub(crate) fn names(&self) -> impl Iterator<Item = &[u16]> {- self.0.iter().map(Vec::as_slice)+ self.names.iter().map(Vec::as_slice)}}@@ -1972,6 +1981,9 @@ impl StyleRangeValue {// A tree-counting function resolves against the queried element's place among its// siblings first.StyleValueData::Calculated { .. } => {+ if crate::css::style_compute::collect_external_value_dependencies(value).uses_tree_counting_function {+ context.note_style_query_sibling_position_dependency();+ }match tree_counting.zip(length_resolution_context).and_then(|(tree_counting, context)| {@@ -3287,6 +3299,7 @@ pub(crate) fn resolve_vars(media_environment,style_query_length_resolution_context: style_query_inputs.map(|inputs| &inputs.length),style_query_color_resolution_input: style_query_inputs.map(|inputs| inputs.color_input()),+ style_query_tree_counting: style_query_inputs.and_then(|inputs| inputs.tree_counting),style_query_dependencies,final_custom_properties,token_cache: Some(token_cache),@@ -3323,6 +3336,38 @@ pub(crate) fn resolve_vars(mod tests {use super::*;+ #[test]+ fn style_queries_only_report_sibling_dependencies_for_tree_counting() {+ let registry = CustomPropertyRegistry::empty();+ let mut random_index = 0;+ let parse_context = registry.parse_context(&mut random_index);+ let length = crate::css::style_compute::FfiLengthResolutionContext::default();+ for (source, expected, reads_sibling_position) in [+ ("10px", 10.0, false),+ ("calc(2 * 10px)", 20.0, false),+ ("calc(10px * sibling-index())", 10.0, true),+ ("calc(10px * sibling-count())", 20.0, true),+ ] {+ let value =+ parse_with_syntax(&parse_context, &utf16(source), &SyntaxNode::Type(SyntaxType::Length)).unwrap();+ let mut dependencies = None;+ let mut context = ASFResolutionContext {+ style_query_length_resolution_context: Some(&length),+ style_query_tree_counting: Some((2, 1)),+ style_query_dependencies: Some(&mut dependencies),+ ..Default::default()+ };+ assert_eq!(StyleRangeValue::of(&value, &mut context).unwrap().value, expected);+ assert_eq!(+ dependencies+ .as_ref()+ .is_some_and(|dependencies| dependencies.sibling_position),+ reads_sibling_position,+ "{source}",+ );+ }+ }+#[test]fn custom_property_values_outlive_their_store() {let name = utf16("--value");diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rsindex 72c72a48998..c3f192085e9 100644--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs@@ -1113,6 +1113,9 @@ impl RetainedState {target: computed::ComputedStyleTarget,) -> Option<crate::css::cascaded_properties::FfiStyleQueryInputs> {let node = target.node();+ let tree_counting = self+ .element_sibling_position(node)+ .map(|(count, index)| (u64::from(count), u64::from(index)));let parent_record = || {if target.pseudo_kind() == u8::MAX {self.computed_group_sets@@ -1134,12 +1137,14 @@ impl RetainedState {);return Some(crate::css::cascaded_properties::FfiStyleQueryInputs {length,+ tree_counting,color_scheme: values.inherited_ui().color_scheme,current_color: values.inherited_text().color,});}Some(crate::css::cascaded_properties::FfiStyleQueryInputs {length: *self.document_media.length()?,+ tree_counting,color_scheme: self.document_style_computation_inputs.preferred_color_scheme,// Opaque black, the initial color.current_color: 0xff00_0000,@@ -1626,9 +1631,13 @@ impl RetainedState {};drop(cascaded_store);self.counters.bump(Counter::EngineCustomPropertyEnvironmentsResolved);- // What the registered values read beyond the element's fonts reaches the element's- // records as what they read themselves does: a sibling change, a container's size.- if reads.sibling_position {+ // What the registered values and style queries read beyond the element's fonts reaches+ // the element's records as what they read themselves does: a sibling change, a container's size.+ if reads.sibling_position+ || style_query_references+ .as_ref()+ .is_some_and(|dependencies| dependencies.sibling_position)+ {*self.custom_declaration_reads.entry(node).or_default() |=bridge::FfiNodeRecordReads::SiblingPosition as u8;}diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex 53430fc5211..c8c90a3811d 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -3742,12 +3742,16 @@ impl RetainedState {self.note_container_effects_for_host(node, effects);}declarations.sort_by_key(|(priority, index, ..)| (*priority, *index));- let store = WinnerStore::new(+ let mut store = WinnerStore::new(declarations.into_iter().map(|(_, _, declaration)| declaration).collect(),);+ store.reads_sibling_position = style_query_references+ .borrow()+ .as_ref()+ .is_some_and(|dependencies| dependencies.sibling_position);// A store built to drive a record says whether that record rolls back; one built to admit a// row only adds to what the node's records are known to do.let bit = rolled_back_bit(pseudo_kind);diff --git a/Libraries/LibWeb/Rust/src/css/style/publication/demand.rs b/Libraries/LibWeb/Rust/src/css/style/publication/demand.rsindex 205eb1a96d1..5b1e15b806d 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication/demand.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication/demand.rs@@ -639,6 +639,7 @@ impl RetainedState {let retained = |value: &StyleValueData| unsafe {RetainedStyleValueData::from_retained_pointer(retain_style_value(value))};+ let style_query_references = std::cell::RefCell::new(None);let mut style_query = None;let mut functions = None;let mut winners: Vec<WinnerDeclaration> = Vec::with_capacity(declarations.len());@@ -698,7 +699,7 @@ impl RetainedState {},attributes: None,style_query: style_query.as_ref().and_then(Option::as_ref),- style_query_references: None,+ style_query_references: Some(&style_query_references),functions: functions.as_ref(),};let substituted = Self::substitute_written_value(@@ -737,7 +738,12 @@ impl RetainedState {));}}- Ok(WinnerStore::new(winners))+ let mut store = WinnerStore::new(winners);+ store.reads_sibling_position = style_query_references+ .into_inner()+ .as_ref()+ .is_some_and(|dependencies| dependencies.sibling_position);+ Ok(store)}}diff --git a/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs b/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rsindex 710f1a59780..b457b6260ee 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs@@ -91,6 +91,8 @@ pub(in crate::css::style) struct WinnerStore {// NB: Cascade order supplies both source slots and logical/physical tie breaking.declarations: Vec<WinnerDeclaration>,by_property: Vec<u16>,+ /// A style query read the sibling position while substituting these declarations.+ pub(super) reads_sibling_position: bool,}impl WinnerStore {@@ -104,6 +106,7 @@ impl WinnerStore {Self {declarations,by_property,+ reads_sibling_position: false,}}@@ -116,6 +119,9 @@ impl WinnerStore {/// NB: Compare the resolved declarations while retaining context-dependent computation guards.pub(super) fn environment_value_delta(&self, other: &Self, engine: &RetainedState) -> Option<SmallVec<[u16; 8]>> {+ if self.reads_sibling_position || other.reads_sibling_position {+ return None;+ }if self.declarations.len() != other.declarations.len() {return None;}@@ -150,9 +156,11 @@ impl WinnerStore {pub(super) fn uses_tree_counting_function(&self, engine: &RetainedState) -> bool {let view = self.view(engine);- self.declarations- .iter()- .any(|declaration| view.dependencies(declaration).uses_tree_counting_function)+ self.reads_sibling_position+ || self+ .declarations+ .iter()+ .any(|declaration| view.dependencies(declaration).uses_tree_counting_function)}/// The proof that no value the store holds resolves a `url()`, or `None` when one may.diff --git a/Tests/LibWeb/Text/expected/css/if-style-tree-counting-invalidation.txt b/Tests/LibWeb/Text/expected/css/if-style-tree-counting-invalidation.txtnew file mode 100644index 00000000000..1eae4a5134d--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/if-style-tree-counting-invalidation.txt@@ -0,0 +1,6 @@+count-equality: "MATCH", "NO MATCH", "NO MATCH", "NO MATCH", "MATCH", "NO MATCH"+registered: "MATCH", "NO MATCH", "NO MATCH", "NO MATCH", "MATCH", "NO MATCH"+unregistered: "MATCH", "MATCH", "NO MATCH", "MATCH", "MATCH", "MATCH"+function-longhand: "MATCH", "NO MATCH", "NO MATCH", "NO MATCH", "MATCH", "NO MATCH"+inline: "MATCH", "NO MATCH", "NO MATCH", "NO MATCH", "MATCH", "NO MATCH"+animation-longhand: "MATCH", "NO MATCH", "NO MATCH", "NO MATCH", "MATCH", "NO MATCH"diff --git a/Tests/LibWeb/Text/expected/css/if-style-tree-counting.txt b/Tests/LibWeb/Text/expected/css/if-style-tree-counting.txtnew file mode 100644index 00000000000..2a9960a2ba9--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/if-style-tree-counting.txt@@ -0,0 +1,3 @@+1: "PASS", PASS, PASS, PASS, PASS, PASS+2: "PASS", PASS, PASS, PASS, PASS, PASS+unregistered function: PASSdiff --git a/Tests/LibWeb/Text/input/css/if-style-tree-counting-invalidation.html b/Tests/LibWeb/Text/input/css/if-style-tree-counting-invalidation.htmlnew file mode 100644index 00000000000..74c888537bc--- /dev/null+++ b/Tests/LibWeb/Text/input/css/if-style-tree-counting-invalidation.html@@ -0,0 +1,85 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ @property --two {+ syntax: "<length>";+ inherits: false;+ initial-value: 20px;+ }++ @property --one {+ syntax: "<length>";+ inherits: false;+ initial-value: 10px;+ }++ @property --registered {+ syntax: "<string>";+ inherits: false;+ initial-value: "NO MATCH";+ }++ @function --count-content(--n <length>) {+ result: if(style(--n: calc(10px * sibling-count())): "MATCH" ; else: "NO MATCH");+ }++ .count-equality {+ content: if(style(--two: calc(10px * sibling-count())): "MATCH" ; else: "NO MATCH");+ }++ .registered {+ --registered: if(style(--two: calc(10px * sibling-count())): "MATCH" ; else: "NO MATCH");+ content: var(--registered);+ }++ .unregistered {+ --unregistered: if(style(--one >= calc(10px * sibling-index())): "MATCH" ; else: "NO MATCH");+ content: var(--unregistered);+ }++ .function-longhand {+ content: --count-content(20px);+ }++ @keyframes count-content {+ from,+ to {+ content: if(style(--two: calc(10px * sibling-count())): "MATCH" ; else: "NO MATCH");+ }+ }++ .animation-longhand {+ animation: count-content 1s paused both;+ }+</style>+<script>+ test(() => {+ for (const name of [+ "count-equality",+ "registered",+ "unregistered",+ "function-longhand",+ "inline",+ "animation-longhand",+ ]) {+ const parent = document.createElement("div");+ parent.innerHTML = `<div class="${name}"></div><div></div>`;+ const [target, sibling] = parent.children;+ if (name === "inline")+ target.style.content = 'if(style(--two: calc(10px * sibling-count())): "MATCH"; else: "NO MATCH")';+ document.body.append(parent);+ const results = [getComputedStyle(target).content];+ const mutate = callback => {+ callback();+ results.push(getComputedStyle(target).content);+ };+ mutate(() => parent.append(document.createElement("div")));+ mutate(() => parent.prepend(document.createElement("div")));+ mutate(() => parent.firstElementChild.remove());+ mutate(() => parent.lastElementChild.remove());+ mutate(() => sibling.remove());+ println(`${name}: ${results.join(", ")}`);+ parent.remove();+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/if-style-tree-counting.html b/Tests/LibWeb/Text/input/css/if-style-tree-counting.htmlnew file mode 100644index 00000000000..99951760a4e--- /dev/null+++ b/Tests/LibWeb/Text/input/css/if-style-tree-counting.html@@ -0,0 +1,53 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ @property --index {+ syntax: "<length>";+ inherits: false;+ initial-value: 0px;+ }++ @property --count {+ syntax: "<length>";+ inherits: false;+ initial-value: 0px;+ }++ @function --matches-index(--n <length>) {+ result: if(style(--n: calc(10px * sibling-index())): PASS; else: FAIL);+ }++ #siblings > div {+ --count: 20px;+ content: if(style(--index: calc(10px * sibling-index())): "PASS" ; else: "FAIL");+ --index-equality: if(style(--index: calc(10px * sibling-index())): PASS; else: FAIL);+ --count-equality: if(style(--count: calc(10px * sibling-count())): PASS; else: FAIL);+ --index-range: if(style(--index >= calc(10px * sibling-index())): PASS; else: FAIL);+ --count-range: if(style(--count <= calc(10px * sibling-count())): PASS; else: FAIL);+ --function: --matches-index(var(--index));+ }+</style>+<div id="siblings">+ <div style="--index: 10px"></div>+ <div style="--index: 20px"></div>+</div>+<div><div id="unregistered" style="--function: --matches-index(10px)"></div></div>+<script>+ test(() => {+ const properties = [+ "content",+ "--index-equality",+ "--count-equality",+ "--index-range",+ "--count-range",+ "--function",+ ];+ for (const [index, element] of document.querySelectorAll("#siblings > div").entries()) {+ const style = getComputedStyle(element);+ const results = properties.map(name => style.getPropertyValue(name).trim());+ println(`${index + 1}: ${results.join(", ")}`);+ }+ const unregistered = document.getElementById("unregistered");+ println(`unregistered function: ${getComputedStyle(unregistered).getPropertyValue("--function").trim()}`);+ });+</script>