Truly independent web browser
LibWeb: Find animated custom property cycles as substitution reads
Andreas Kling85400450b940
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex 3ee45c7ea42..d3ebf1246a8 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -477,13 +477,6 @@ impl CustomPropertyRegistry {}/// Whether the custom property `name` names is registered.- /// Whether the name is registered with an initial value, which it reads as where nothing declares it.- pub(crate) fn has_initial_value(&self, name: &Utf16FlyString) -> bool {- self.registrations- .get(name)- .is_some_and(|registration| registration.initial_source.is_some())- }-pub(crate) fn is_registered(&self, name: &Utf16FlyString) -> bool {self.registrations.contains_key(name)}@@ -1022,11 +1015,6 @@ impl CustomPropertyStore {Some(entry.value.pointer() as usize)}- /// Whether the store, or one it inherits from, holds a value of the name.- pub(crate) fn holds_name(&self, name: &Utf16FlyString) -> bool {- self.get_by_name_with_owner(name).is_some()- }-fn get_by_name_with_owner(&self, name: &Utf16FlyString) -> Option<(&CustomPropertyEntry, &CustomPropertyStore)> {self.own_values.get(&name.raw_identity())@@ -1323,6 +1311,8 @@ struct ASFResolutionContext<'a> {substitution_limit_hits: u64,function_local_scopes: Vec<FunctionLocalScope<'a>>,token_cache: Option<&'a mut CustomPropertyTokenCache>,+ /// Where the custom properties of the element the substitution under way looks up are noted, if anywhere.+ element_property_reads: Option<&'a mut HashSet<Utf16FlyString>>,}impl ASFResolutionContext<'_> {@@ -1608,6 +1598,7 @@ fn compute_element_custom_property(element_values: context.element_values.as_deref_mut(),function_local_scopes: Vec::new(),token_cache: context.token_cache.as_deref_mut(),+ element_property_reads: context.element_property_reads.as_deref_mut(),..*context};@@ -1965,6 +1956,12 @@ fn resolve_custom_property_with_lookup(return result;}+ if lookup == CustomPropertyLookup::Normal+ && let Some(reads) = context.element_property_reads.as_deref_mut()+ {+ reads.insert(name.clone());+ }+// Pop the function local scopes while we resolve the element level custom property.let mut local_scopes = std::mem::take(&mut context.function_local_scopes);let context_ref = RefCell::new(context);@@ -2857,151 +2854,6 @@ fn split_function_arguments(tokens: &[ComponentValue]) -> Vec<&[ComponentValue]>tokens.split(ComponentValue::is_comma).collect()}-/// The custom properties of the element that substituting `tokens` reads, looking through the custom functions it-/// calls as [`replace_a_dashed_function`] resolves them. A parameter or local of a function on the way shadows the-/// element's property of that name, and `holds_a_value` says of a name whether its `var()` leaves its fallback unread.-/// A function's reads are worked out once per number of arguments passed to it, so this takes time in proportion to-/// the functions and the calls, however many paths lead through them.-/// What `if()`, `attr()`, `inherit()` and `env()` read is left out: which of their arguments substitute depends on the-/// values themselves.-pub(crate) fn custom_property_reads_through_functions(- tokens: &[ComponentValue],- functions: &CustomFunctionRegistry<'_>,- holds_a_value: &dyn Fn(&Utf16FlyString) -> bool,-) -> Vec<Arc<[u16]>> {- let mut read_ahead = FunctionReadAhead {- functions,- holds_a_value,- calling: Vec::new(),- reads_of_calls: HashMap::new(),- reads: HashSet::new(),- };- read_ahead.visit(tokens);- read_ahead.reads.iter().map(|name| Arc::from(name.to_utf16())).collect()-}--struct FunctionReadAhead<'a, 'b> {- functions: &'a CustomFunctionRegistry<'b>,- holds_a_value: &'a dyn Fn(&Utf16FlyString) -> bool,- /// The functions whose bodies are being visited, innermost last: their local scopes.- calling: Vec<&'a PreparedCustomFunction<'b>>,- /// What a call of a definition with so many of its parameters passed reads, past the locals of that definition and- /// of what it calls. Which caller's locals shadow those is for each caller to say as it takes them.- reads_of_calls: HashMap<(*const PreparedCustomFunction<'b>, usize), Rc<HashSet<Utf16FlyString>>>,- /// What the innermost function being visited reads so far.- reads: HashSet<Utf16FlyString>,-}--impl FunctionReadAhead<'_, '_> {- fn visit(&mut self, tokens: &[ComponentValue]) {- for value in tokens {- match &value.kind {- ComponentKind::Token(_) => {}- ComponentKind::SimpleBlock { values, .. } => self.visit(values.as_ref()),- ComponentKind::Function { name, values } => {- if name.eq_ignore_ascii_case("var") {- self.visit_var(values.as_ref());- } else if name.starts_with_ascii("--") {- self.visit_call(name.as_ref(), values.as_ref());- } else if !is_substitution_function(name.as_ref()) {- self.visit(values.as_ref());- }- }- }- }- }-- fn visit_var(&mut self, arguments: &[ComponentValue]) {- let comma = arguments.iter().position(ComponentValue::is_comma);- let first_argument = trim_whitespace(&arguments[..comma.unwrap_or(arguments.len())]);- let name = match first_argument {- [value] => value.ident_string().filter(|name| name.starts_with_ascii("--")),- _ => None,- };- let Some(name) = name else {- self.visit(first_argument);- return;- };- let fly_name = name.fly_string();- if self- .calling- .last()- .is_some_and(|function| function.declares_local(&fly_name))- {- return;- }- // NB: A fallback counts even where a caller's local shadows the name, which can leave that local no value.- let reads_fallback = !(self.holds_a_value)(&fly_name);- self.reads.insert(fly_name.into_owned());- if let Some(comma) = comma- && reads_fallback- {- self.visit(&arguments[comma + 1..]);- }- }-- fn visit_call(&mut self, name: &[u16], arguments: &[ComponentValue]) {- let caller_scope_identity = self- .calling- .last()- .map_or(self.functions.caller_scope_identity, |function| function.scope_identity);- let functions = self.functions;- let Some(function) = functions- .visible- .iter()- .filter(|visibility| visibility.caller_scope_identity == caller_scope_identity)- .map(|visibility| &functions.definitions[visibility.definition_index])- .find(|definition| definition.signature.name.units() == name)- else {- return;- };- let arguments = split_function_arguments(arguments);- for argument in &arguments {- self.visit(argument);- }- // NB: A function reached again is a cycle of its own, and reads nothing it has not read on the way there.- if self.calling.iter().any(|calling| calling.identity == function.identity) {- return;- }- let passed = arguments.len().min(function.parameter_defaults.len());- let key = (std::ptr::from_ref(function), passed);- let reads_of_call = if let Some(reads_of_call) = self.reads_of_calls.get(&key) {- Rc::clone(reads_of_call)- } else {- let reads_of_caller = std::mem::take(&mut self.reads);- self.calling.push(function);- for default_value in function.parameter_defaults[passed..].iter().flatten() {- self.visit(default_value.as_ref());- }- // NB: Resolving function styles computes every declaration of the body, whether the result reads it or not.- for declaration in &function.declarations {- self.visit(declaration.tokens());- }- self.calling.pop();- let reads_of_call = Rc::new(std::mem::replace(&mut self.reads, reads_of_caller));- self.reads_of_calls.insert(key, Rc::clone(&reads_of_call));- reads_of_call- };- let caller = self.calling.last().copied();- self.reads.extend(- reads_of_call- .iter()- .filter(|name| !caller.is_some_and(|caller| caller.declares_local(name)))- .cloned(),- );- }-}--impl PreparedCustomFunction<'_> {- fn declares_local(&self, name: &Utf16FlyString) -> bool {- self.signature- .parameters- .iter()- .any(|parameter| parameter.name == *name)- || self.declarations.iter().any(|declaration| declaration.name == *name)- }-}-// https://drafts.csswg.org/css-mixins/#resolve-function-stylesfn resolve_function_styles<'a, 'names>(store: Option<&CustomPropertyStore>,@@ -3839,6 +3691,49 @@ pub(crate) struct VarResolutionInputs<'a> {pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::StyleQueryInputs>,}+/// The custom properties of the element that substituting `value`, as the custom property `name`, looks up with the+/// values `inputs` holds: what its `var()` functions and `if()` conditions name, wherever a function, a branch, a+/// fallback or an attribute's value takes that, and only where they do.+pub(crate) fn custom_properties_a_substitution_reads(+ inputs: &VarResolutionInputs,+ name: &Utf16FlyString,+ value: &UnresolvedPayload,+ environment: &mut VarResolutionEnvironment<'_>,+) -> HashSet<Utf16FlyString> {+ let VarResolutionEnvironment {+ attributes,+ custom_functions,+ token_cache,+ } = environment;+ let mut reads = HashSet::new();+ let mut context = ASFResolutionContext {+ attributes: Some(attributes),+ inheritance_store: inputs.inheritance_store,+ attribute_names_are_ascii_case_insensitive: inputs.attribute_names_are_ascii_case_insensitive,+ custom_functions: Some(custom_functions),+ parse_context: inputs.parse_context,+ media_environment: inputs.media_environment,+ style_query_length_resolution_context: inputs.style_query_inputs.map(|inputs| &inputs.length),+ style_query_color_resolution_input: inputs.style_query_inputs.map(|inputs| inputs.color_input()),+ style_query_tree_counting: inputs.style_query_inputs.and_then(|inputs| inputs.tree_counting),+ token_cache: Some(token_cache),+ element_property_reads: Some(&mut reads),+ ..Default::default()+ };+ let tokens = value.components();+ // NB: What the substitution comes to is of no interest here, only what it looked at.+ let _ = substitute_arbitrary_substitution_functions(+ inputs.store,+ inputs.registry,+ tokens.as_ref(),+ &mut context,+ 0,+ Some(SubstitutionContextDependency::Property(name.clone(), None)),+ );+ drop(context);+ reads+}+pub(crate) fn resolve_vars(inputs: &VarResolutionInputs,property_id: u16,diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rsindex d89f002f5fc..85cc439a0f1 100644--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs@@ -437,6 +437,11 @@ fn named_custom_property_reads(value: &StyleValueData) -> Option<Vec<&[u16]>> {all_references_visible.then_some(references)}+/// Whether a written value holds a function that substitutes anything.+fn substitutes(value: &StyleValueData) -> bool {+ matches!(substituted_tokens(value), StyleValueData::Unresolved(unresolved) if unresolved.presence().has_any())+}+/// Which nodes of the graph `edges` describes lie on a cycle of it, one with an edge to itself among them. Those are the/// nodes of a strongly connected component of more than one node, which Tarjan's algorithm finds in time linear in the/// nodes and edges. It walks with a stack of its own, as a chain may be as long as a page likes.@@ -812,13 +817,21 @@ impl RetainedState {/// The custom properties in a dependency cycle through what an element's animations declare, as/// `--p: var(--q)` in a keyframe beside `--q: var(--p)` on the element. An animated value wins- /// the cascade over a declared one, so a name it animates reads as its keyframes do. `inherited`- /// is the environment the element inherits.+ /// the cascade over a declared one, so a name it animates reads as its keyframes do. What a value+ /// reads is what substituting it looks up, over `base`, the element's environment beneath its+ /// animations, with their values `animated`, and `inheritance`, the environment it inherits:+ /// which branch of an `if()` or fallback that takes depends on the values, and what decides that+ /// is itself read, so that a cycle through it is found whichever way it went.pub(crate) fn custom_properties_in_an_animated_cycle(&self,node: StyleNodeID,pseudo: Option<u8>,- inherited: Option<&CustomPropertyStore>,+ base: *const c_void,+ inheritance: *const c_void,+ animated: &[(+ crate::css::retained_fly_string::RetainedUtf16FlyString,+ RetainedStyleValueData,+ )],) -> Vec<crate::css::retained_fly_string::RetainedUtf16FlyString> {type Name = crate::css::retained_fly_string::RetainedUtf16FlyString;let slot = pseudo.map_or(0, |kind| kind + 1);@@ -834,14 +847,10 @@ impl RetainedState {}}}- if written.iter().all(|(_, value)| {- !value_calls_custom_functions(value)- && named_custom_property_reads(value).is_none_or(|names| names.is_empty())- }) {+ if !written.iter().any(|(_, value)| substitutes(value)) {return Vec::new();}- let animated_count = written.len();- let mut written_names: HashSet<usize> = written.iter().map(|(name, _)| name.raw()).collect();+ let written_names: HashSet<usize> = written.iter().map(|(name, _)| name.raw()).collect();let declarations = self.live_style.as_ref()@@ -860,54 +869,78 @@ impl RetainedState {}}}- written_names.extend(written[animated_count..].iter().map(|(name, _)| name.raw()));// NB: A container condition the engine cannot decide leaves what a function reads unknown, as a read of no name.let functions = written.iter().any(|(_, value)| value_calls_custom_functions(value)).then(|| self.prepare_custom_functions(&self.document_functions, node, pseudo)).flatten();+ let reads_attributes = functions.as_ref().is_some_and(|functions| functions.reads_attributes)+ || written.iter().any(|(_, value)| value_reads_attributes(value));+ let attribute_element = self.substitution_attribute_element(node, pseudo);+ let attributes = reads_attributes+ .then(|| SubstitutionAttributes::of(&self.projection, attribute_element, self.html_element_namespace));+ let reads_conditions = functions.is_some() || written.iter().any(|(_, value)| value_reads_conditions(value));+ let style_query = reads_conditions+ .then(|| self.style_query_inputs(computed::ComputedStyleTarget::new(node, pseudo.unwrap_or(u8::MAX))))+ .flatten();+ // SAFETY: The base store is live for the sample, and the values are live for the call.+ let base = unsafe { retained_store(base) };+ let values = animated+ .iter()+ .map(|(name, value)| (name.raw(), false, value.pointer().cast()))+ .collect();+ // SAFETY: The values are live for the call.+ let store = unsafe { CustomPropertyStore::cascaded_child(base, values) };let registry = self.document_style_computation_inputs.custom_property_registry();- let holds_a_value = |name: &ak::Utf16FlyString| {- written_names.contains(&name.raw_identity())- || registry.has_initial_value(name)- || inherited.is_some_and(|store| store.holds_name(name))- };- let mut reads: Vec<(&Name, Vec<Arc<[u16]>>)> = Vec::new();+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();+ let mut parse_context = registry.parse_context(&random_function_index);+ parse_context.in_quirks_mode = self.document_style_computation_inputs.in_quirks_mode;+ let media_environment = self.document_media.environment();+ // SAFETY: The store the element inherits from is live for the sample.+ let inheritance_store = unsafe { inheritance.cast::<CustomPropertyStore>().as_ref() };+ let resolution_context = engine_resolution_context(+ &parse_context,+ Some(&store),+ inheritance_store,+ registry,+ attributes.as_ref(),+ &media_environment,+ style_query.as_ref(),+ functions.as_ref(),+ );+ let mut environment = crate::css::custom_properties::prepare_var_resolution_environment(+ resolution_context.attributes,+ resolution_context.custom_functions,+ );+ let mut reads: Vec<(&Name, Vec<usize>)> = Vec::new();let mut reads_of_name: HashMap<usize, usize> = HashMap::default();for (name, value) in &written {- let names: Vec<Arc<[u16]>> = match (&functions, substituted_tokens(value)) {- (Some(functions), StyleValueData::Unresolved(unresolved)) if value_calls_custom_functions(value) => {- crate::css::custom_properties::custom_property_reads_through_functions(- unresolved.components().as_ref(),- &functions.registry,- &holds_a_value,- )- }- _ => named_custom_property_reads(value)- .unwrap_or_default()- .into_iter()- .map(Arc::from)- .collect(),- };let index = *reads_of_name.entry(name.raw()).or_insert_with(|| {reads.push((name, Vec::new()));reads.len() - 1});- reads[index].1.extend(names);+ let StyleValueData::Unresolved(unresolved) = substituted_tokens(value) else {+ continue;+ };+ if !unresolved.presence().has_any() {+ continue;+ }+ let fly_name = ak::Utf16FlyString::from_utf16(name.to_utf16().as_ref());+ let names = crate::css::custom_properties::custom_properties_a_substitution_reads(+ &resolution_context.inputs,+ &fly_name,+ unresolved,+ &mut environment,+ );+ reads[index].1.extend(names.iter().map(|name| name.raw_identity()));}- let names: Vec<_> = reads.iter().map(|(name, _)| name.to_utf16()).collect();- let index_of_name: HashMap<&[u16], usize> = names- .iter()- .enumerate()- .map(|(index, name)| (name.as_ref(), index))- .collect();// NB: A name nothing writes reads nothing, so no cycle goes through it.let edges: Vec<Vec<usize>> = reads.iter().map(|(_, read)| {read.iter()- .filter_map(|read| index_of_name.get(&**read).copied())+ .filter_map(|read| reads_of_name.get(read).copied()).collect()}).collect();diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 2b963aec97c..79c557e6506 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -8323,7 +8323,14 @@ fn finish_animation_sample(.cast::<crate::css::custom_properties::CustomPropertyStore>().as_ref()};- for name in engine.custom_properties_in_an_animated_cycle(node, cycle_pseudo, inherited) {+ let names_in_a_cycle = engine.custom_properties_in_an_animated_cycle(+ node,+ cycle_pseudo,+ input.stores.base,+ input.stores.inheritance,+ &retained,+ );+ for name in names_in_a_cycle {let value = registry.invalid_at_computed_value_time(&name, inherited);match retained.iter_mut().find(|(animated, _)| *animated == name) {Some((_, animated)) => *animated = value,diff --git a/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-if-and-attr.txt b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-if-and-attr.txtnew file mode 100644index 00000000000..9d60b15ca7d--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-if-and-attr.txt@@ -0,0 +1,15 @@+a condition reads the other property: --p: 0px, --q: 0px+a later condition reads it: --p: 0px, --q: 0px+the branch taken reads it: --p: 0px, --q: 0px+a branch not taken reads it: --p: 1px, --q: 1px+a condition after the one that held reads it: --p: 1px, --q: 1px+an else not taken reads it: --p: 1px, --q: 1px+a function's branch taken reads it: --p: 0px, --q: 0px+an attribute's value reads it: --p: 0px, --q: 0px+an attribute's value reads it as a string: --p: 5px, --q: 5px+a fallback in place of no attribute reads it: --p: 0px, --q: 0px+a fallback beside an attribute reads it: --p: 5px, --q: 5px+a fallback in place of an invalid attribute reads it: --p: 0px, --q: 0px+a fallback in place of no environment variable reads it: --p: 0px, --q: 0px+a fallback beside an inherited value reads it: --p: 7px, --q: 7px+a fallback in place of no inherited value reads it: --p: 0px, --q: 0pxdiff --git a/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-if-and-attr.html b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-if-and-attr.htmlnew file mode 100644index 00000000000..223e9632edc--- /dev/null+++ b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-if-and-attr.html@@ -0,0 +1,74 @@+<!DOCTYPE html>+<style>+@property --p { syntax: "<length>"; inherits: true; initial-value: 0px; }+@property --q { syntax: "<length>"; inherits: true; initial-value: 0px; }+@function --conditional() { result: if(style(--mode: on): var(--q); else: 2px); }+</style>+<body>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ // A keyframe's value takes part in a cycle exactly as the same value declared on the element does.+ const cases = {+ "a condition reads the other property": "if(style(--q: 7px): 1px; else: 2px)",+ "a later condition reads it": "if(media(not all): 1px; style(--q: 7px): 2px; else: 3px)",+ "the branch taken reads it": "if(style(--mode: on): calc(var(--q) + 1px); else: 1px)",+ "a branch not taken reads it": "if(style(--mode: off): calc(var(--q) + 1px); else: 1px)",+ "a condition after the one that held reads it": "if(style(--mode: on): 1px; style(--q: 7px): 2px; else: 3px)",+ "an else not taken reads it": "if(style(--mode: on): 1px; else: calc(var(--q) + 1px))",+ "a function's branch taken reads it": "calc(--conditional() + 1px)",+ "an attribute's value reads it": "calc(attr(data-reads type(<length>)) + 1px)",+ "an attribute's value reads it as a string": "calc(attr(data-length px) + 1px)",+ "a fallback in place of no attribute reads it": "calc(attr(data-none type(<length>), var(--q)) + 1px)",+ "a fallback beside an attribute reads it": "calc(attr(data-length px, var(--q)) + 1px)",+ "a fallback in place of an invalid attribute reads it": "calc(attr(data-invalid px, var(--q)) + 1px)",+ "a fallback in place of no environment variable reads it": "calc(env(no-such-variable, var(--q)) + 1px)",+ "a fallback beside an inherited value reads it": "calc(inherit(--held, var(--q)) + 1px)",+ "a fallback in place of no inherited value reads it": "calc(inherit(--unset, var(--q)) + 1px)",+ };++ document.body.style.setProperty("--held", "6px");+ let css = "";+ const elements = [];+ Object.entries(cases).forEach(([name, value], index) => {+ css += `.declared${index} { --p: ${value}; --q: var(--p); }\n`;+ css += `@keyframes k${index} { from, to { --p: ${value}; } }\n`;+ css += `.paused${index} { --q: var(--p); animation: k${index} 100s paused; }\n`;+ css += `.running${index} { --q: var(--p); animation: k${index} 100s linear; }\n`;+ const add = variant => {+ const element = document.createElement("div");+ element.className = `${variant}${index}`;+ element.style.setProperty("--mode", "on");+ element.dataset.reads = "var(--q)";+ element.dataset.length = "4";+ element.dataset.invalid = "x";+ document.body.append(element);+ return element;+ };+ elements.push({ name, declared: add("declared"), paused: add("paused"), running: add("running") });+ });+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);++ const values = element => {+ const style = getComputedStyle(element);+ return `--p: ${style.getPropertyValue("--p")}, --q: ${style.getPropertyValue("--q")}`;+ };+ elements.forEach(({ paused, running }) => {+ values(paused);+ values(running);+ });+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));++ for (const { name, declared, paused, running } of elements) {+ println(`${name}: ${values(declared)}`);+ if (values(paused) !== values(declared))+ println(` paused differs: ${values(paused)}`);+ if (values(running) !== values(declared))+ println(` running differs: ${values(running)}`);+ }+ done();+ });+</script>