Skip to content

Truly independent web browser

LibWeb: Cache computed element custom property values

Callum Law1f2a37a306a0
diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
index 89f25bca5e7..f95d27f943f 100644
--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
@@ -19,7 +19,7 @@ use std::hash::BuildHasherDefault;
use std::hash::Hasher;
use std::sync::Arc;
-use crate::css::custom_properties::{CustomPropertyStore, finalize_element_custom_property};
+use crate::css::custom_properties::CustomPropertyStore;
use crate::css::parser::value_parser::{
FfiValueParsingContext, FfiValueParsingContextKind, ParseContext, ParseOutcome, parse_css_value_from_source,
};
@@ -404,34 +404,6 @@ impl FfiStyleQueryInputs {
}
}
-/// One unresolved value submitted to the bulk substitution resolver.
-struct UnresolvedStyleValue<'a> {
- property_id: u16,
- /// The custom property the value is declared for, or empty for another property.
- root_custom_property_name: &'a [u16],
- value: &'a RetainedStyleValueData,
- resolve_substitutions: bool,
-}
-
-fn custom_property_needs_resolution(value: &StyleValueData) -> bool {
- matches!(
- value,
- StyleValueData::Unresolved {
- presence_attr: true,
- ..
- } | StyleValueData::Unresolved {
- presence_dashed_function: true,
- ..
- } | StyleValueData::Unresolved { presence_env: true, .. }
- | StyleValueData::Unresolved { presence_if: true, .. }
- | StyleValueData::Unresolved {
- presence_inherit: true,
- ..
- }
- | StyleValueData::Unresolved { presence_var: true, .. }
- )
-}
-
/// Resolves the custom properties `store` declares, finalizing each registered value against
/// `finalization`. Answers the store holding them over the parent's, or none where the element
/// declares nothing that differs from the parent and may reuse its store; and what the registered
@@ -447,26 +419,18 @@ pub(crate) fn resolve_declared_custom_properties(
crate::css::custom_properties::RegisteredValueReads,
) {
let names = &store.declared_names;
- let own_entry = |name_raw: &usize| {
- store
- .own_values
- .get(name_raw)
- .expect("declared custom property must be an own value")
- };
- let inputs: Vec<_> = names
- .iter()
- .map(|name_raw| {
- let entry = own_entry(name_raw);
- UnresolvedStyleValue {
- property_id: crate::css::property_metadata::property_id::CUSTOM,
- root_custom_property_name: &entry.name,
- value: &entry.value,
- resolve_substitutions: custom_property_needs_resolution(entry.value.data()),
- }
- })
- .collect();
- let mut reads = crate::css::custom_properties::RegisteredValueReads::default();
- let outputs = resolve_unresolved_style_values(resolution_context, &inputs, &finalization, &mut reads);
+ let mut environment = crate::css::custom_properties::prepare_var_resolution_environment(
+ resolution_context.attributes,
+ resolution_context.custom_functions,
+ resolution_context.custom_function_scope_identity,
+ resolution_context.custom_function_visibilities,
+ );
+ let (outputs, reads) = crate::css::custom_properties::resolve_element_custom_properties(
+ &resolution_context.inputs,
+ &mut environment,
+ resolution_context.style_query_dependencies.as_deref_mut(),
+ finalization,
+ );
let resolved_parent = resolved_parent_store;
let resolved_values: Vec<_> = names
.iter()
@@ -486,203 +450,3 @@ pub(crate) fn resolve_declared_custom_properties(
/// Sentinel passed when cascading for an element rather than a pseudo-element.
pub(crate) const NO_PSEUDO_ELEMENT: u8 = u8::MAX;
-
-#[allow(clippy::too_many_arguments)]
-fn resolve_cascade_value(
- resolution_context: &mut CascadeResolutionContext,
- resolution_environment: &mut crate::css::custom_properties::VarResolutionEnvironment,
- property_id: u16,
- root_custom_property_name: &[u16],
- unresolved: &StyleValueData,
- final_custom_properties: Option<&HashMap<Vec<u16>, RetainedStyleValueData>>,
- finalization: &crate::css::custom_properties::CustomPropertyFinalization,
- reads: &mut crate::css::custom_properties::RegisteredValueReads,
-) -> RetainedStyleValueData {
- let native_resolution = crate::css::custom_properties::resolve_vars(
- &resolution_context.inputs,
- property_id,
- root_custom_property_name,
- unresolved,
- resolution_environment,
- resolution_context.style_query_dependencies.as_deref_mut(),
- final_custom_properties,
- *finalization,
- Some(reads),
- );
-
- match native_resolution {
- crate::css::custom_properties::NativeVarResolution::Resolved {
- source,
- contains_attr_tainted_values,
- } => {
- let Some(base_context) = resolution_context.inputs.parse_context else {
- return RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid);
- };
- let contains_attr_tainted_values = contains_attr_tainted_values
- || matches!(
- unresolved,
- StyleValueData::Unresolved {
- contains_attr_tainted_values: true,
- ..
- }
- );
- parse_substituted_value(base_context, property_id, &source, contains_attr_tainted_values)
- }
- crate::css::custom_properties::NativeVarResolution::Invalid
- | crate::css::custom_properties::NativeVarResolution::NotHandled => {
- RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid)
- }
- }
-}
-
-fn custom_property_components(inputs: &[UnresolvedStyleValue]) -> (Vec<Vec<u32>>, bool) {
- let mut indices = HashMap::new();
- for (index, input) in inputs.iter().enumerate() {
- indices.insert(input.root_custom_property_name.to_vec(), index as u32);
- }
-
- let mut edges = vec![Vec::new(); inputs.len()];
- let mut has_own_reference = false;
- for (index, input) in inputs.iter().enumerate() {
- let value = input.value.data();
- let Some((references, mut all_references_visible)) = crate::css::style_value::custom_property_references(value)
- else {
- continue;
- };
- if let StyleValueData::Unresolved {
- presence_attr,
- presence_dashed_function,
- presence_if,
- ..
- } = value
- {
- all_references_visible &= !presence_attr && !presence_dashed_function && !presence_if;
- }
- if all_references_visible {
- for reference in references {
- if let Some(target) = indices.get(reference) {
- edges[index].push(*target);
- has_own_reference |= inputs[*target as usize].resolve_substitutions;
- }
- }
- } else {
- edges[index].extend(0..inputs.len() as u32);
- }
- }
-
- let unvisited = u32::MAX;
- let mut discovery_index = vec![unvisited; inputs.len()];
- let mut lowlink = vec![0; inputs.len()];
- let mut on_stack = vec![false; inputs.len()];
- let mut component_stack = Vec::new();
- let mut components = Vec::new();
- let mut next_discovery_index = 0;
- let mut walk_stack: Vec<(u32, usize)> = Vec::new();
-
- for root in 0..inputs.len() as u32 {
- if discovery_index[root as usize] != unvisited {
- continue;
- }
- walk_stack.push((root, 0));
- while let Some(&(node, next_edge)) = walk_stack.last() {
- let node_index = node as usize;
- if next_edge == 0 {
- discovery_index[node_index] = next_discovery_index;
- lowlink[node_index] = next_discovery_index;
- next_discovery_index += 1;
- component_stack.push(node);
- on_stack[node_index] = true;
- }
- if next_edge < edges[node_index].len() {
- let target = edges[node_index][next_edge];
- walk_stack.last_mut().unwrap().1 += 1;
- if discovery_index[target as usize] == unvisited {
- walk_stack.push((target, 0));
- } else if on_stack[target as usize] {
- lowlink[node_index] = lowlink[node_index].min(discovery_index[target as usize]);
- }
- continue;
- }
- if lowlink[node_index] == discovery_index[node_index] {
- let mut component = Vec::new();
- loop {
- let popped = component_stack.pop().expect("active custom-property component");
- on_stack[popped as usize] = false;
- component.push(popped);
- if popped == node {
- break;
- }
- }
- components.push(component);
- }
- walk_stack.pop();
- if let Some(&(parent, _)) = walk_stack.last() {
- lowlink[parent as usize] = lowlink[parent as usize].min(lowlink[node_index]);
- }
- }
- }
- (components, has_own_reference)
-}
-
-/// Resolves and parses custom properties in dependency order, finalizing each component before
-/// later components can read it.
-fn resolve_unresolved_style_values(
- resolution_context: &mut CascadeResolutionContext,
- inputs: &[UnresolvedStyleValue],
- finalization: &crate::css::custom_properties::CustomPropertyFinalization,
- reads: &mut crate::css::custom_properties::RegisteredValueReads,
-) -> Vec<RetainedStyleValueData> {
- let mut outputs: Vec<_> = inputs.iter().map(|_| RetainedStyleValueData::none()).collect();
- let mut resolution_environment = crate::css::custom_properties::prepare_var_resolution_environment(
- resolution_context.attributes,
- resolution_context.custom_functions,
- resolution_context.custom_function_scope_identity,
- resolution_context.custom_function_visibilities,
- );
- let (components, use_final_custom_properties) = custom_property_components(inputs);
- let registry = resolution_context
- .inputs
- .registry
- .unwrap_or_else(|| crate::css::custom_properties::CustomPropertyRegistry::shared_empty());
- let store = resolution_context
- .inputs
- .store
- .expect("declared custom properties have an element store");
- let mut final_custom_properties = HashMap::new();
- for mut component in components {
- component.sort_unstable();
- for &member in &component {
- let input = &inputs[member as usize];
- if !input.resolve_substitutions {
- outputs[member as usize] = input.value.clone();
- continue;
- }
- outputs[member as usize] = resolve_cascade_value(
- resolution_context,
- &mut resolution_environment,
- input.property_id,
- input.root_custom_property_name,
- input.value.data(),
- use_final_custom_properties.then_some(&final_custom_properties),
- finalization,
- reads,
- );
- }
- for &member in &component {
- let index = member as usize;
- let name = inputs[index].root_custom_property_name;
- let substituted = std::mem::replace(&mut outputs[index], RetainedStyleValueData::none());
- outputs[index] = finalize_element_custom_property(
- registry,
- resolution_context.inputs.inheritance_store,
- finalization,
- reads,
- store.declared_names[index],
- name,
- substituted,
- );
- final_custom_properties.insert(name.to_vec(), outputs[index].clone());
- }
- }
- outputs
-}
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
index 3145632aa92..0195f81f685 100644
--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
@@ -939,7 +939,9 @@ struct ASFResolutionContext<'a> {
style_query_dependencies: Option<&'a mut Option<Box<StyleQueryDependencies>>>,
custom_property_finalization: CustomPropertyFinalization<'a>,
registered_value_reads: Option<&'a mut RegisteredValueReads>,
- final_custom_properties: Option<&'a HashMap<Vec<u16>, RetainedStyleValueData>>,
+ element_store: Option<&'a CustomPropertyStore>,
+ element_values: Option<&'a mut HashMap<usize, RetainedStyleValueData>>,
+ substitution_limit_hits: u64,
function_local_scopes: Vec<FunctionLocalScope>,
token_cache: Option<&'a mut CustomPropertyTokenCache>,
}
@@ -1288,18 +1290,33 @@ pub(crate) fn finalize_element_custom_property(
value
}
+#[cfg(test)]
+thread_local! {
+ static CUSTOM_PROPERTY_COMPUTATIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
+}
+
fn compute_element_custom_property(
store: &CustomPropertyStore,
registry: &CustomPropertyRegistry,
name: &[u16],
context: &mut ASFResolutionContext,
recursion_depth: u32,
-) -> Result<(RetainedStyleValueData, bool), ()> {
+) -> Result<RetainedStyleValueData, ()> {
let name_raw = store.own_names[name];
+
+ if let Some(cached) = context.element_values.as_deref().ok_or(())?.get(&name_raw) {
+ return Ok(cached.clone());
+ }
+
+ let limit_hits_before_computation = context.substitution_limit_hits;
+
+ #[cfg(test)]
+ CUSTOM_PROPERTY_COMPUTATIONS.with(|count| count.set(count.get() + 1));
+
let entry = &store.own_values[&name_raw];
let (tokens, includes_substitution, tainted) = cached_tokens_for_custom_property_value(entry.value.data(), context);
- let (value, is_cyclic) = if includes_substitution {
+ let value = if includes_substitution {
let guarded_contexts = GuardedSubstitutionContexts {
contexts: Rc::new(RefCell::new(
context
@@ -1320,6 +1337,7 @@ fn compute_element_custom_property(
uses_attr_tainted_url: false,
style_query_dependencies: context.style_query_dependencies.as_deref_mut(),
registered_value_reads: context.registered_value_reads.as_deref_mut(),
+ element_values: context.element_values.as_deref_mut(),
function_local_scopes: Vec::new(),
token_cache: context.token_cache.as_deref_mut(),
..*context
@@ -1334,9 +1352,9 @@ fn compute_element_custom_property(
Some(SubstitutionContextDependency::Property(name.to_vec(), None)),
);
- let result_is_cyclic = matches!(result, TokenResolution::Cyclic);
+ context.substitution_limit_hits = property_context.substitution_limit_hits;
- let value = match result {
+ match result {
TokenResolution::Resolved(tokens) => crate::css::cascaded_properties::parse_substituted_value(
property_context.parse_context.ok_or(())?,
crate::css::property_metadata::property_id::CUSTOM,
@@ -1347,12 +1365,12 @@ fn compute_element_custom_property(
RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid)
}
TokenResolution::NotHandled => return Err(()),
- };
- (value, result_is_cyclic)
+ }
} else {
- (entry.value.clone(), false)
+ entry.value.clone()
};
- let value = finalize_element_custom_property(
+
+ let finalized_value = finalize_element_custom_property(
registry,
context.inheritance_store,
&context.custom_property_finalization,
@@ -1361,7 +1379,73 @@ fn compute_element_custom_property(
name,
value,
);
- Ok((value, is_cyclic))
+
+ if context.substitution_limit_hits == limit_hits_before_computation {
+ context
+ .element_values
+ .as_deref_mut()
+ .ok_or(())?
+ .insert(name_raw, finalized_value.clone());
+ }
+
+ Ok(finalized_value)
+}
+
+/// Computes the element's declared custom properties, reusing completed values across declarations.
+pub(crate) fn resolve_element_custom_properties(
+ inputs: &VarResolutionInputs,
+ environment: &mut VarResolutionEnvironment,
+ style_query_dependencies: Option<&mut Option<Box<StyleQueryDependencies>>>,
+ finalization: CustomPropertyFinalization,
+) -> (Vec<RetainedStyleValueData>, RegisteredValueReads) {
+ let store = inputs.store.expect("declared custom properties have an element store");
+
+ let mut reads = RegisteredValueReads::default();
+
+ let mut context = ASFResolutionContext {
+ attributes: Some(&environment.attributes),
+ inheritance_store: inputs.inheritance_store,
+ attribute_names_are_ascii_case_insensitive: inputs.attribute_names_are_ascii_case_insensitive,
+ custom_functions: Some(&environment.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),
+ style_query_dependencies,
+ custom_property_finalization: finalization,
+ registered_value_reads: Some(&mut reads),
+ element_store: Some(store),
+ element_values: Some(&mut HashMap::new()),
+ token_cache: Some(&mut environment.token_cache),
+ ..Default::default()
+ };
+
+ let registry = inputs
+ .registry
+ .unwrap_or_else(|| CustomPropertyRegistry::shared_empty());
+
+ let values = store
+ .declared_names
+ .iter()
+ .map(|&name_raw| {
+ let name = &store.own_values[&name_raw].name;
+ match compute_element_custom_property(store, registry, name, &mut context, 0) {
+ Ok(value) => value,
+ Err(()) => finalize_element_custom_property(
+ registry,
+ inputs.inheritance_store,
+ &finalization,
+ context.registered_value_reads.as_deref_mut().unwrap(),
+ name_raw,
+ name,
+ RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid),
+ ),
+ }
+ })
+ .collect();
+
+ (values, reads)
}
fn computed_property_tokens(value: &RetainedStyleValueData, context: &mut ASFResolutionContext) -> TokenResolution {
@@ -1622,20 +1706,6 @@ fn resolve_custom_property_with_lookup(
if lookup == CustomPropertyLookup::Normal && context.guarded_contexts.mark_cycle_if_guarded(&substitution_context) {
return TokenResolution::Cyclic;
}
- if lookup == CustomPropertyLookup::Normal
- && let Some(final_values) = context.final_custom_properties
- && let Some(data) = final_values.get(name).and_then(RetainedStyleValueData::optional_data)
- {
- if matches!(data, StyleValueData::GuaranteedInvalid) {
- return TokenResolution::Invalid;
- }
- let (tokens, includes_substitution, contains_attr_tainted_values) =
- cached_tokens_for_custom_property_value(data, context);
- context.contains_attr_tainted_values |= contains_attr_tainted_values;
- if !includes_substitution {
- return TokenResolution::Resolved(tokens.to_vec());
- }
- }
let registration = registry.and_then(|registry| registry.registrations.get(name));
let entry_and_owner = store.and_then(|store| {
if lookup == CustomPropertyLookup::ExplicitInheritance {
@@ -1652,18 +1722,20 @@ fn resolve_custom_property_with_lookup(
.map_or(TokenResolution::Invalid, TokenResolution::from_source);
};
if lookup == CustomPropertyLookup::Normal
- && context.registered_value_reads.is_some()
+ && context.element_store.is_some_and(|store| std::ptr::eq(store, owner))
+ && owner.declared_names.contains(&owner.own_names[name])
&& store.is_some_and(|store| std::ptr::eq(store, owner))
{
- return match compute_element_custom_property(
+ let computed_value = compute_element_custom_property(
owner,
registry.unwrap_or_else(|| CustomPropertyRegistry::shared_empty()),
name,
context,
recursion_depth + 1,
- ) {
- Ok((value, true)) if matches!(value.data(), StyleValueData::GuaranteedInvalid) => TokenResolution::Cyclic,
- Ok((value, _)) => computed_property_tokens(&value, context),
+ );
+
+ return match computed_value {
+ Ok(value) => computed_property_tokens(&value, context),
Err(()) => TokenResolution::NotHandled,
};
}
@@ -1676,7 +1748,10 @@ fn resolve_custom_property_with_lookup(
// https://drafts.csswg.org/css-cascade-5/#inheritance
// The inherited value of a property on an element is the computed value of the property on the element’s parent
// element.
- if lookup == CustomPropertyLookup::ExplicitInheritance || store.is_some_and(|store| !std::ptr::eq(store, owner)) {
+ if context.element_store.is_some()
+ || lookup == CustomPropertyLookup::ExplicitInheritance
+ || store.is_some_and(|store| !std::ptr::eq(store, owner))
+ {
return TokenResolution::Resolved(source.to_vec());
}
let result = if includes_var {
@@ -3172,6 +3247,7 @@ fn substitute_tokens(
recursion_depth: u32,
) -> TokenResolution {
if recursion_depth > MAX_SUBSTITUTION_RECURSION_DEPTH {
+ context.substitution_limit_hits += 1;
return TokenResolution::Invalid;
}
@@ -3262,6 +3338,7 @@ fn substitute_tokens(
}
let remaining_token_count = tokens.len() - close_index - 1;
if output.len() + remaining_token_count > MAX_SUBSTITUTED_TOKEN_COUNT {
+ context.substitution_limit_hits += 1;
return TokenResolution::Invalid;
}
index = close_index + 1;
@@ -3372,7 +3449,6 @@ pub(crate) struct VarResolutionInputs<'a> {
pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
}
-#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_vars(
inputs: &VarResolutionInputs,
property_id: u16,
@@ -3380,9 +3456,6 @@ pub(crate) fn resolve_vars(
value_data: &StyleValueData,
environment: &mut VarResolutionEnvironment,
style_query_dependencies: Option<&mut Option<Box<StyleQueryDependencies>>>,
- final_custom_properties: Option<&HashMap<Vec<u16>, RetainedStyleValueData>>,
- custom_property_finalization: CustomPropertyFinalization,
- registered_value_reads: Option<&mut RegisteredValueReads>,
) -> NativeVarResolution {
let VarResolutionInputs {
store,
@@ -3422,9 +3495,6 @@ pub(crate) fn resolve_vars(
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,
- custom_property_finalization,
- registered_value_reads,
token_cache: Some(token_cache),
..Default::default()
};
@@ -3801,6 +3871,92 @@ mod tests {
TokenResolution::Invalid
));
}
+
+ fn build_custom_property_store(
+ parse_context: &ParseContext,
+ properties: &[(&str, &str)],
+ ) -> Arc<CustomPropertyStore> {
+ let entries = properties
+ .iter()
+ .enumerate()
+ .map(|(name_raw, (name, source))| {
+ let source = utf16(source);
+ let values = consume_a_list_of_component_values(tokenize_for_parser(&source)).unwrap();
+ let crate::css::parser::value_parser::ParseOutcome::Parsed(value) =
+ crate::css::parser::value_parser::parse_css_value_with_source(
+ parse_context,
+ crate::css::property_metadata::property_id::CUSTOM,
+ &values,
+ &source,
+ &source,
+ )
+ else {
+ panic!("custom property value should parse");
+ };
+ (
+ name_raw,
+ CustomPropertyEntry {
+ _name: RetainedUtf16FlyString::none(),
+ name: utf16(name).into(),
+ value: RetainedStyleValueData::from_arc(value),
+ important: false,
+ },
+ )
+ })
+ .collect();
+
+ CustomPropertyStore::child(None, entries)
+ }
+
+ #[test]
+ fn element_custom_properties_are_computed_once_for_repeated_references() {
+ let registry = CustomPropertyRegistry::empty();
+
+ let random_index = RandomFunctionIndex::default();
+ let parse_context = registry.parse_context(&random_index);
+
+ // Put the consumer first so --shared is computed on demand. References inside if()
+ // were not visible to the dependency ordering used before completed values were cached.
+ let definitions = [
+ ("--consumer", "if(else: var(--shared) var(--shared))"),
+ ("--shared", "if(else: 1px)"),
+ ];
+
+ let store = build_custom_property_store(&parse_context, &definitions);
+
+ let inputs = VarResolutionInputs {
+ store: Some(&store),
+ inheritance_store: None,
+ registry: Some(&registry),
+ parse_context: Some(&parse_context),
+ media_environment: None,
+ attribute_names_are_ascii_case_insensitive: false,
+ style_query_inputs: None,
+ };
+
+ let mut environment = prepare_var_resolution_environment(&[], &[], 0, &[]);
+
+ CUSTOM_PROPERTY_COMPUTATIONS.with(|count| count.set(0));
+
+ let (values, _) =
+ resolve_element_custom_properties(&inputs, &mut environment, None, CustomPropertyFinalization::default());
+
+ let sources: Vec<_> = values
+ .iter()
+ .map(|value| {
+ String::from_utf16(&crate::css::serialize::serialize_resolved_style_value_to_utf16(
+ value.data(),
+ ))
+ .unwrap()
+ .trim()
+ .to_owned()
+ })
+ .collect();
+ assert_eq!(sources, ["1px 1px", "1px"]);
+ CUSTOM_PROPERTY_COMPUTATIONS.with(|count| {
+ assert_eq!(count.get(), 2, "each declaration should be computed only once");
+ });
+ }
}
/// A document's registry of custom properties, which the document holds a reference to: a style
diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
index 19aeca73af3..29631ce9748 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
@@ -2290,9 +2290,6 @@ fn substitute_against_stores(
written.data(),
&mut resolution_environment,
style_query_references.as_deref_mut(),
- None,
- Default::default(),
- None,
);
let invalid = || RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid);
match resolution {
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 29e7c6c499c..da1fd765090 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -180,6 +180,7 @@ RENDER_STATE_ALLOWED = {
**render_state_entries(
TEST_ONLY,
[
+ "css/custom_properties.rs:CUSTOM_PROPERTY_COMPUTATIONS",
"css/declaration_block.rs:DECLARATION_OWNER_ALLOCATIONS",
"css/descriptor_block.rs:DESCRIPTOR_OWNER_ALLOCATIONS",
"css/rule.rs:RULE_OWNER_ALLOCATIONS",
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-cache-recursion-limit.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-cache-recursion-limit.txt
new file mode 100644
index 00000000000..5e699e79ef5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-cache-recursion-limit.txt
@@ -0,0 +1 @@
+PASS: shallow reads resolve in every declaration order
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-function-inheritance-cache.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-function-inheritance-cache.txt
new file mode 100644
index 00000000000..1db8ef7ecee
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-function-inheritance-cache.txt
@@ -0,0 +1,3 @@
+direct and inherited reads: 2px 2px
+after source changes: 3px 3px
+cyclic property and independent call: fallback 1px
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-cache-recursion-limit.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-cache-recursion-limit.html
new file mode 100644
index 00000000000..d20b4bbfecc
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-cache-recursion-limit.html
@@ -0,0 +1,39 @@
+<!doctype html>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ // A deep read can hit the substitution recursion limit while computing --consumer.
+ // That failure must not be cached: computing --consumer on its own still succeeds.
+ // Sweep around the limit of 64, allowing for the calls made by var() and if().
+ for (let depth = 48; depth <= 72; ++depth) {
+ const declarations = [
+ ["--deep", "calc(".repeat(depth) + "var(--consumer)" + ")".repeat(depth)],
+ ["--consumer", "var(--value)"],
+ ["--value", "if(else: 1px)"],
+ ];
+ // Check every declaration order so an earlier shallow read cannot hide the failure.
+ for (const declarationOrder of [
+ [0, 1, 2],
+ [0, 2, 1],
+ [1, 0, 2],
+ [1, 2, 0],
+ [2, 0, 1],
+ [2, 1, 0],
+ ]) {
+ const element = document.createElement("div");
+ for (const index of declarationOrder) {
+ element.style.setProperty(...declarations[index]);
+ }
+ document.body.append(element);
+ const value = getComputedStyle(element).getPropertyValue("--consumer").trim();
+ element.remove();
+ if (value !== "1px") {
+ const names = declarationOrder.map(index => declarations[index][0]).join(", ");
+ println(`FAIL: depth ${depth}, declaration order [${names}]: --consumer was ${JSON.stringify(value)}, expected "1px"`);
+ return;
+ }
+ }
+ }
+ println("PASS: shallow reads resolve in every declaration order");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-function-inheritance-cache.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-function-inheritance-cache.html
new file mode 100644
index 00000000000..9578c7f75e8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-function-inheritance-cache.html
@@ -0,0 +1,38 @@
+<!doctype html>
+<style>
+ @function --read-element-value(--direct) {
+ result: if(style(--direct: yes): var(--value); else: var(--cached));
+ }
+ @function --read-cyclic-value() {
+ result: var(--cyclic, 1px);
+ }
+ #target {
+ --value: 2px;
+ --cached: --read-element-value(yes);
+ --consumer: var(--cached) --read-element-value(no);
+ }
+ #cycle {
+ --cyclic: --read-cyclic-value();
+ --consumer: var(--cyclic, fallback) --read-cyclic-value();
+ }
+</style>
+<div id="target"></div>
+<div id="cycle"></div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ const target = document.getElementById("target");
+ // The function inherits the completed --cached value. Repeated reads should reuse
+ // that value, including after the source property changes.
+ println(`direct and inherited reads: ${getComputedStyle(target).getPropertyValue("--consumer").trim()}`);
+ target.style.setProperty("--value", "3px");
+ println(`after source changes: ${getComputedStyle(target).getPropertyValue("--consumer").trim()}`);
+
+ // --cyclic is guaranteed-invalid. Reading that completed value must allow the
+ // independent function call to use its fallback without making the consumer cyclic.
+ const cycle = document.getElementById("cycle");
+ println(
+ `cyclic property and independent call: ${getComputedStyle(cycle).getPropertyValue("--consumer").trim()}`
+ );
+ });
+</script>