Skip to content

Truly independent web browser

LibWeb: Resolve custom property substitutions over Rust types

Andreas Kling5afb9f22ca33
diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
index 3306363306b..e1da8f5a840 100644
--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
@@ -20,8 +20,6 @@ use std::hash::BuildHasherDefault;
use std::hash::Hasher;
use crate::css::custom_properties::CustomPropertyStore;
-use crate::css::ffi_support::FfiUtf16View;
-use crate::css::parser::query_parser::FfiMediaEnvironment;
use crate::css::parser::value_parser::{
FfiValueParsingContext, FfiValueParsingContextKind, ParseContext, ParseOutcome, parse_css_value_from_source,
};
@@ -465,45 +463,16 @@ pub(crate) fn parse_substituted_source(
parse_css_value_from_source(&context, property_id, source)
}
-/// One winning custom-property declaration, reported in first-declaration order.
-#[repr(C)]
-pub struct FfiCascadedCustomProperty {
- pub name_raw: usize,
- pub important: bool,
- pub data: *const c_void,
-}
-
-/// Main-thread services used while resolving substituted values inside the Rust cascade.
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiCascadeResolutionContext {
- pub parse_context: *const c_void,
- pub media_environment: *const c_void,
- pub load_media_environment: Option<unsafe extern "C" fn(*mut c_void) -> *const c_void>,
- pub custom_property_store: *const c_void,
- pub inheritance_custom_property_store: *const c_void,
- pub custom_property_registry: *const c_void,
- pub root_custom_property_name: FfiUtf16View,
- pub attributes: *const crate::css::custom_properties::FfiSubstitutionAttribute,
- pub attribute_count: usize,
- pub attribute_names_are_ascii_case_insensitive: bool,
- pub custom_functions: *const crate::css::custom_properties::FfiSubstitutionFunctionDefinition,
- pub custom_function_count: usize,
- pub custom_function_scope_identity: usize,
- pub custom_function_visibilities: *const crate::css::custom_properties::FfiSubstitutionFunctionVisibility,
- pub custom_function_visibility_count: usize,
- pub callback_context: *mut c_void,
- pub install_custom_properties: Option<
- unsafe extern "C" fn(*mut c_void, *const FfiCascadedCustomProperty, usize, *mut *const c_void) -> *const c_void,
- >,
- /// What a style query resolves against, or null to have `load_style_query_inputs` load it
- /// from the callback context the first time a query is evaluated.
- pub style_query_inputs: *const FfiStyleQueryInputs,
- pub load_style_query_inputs: Option<unsafe extern "C" fn(*mut c_void) -> *const FfiStyleQueryInputs>,
- /// Null, or where the custom properties style queries read are kept: null until the first,
- /// then a handle for `rust_style_query_dependencies_take`.
- pub style_query_dependencies: *mut *mut c_void,
- pub note_substitution: Option<unsafe extern "C" fn(*mut c_void, *const c_void)>,
+/// What resolving substituted values inside the Rust cascade reads beyond the values themselves.
+pub(crate) struct CascadeResolutionContext<'a> {
+ pub(crate) inputs: crate::css::custom_properties::VarResolutionInputs<'a>,
+ pub(crate) attributes: &'a [crate::css::custom_properties::SubstitutionAttribute<'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.
+ 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
@@ -531,68 +500,12 @@ impl FfiStyleQueryInputs {
}
/// One unresolved value submitted to the bulk substitution resolver.
-#[repr(C)]
-pub struct FfiUnresolvedStyleValue {
- pub property_id: u16,
- pub root_custom_property_name: FfiUtf16View,
- pub data: *const c_void,
- pub resolve_substitutions: bool,
-}
-
-/// One retained value produced by the bulk substitution resolver.
-#[repr(C)]
-pub struct FfiResolvedStyleValue {
- pub data: *const c_void,
-}
-
-#[repr(C)]
-pub struct FfiCustomPropertyResolutionStats {
- pub final_value_hits: u64,
- pub final_value_misses: u64,
- pub cycle_participants: u64,
- /// Whether computing a registered value resolved a viewport-relative length.
- pub depends_on_viewport_metrics: bool,
- /// Whether a registered value did not compute against the element's inputs, and took its
- /// invalid fallback instead.
- pub left_a_value_uncomputed: bool,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiCustomPropertyDriveInput {
- pub store: *const c_void,
- pub resolved_parent_store: *const c_void,
- pub reuse_resolved_parent_if_empty: bool,
- pub resolution_context: *const FfiCascadeResolutionContext,
- /// What a registered value computes against: the element's lengths as its style computes them
- /// after line-height, null where it declares no registered name; the facts its longhands are
- /// computed against, or null; and the color scheme its colors resolve with.
- pub finalization_length_resolution_context: *const crate::css::style_compute::FfiLengthResolutionContext,
- pub finalization_environment: *const crate::css::style_compute::FfiStyleComputationEnvironment,
- pub finalization_color_scheme: u8,
- /// Draws the random base value of a random caching key a registered value holds only once
- /// substituted, which the host could not draw beforehand; none where nothing may be drawn.
- pub draw_random_base_value: Option<unsafe extern "C" fn(*mut c_void, *const u16, usize, bool) -> f64>,
- pub random_base_context: *mut c_void,
-}
-
-#[repr(C)]
-pub struct FfiResolvedCustomProperty {
- pub name_raw: usize,
- pub important: bool,
- /// Transfers one strong style-value reference to C++.
- pub data: *const c_void,
-}
-
-#[repr(C)]
-pub struct FfiResolvedCustomProperties {
- pub properties: *const FfiResolvedCustomProperty,
- pub count: usize,
- pub did_resolve: bool,
- /// Transfers one strong custom-property store reference to C++.
- pub rust_store: *const c_void,
- pub stats: FfiCustomPropertyResolutionStats,
- pub storage: *mut c_void,
+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 {
@@ -614,237 +527,118 @@ fn custom_property_needs_resolution(value: &StyleValueData) -> bool {
)
}
-/// What the drive finalizes each declared value with: the store declaring the values, in the
-/// order of `names`, the registry and the environment inherited, and the element's finalization
-/// inputs.
-struct CustomPropertyFinalizerContext<'a> {
- store: &'a CustomPropertyStore,
- names: &'a [usize],
- registry: &'a crate::css::custom_properties::CustomPropertyRegistry,
- inherited: Option<&'a CustomPropertyStore>,
- finalization: crate::css::custom_properties::CustomPropertyFinalization<'a>,
- reads: Cell<crate::css::custom_properties::RegisteredValueReads>,
- left_a_value_uncomputed: Cell<bool>,
-}
-
-unsafe extern "C" fn finalize_custom_property_component(
- context: *mut c_void,
- members: *const u32,
- member_count: usize,
- outputs: *mut FfiResolvedStyleValue,
-) {
- let context = unsafe { &*context.cast::<CustomPropertyFinalizerContext>() };
- for &member in unsafe { std::slice::from_raw_parts(members, member_count) } {
- let name_raw = context.names[member as usize];
- let name = &context
- .store
- .own_values
- .get(&name_raw)
- .expect("declared custom property must be an own value")
- .name;
- // SAFETY: The resolver hands each member's output over with one transferred reference,
- // and takes one back.
- let output = unsafe { &mut *outputs.add(member as usize) };
- let substituted = unsafe { RetainedStyleValueData::from_retained_pointer(output.data.cast()) };
- let (finalized, reads) = context
- .registry
- .finalize_custom_property_value(context.inherited, name_raw, name, substituted, &context.finalization)
- .unwrap_or_else(|fallback| {
- context.left_a_value_uncomputed.set(true);
- (fallback, Default::default())
- });
- let mut all_reads = context.reads.get();
- all_reads |= reads;
- context.reads.set(all_reads);
- output.data = std::sync::Arc::into_raw(finalized.into_arc()).cast();
- }
-}
-
-/// What `drive_custom_property_resolution` resolves, finalizing against `finalization` rather than
-/// what `input` says, and what the registered values read as they computed.
+/// Resolves the custom properties `store` declares, finalizing each registered value against
+/// `finalization`. Answers the store holding them over the parent's, which transfers one strong
+/// reference to the caller, or null where the element declares nothing that differs from the
+/// parent and may reuse its store; and what the registered values read as they computed.
///
/// # Safety
-/// As for `drive_custom_property_resolution`.
+/// `resolved_parent_store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
pub(crate) unsafe fn resolve_declared_custom_properties(
- input: &FfiCustomPropertyDriveInput,
+ store: &CustomPropertyStore,
+ resolved_parent_store: *const c_void,
+ reuse_resolved_parent_if_empty: bool,
+ resolution_context: &mut CascadeResolutionContext,
finalization: crate::css::custom_properties::CustomPropertyFinalization<'_>,
-) -> (
- FfiResolvedCustomProperties,
- crate::css::custom_properties::RegisteredValueReads,
-) {
- let store = unsafe { &*input.store.cast::<CustomPropertyStore>() };
+) -> (*const c_void, crate::css::custom_properties::RegisteredValueReads) {
let names = &store.declared_names;
- let mut inputs = Vec::with_capacity(names.len());
- for name_raw in names {
- let entry = store
+ let own_entry = |name_raw: &usize| {
+ store
.own_values
.get(name_raw)
- .expect("declared custom property must be an own value");
- inputs.push(FfiUnresolvedStyleValue {
- property_id: crate::css::property_metadata::property_id::CUSTOM,
- root_custom_property_name: FfiUtf16View {
- ascii: std::ptr::null(),
- utf16: entry.name.as_ptr(),
- length: entry.name.len(),
- },
- data: entry.value.pointer().cast(),
- resolve_substitutions: custom_property_needs_resolution(entry.value.data()),
- });
- }
- let mut outputs: Vec<FfiResolvedStyleValue> = names
+ .expect("declared custom property must be an own value")
+ };
+ let inputs: Vec<_> = names
.iter()
- .map(|_| FfiResolvedStyleValue { data: std::ptr::null() })
+ .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();
- // SAFETY: The resolution context and what it names are live for the call.
- let resolution_context = unsafe { &*input.resolution_context };
- let mut finalizer_context = CustomPropertyFinalizerContext {
- store,
- names,
- registry: unsafe {
- resolution_context
- .custom_property_registry
- .cast::<crate::css::custom_properties::CustomPropertyRegistry>()
- .as_ref()
+ let registry = resolution_context
+ .inputs
+ .registry
+ .unwrap_or_else(|| crate::css::custom_properties::CustomPropertyRegistry::shared_empty());
+ let inherited = resolution_context.inputs.inheritance_store;
+ let mut reads = crate::css::custom_properties::RegisteredValueReads::default();
+ let mut finalize_component = |members: &[u32], outputs: &mut [RetainedStyleValueData]| {
+ for &member in members {
+ let name_raw = names[member as usize];
+ let substituted = std::mem::replace(&mut outputs[member as usize], RetainedStyleValueData::none());
+ let (finalized, value_reads) = registry
+ .finalize_custom_property_value(
+ inherited,
+ name_raw,
+ &own_entry(&name_raw).name,
+ substituted,
+ &finalization,
+ )
+ .unwrap_or_else(|fallback| (fallback, Default::default()));
+ reads |= value_reads;
+ outputs[member as usize] = finalized;
}
- .unwrap_or_else(crate::css::custom_properties::CustomPropertyRegistry::shared_empty),
- inherited: unsafe {
- resolution_context
- .inheritance_custom_property_store
- .cast::<CustomPropertyStore>()
- .as_ref()
- },
- finalization,
- reads: Cell::default(),
- left_a_value_uncomputed: Cell::new(false),
};
- let mut stats = unsafe {
- resolve_unresolved_style_values(
- input.resolution_context,
- inputs.as_ptr(),
- inputs.len(),
- outputs.as_mut_ptr(),
- std::ptr::from_mut(&mut finalizer_context).cast(),
- Some(finalize_custom_property_component),
- )
- };
- let reads = finalizer_context.reads.get();
- stats.depends_on_viewport_metrics = reads.viewport;
- stats.left_a_value_uncomputed = finalizer_context.left_a_value_uncomputed.get();
- let resolved_parent = if input.resolved_parent_store.is_null() {
- None
- } else {
- Some(unsafe { &*input.resolved_parent_store.cast::<CustomPropertyStore>() })
- };
- let mut resolved_values = Vec::with_capacity(names.len());
- let properties: Vec<FfiResolvedCustomProperty> = names
+ let outputs = resolve_unresolved_style_values(resolution_context, &inputs, Some(&mut finalize_component));
+ // SAFETY: Guaranteed by the caller.
+ let resolved_parent = unsafe { resolved_parent_store.cast::<CustomPropertyStore>().as_ref() };
+ let resolved_values: Vec<_> = names
.iter()
.zip(outputs)
- .filter_map(|(name_raw, output)| {
- let entry = store
- .own_values
- .get(name_raw)
- .expect("declared custom property must be an own value");
- let value = unsafe { RetainedStyleValueData::from_retained_pointer(output.data.cast()) };
- if resolved_parent.is_some_and(|parent| parent.value_matches(*name_raw, value.data())) {
- return None;
- }
- let property = FfiResolvedCustomProperty {
- name_raw: *name_raw,
- important: entry.important,
- data: unsafe { crate::css::style_value::retain_style_value(value.pointer()) }.cast(),
- };
- resolved_values.push((*name_raw, value));
- Some(property)
+ .filter(|(name_raw, value)| {
+ !resolved_parent.is_some_and(|parent| parent.value_matches(**name_raw, value.data()))
})
+ .map(|(name_raw, value)| (*name_raw, value))
.collect();
- let rust_store = if properties.is_empty() && input.reuse_resolved_parent_if_empty {
+ let rust_store = if resolved_values.is_empty() && reuse_resolved_parent_if_empty {
std::ptr::null()
} else {
- unsafe { store.resolved_child(input.resolved_parent_store, resolved_values) }
- };
- let properties = properties.into_boxed_slice();
- let count = properties.len();
- let storage = Box::into_raw(properties);
- let resolved = FfiResolvedCustomProperties {
- properties: storage.cast::<FfiResolvedCustomProperty>(),
- count,
- did_resolve: true,
- rust_store,
- stats,
- storage: storage.cast(),
+ // SAFETY: Guaranteed by the caller.
+ unsafe { store.resolved_child(resolved_parent_store, resolved_values) }
};
- (resolved, reads)
-}
-
-/// # Safety
-/// `storage` and `count` must identify a live custom-property result batch.
-pub(crate) unsafe fn destroy_resolved_custom_properties(storage: *mut c_void, count: usize) {
- drop(unsafe {
- Box::from_raw(std::ptr::slice_from_raw_parts_mut(
- storage.cast::<FfiResolvedCustomProperty>(),
- count,
- ))
- });
+ (rust_store, reads)
}
/// Sentinel passed when cascading for an element rather than a pseudo-element.
pub(crate) const NO_PSEUDO_ELEMENT: u8 = u8::MAX;
#[allow(clippy::arc_with_non_send_sync)]
-pub(crate) fn resolve_cascade_value(
- resolution_context: &FfiCascadeResolutionContext,
+fn resolve_cascade_value(
+ resolution_context: &mut CascadeResolutionContext,
resolution_environment: Option<&mut crate::css::custom_properties::VarResolutionEnvironment>,
property_id: u16,
- unresolved_data: *const c_void,
- final_custom_properties: Option<&HashMap<Vec<u16>, *const c_void>>,
+ root_custom_property_name: &[u16],
+ unresolved: &StyleValueData,
+ final_custom_properties: Option<&HashMap<Vec<u16>, RetainedStyleValueData>>,
) -> RetainedStyleValueData {
let native_resolution = match resolution_environment {
- Some(resolution_environment) => unsafe {
- let parse_context = resolution_context.parse_context.cast::<ParseContext>().as_ref();
- let media_environment = resolution_context
- .media_environment
- .cast::<FfiMediaEnvironment>()
- .as_ref();
- crate::css::custom_properties::resolve_vars(
- resolution_context.custom_property_store,
- resolution_context.inheritance_custom_property_store,
- resolution_context.custom_property_registry,
- parse_context,
- media_environment,
- resolution_context.load_media_environment,
- property_id,
- resolution_context.root_custom_property_name,
- unresolved_data,
- resolution_environment,
- resolution_context.attribute_names_are_ascii_case_insensitive,
- resolution_context.callback_context,
- resolution_context.style_query_inputs.as_ref(),
- resolution_context.load_style_query_inputs,
- resolution_context
- .style_query_dependencies
- .cast::<Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>()
- .as_mut(),
- final_custom_properties,
- )
- },
+ Some(resolution_environment) => 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,
+ ),
None => crate::css::custom_properties::NativeVarResolution::NotHandled,
};
- if let Some(note_substitution) = resolution_context.note_substitution {
- unsafe { note_substitution(resolution_context.callback_context, unresolved_data) };
- }
let parsed = match native_resolution {
crate::css::custom_properties::NativeVarResolution::Resolved {
source,
contains_attr_tainted_values,
} => {
- let Some(base_context) = (unsafe { resolution_context.parse_context.cast::<ParseContext>().as_ref() })
- else {
+ 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!(
- unsafe { &*unresolved_data.cast::<StyleValueData>() },
+ unresolved,
StyleValueData::Unresolved {
contains_attr_tainted_values: true,
..
@@ -870,18 +664,16 @@ pub(crate) fn resolve_cascade_value(
RetainedStyleValueData::from_arc(parsed)
}
-fn custom_property_components(inputs: &[FfiUnresolvedStyleValue]) -> (Vec<Vec<u32>>, u64, bool) {
+fn custom_property_components(inputs: &[UnresolvedStyleValue]) -> (Vec<Vec<u32>>, bool) {
let mut indices = HashMap::new();
for (index, input) in inputs.iter().enumerate() {
- if let Some(name) = unsafe { input.root_custom_property_name.to_utf16() } {
- indices.insert(name, index as u32);
- }
+ 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 = unsafe { &*input.data.cast::<StyleValueData>() };
+ let value = input.value.data();
let Some((references, mut all_references_visible)) = crate::css::style_value::custom_property_references(value)
else {
continue;
@@ -913,7 +705,6 @@ fn custom_property_components(inputs: &[FfiUnresolvedStyleValue]) -> (Vec<Vec<u3
let mut on_stack = vec![false; inputs.len()];
let mut component_stack = Vec::new();
let mut components = Vec::new();
- let mut cycle_participants = 0;
let mut next_discovery_index = 0;
let mut walk_stack: Vec<(u32, usize)> = Vec::new();
@@ -951,9 +742,6 @@ fn custom_property_components(inputs: &[FfiUnresolvedStyleValue]) -> (Vec<Vec<u3
break;
}
}
- if component.len() > 1 || edges[component[0] as usize].contains(&component[0]) {
- cycle_participants += component.len() as u64;
- }
components.push(component);
}
walk_stack.pop();
@@ -962,55 +750,31 @@ fn custom_property_components(inputs: &[FfiUnresolvedStyleValue]) -> (Vec<Vec<u3
}
}
}
- (
- components,
- if has_own_reference { cycle_participants } else { 0 },
- has_own_reference,
- )
-}
-
-/// Resolves and parses unresolved values outside the longhand cascade. When a
-/// finalizer is supplied, custom properties are resolved in dependency order
-/// and each component is finalized before later components can read it.
-///
-/// # Safety
-/// Every pointer must remain valid for this call. `outputs` must have room for
-/// `input_count` entries, and a finalizer must replace each component output
-/// with a live style value pointer before returning.
-unsafe fn resolve_unresolved_style_values(
- resolution_context: *const FfiCascadeResolutionContext,
- inputs: *const FfiUnresolvedStyleValue,
- input_count: usize,
- outputs: *mut FfiResolvedStyleValue,
- finalizer_context: *mut c_void,
- finalize_component: Option<unsafe extern "C" fn(*mut c_void, *const u32, usize, *mut FfiResolvedStyleValue)>,
-) -> FfiCustomPropertyResolutionStats {
- let resolution_context = unsafe { *resolution_context };
- let inputs = if input_count == 0 {
- &[]
- } else {
- unsafe { std::slice::from_raw_parts(inputs, input_count) }
- };
- let outputs = if input_count == 0 {
- &mut []
- } else {
- unsafe { std::slice::from_raw_parts_mut(outputs, input_count) }
- };
- let mut resolution_environment = unsafe {
- crate::css::custom_properties::prepare_var_resolution_environment(
- resolution_context.attributes,
- resolution_context.attribute_count,
- resolution_context.custom_functions,
- resolution_context.custom_function_count,
- resolution_context.custom_function_scope_identity,
- resolution_context.custom_function_visibilities,
- resolution_context.custom_function_visibility_count,
- )
- };
- let (components, cycle_participants, use_final_custom_properties) = if finalize_component.is_some() {
+ (components, has_own_reference)
+}
+
+/// Finalizes the values of one component of custom properties, by their indices among the outputs.
+type FinalizeComponent<'a> = dyn FnMut(&[u32], &mut [RetainedStyleValueData]) + 'a;
+
+/// Resolves and parses unresolved values outside the longhand cascade, one output per input. When
+/// a finalizer is supplied, custom properties are resolved in dependency order and each component
+/// is finalized before later components can read it.
+fn resolve_unresolved_style_values(
+ resolution_context: &mut CascadeResolutionContext,
+ inputs: &[UnresolvedStyleValue],
+ mut finalize_component: Option<&mut FinalizeComponent>,
+) -> 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) = if finalize_component.is_some() {
custom_property_components(inputs)
} else {
- ((0..input_count as u32).map(|index| vec![index]).collect(), 0, false)
+ ((0..inputs.len() as u32).map(|index| vec![index]).collect(), false)
};
let mut final_custom_properties = HashMap::new();
for mut component in components {
@@ -1018,47 +782,27 @@ unsafe fn resolve_unresolved_style_values(
for &member in &component {
let input = &inputs[member as usize];
if !input.resolve_substitutions {
- outputs[member as usize].data =
- unsafe { crate::css::style_value::retain_style_value(input.data.cast::<StyleValueData>()).cast() };
+ outputs[member as usize] = input.value.clone();
continue;
}
- let mut member_context = resolution_context;
- member_context.root_custom_property_name = input.root_custom_property_name;
- let resolved = resolve_cascade_value(
- &member_context,
+ outputs[member as usize] = resolve_cascade_value(
+ resolution_context,
resolution_environment.as_mut(),
input.property_id,
- input.data,
+ input.root_custom_property_name,
+ input.value.data(),
use_final_custom_properties.then_some(&final_custom_properties),
);
- outputs[member as usize].data = resolved.pointer().cast();
- std::mem::forget(resolved);
}
- if let Some(finalize_component) = finalize_component {
- unsafe {
- finalize_component(
- finalizer_context,
- component.as_ptr(),
- component.len(),
- outputs.as_mut_ptr(),
- );
- };
+ if let Some(finalize_component) = finalize_component.as_deref_mut() {
+ finalize_component(&component, &mut outputs);
for &member in &component {
- let name = unsafe { inputs[member as usize].root_custom_property_name.to_utf16() }
- .expect("custom-property resolution input name");
- final_custom_properties.insert(name, outputs[member as usize].data);
+ final_custom_properties.insert(
+ inputs[member as usize].root_custom_property_name.to_vec(),
+ outputs[member as usize].clone(),
+ );
}
}
}
- FfiCustomPropertyResolutionStats {
- final_value_hits: resolution_environment
- .as_ref()
- .map_or(0, |environment| environment.final_value_hits()),
- final_value_misses: resolution_environment
- .as_ref()
- .map_or(0, |environment| environment.final_value_misses()),
- cycle_participants,
- depends_on_viewport_metrics: false,
- left_a_value_uncomputed: false,
- }
+ outputs
}
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
index 57cd4e23ba4..6ef784b7390 100644
--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
@@ -198,25 +198,24 @@ pub struct FfiCustomPropertyRegistryContext {
pub document_base_url_length: usize,
}
-#[repr(C)]
-pub struct FfiSubstitutionAttribute {
- pub name: FfiUtf16View,
- pub value: FfiUtf16View,
+/// One of an element's attributes an `attr()` reads: its local name, and its value's text.
+pub(crate) struct SubstitutionAttribute<'a> {
+ pub(crate) name: &'a [u16],
+ pub(crate) value: &'a [u16],
}
-#[repr(C)]
-pub struct FfiSubstitutionFunctionDeclaration {
- pub name: FfiUtf16View,
- pub data: *const c_void,
+/// One declaration in the body of a custom function, as its conditions select it.
+pub(crate) struct SubstitutionFunctionDeclaration {
+ pub(crate) name: crate::css::style_value::CssString,
+ pub(crate) value: Arc<StyleValueData>,
}
-#[repr(C)]
-pub struct FfiSubstitutionFunctionDefinition {
- pub identity: u64,
- pub scope_identity: usize,
- pub signature: *const c_void,
- pub declarations: *const FfiSubstitutionFunctionDeclaration,
- pub declaration_count: usize,
+/// A custom function a call may reach, with the declarations its conditions select.
+pub(crate) struct SubstitutionFunctionDefinition {
+ pub(crate) identity: u64,
+ pub(crate) scope_identity: usize,
+ pub(crate) signature: Arc<FunctionSignature>,
+ pub(crate) declarations: Vec<SubstitutionFunctionDeclaration>,
}
/// That a call from a scope names a function: the definition its name dereferences to there, as
@@ -317,10 +316,15 @@ pub(crate) struct CustomPropertyFinalization<'a> {
pub(crate) random_base_values: &'a [crate::css::style_compute::FfiRandomBaseValue],
/// A PreferredColorScheme code.
pub(crate) color_scheme: u8,
- /// How to draw the random base value of a key the host published none for, with its context.
- pub(crate) draw_random_base_value: Option<(DrawRandomBaseValue, *mut c_void)>,
+ /// Draws the random base value of a key the host published none for, from its name and whether
+ /// the key's element is null.
+ pub(crate) draw_random_base_value: Option<&'a DrawRandomBaseValue<'a>>,
}
+/// Draws the random base value of a random caching key for the element computed: its name, and
+/// whether the key's element is null.
+pub(crate) type DrawRandomBaseValue<'a> = dyn Fn(&[u16], bool) -> f64 + 'a;
+
/// What computing registered values read of their element beyond the fonts of its lengths: the
/// viewport, its place among its siblings, and the container-relative units it resolved against
/// its query containers, as a `container_relative_length_unit_mask`.
@@ -339,14 +343,6 @@ impl std::ops::BitOrAssign for RegisteredValueReads {
}
}
-/// Loads what a style query resolves against from a resolution's callback context.
-pub(crate) type LoadStyleQueryInputs =
- unsafe extern "C" fn(*mut c_void) -> *const crate::css::cascaded_properties::FfiStyleQueryInputs;
-
-/// Draws the random base value of a random caching key for the element computed: its name, and
-/// whether the key's element is null.
-pub(crate) type DrawRandomBaseValue = unsafe extern "C" fn(*mut c_void, *const u16, usize, bool) -> f64;
-
impl CustomPropertyRegistry {
/// Parse a value with a registration's syntax, as the computation of its name parses it.
fn parse_registered_value(
@@ -550,9 +546,9 @@ fn random_base_values_for_registered_value(
let value = match published.iter().find(|base| kind(base.source.cast()) == Some(wanted)) {
Some(base) => base.value,
None => {
- let (draw, context) = finalization.draw_random_base_value?;
+ let draw = finalization.draw_random_base_value?;
let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
- unsafe { draw(context, name.as_ptr(), name.len(), element_shared) }
+ draw(name, element_shared)
}
};
Some(crate::css::style_compute::FfiRandomBaseValue {
@@ -896,8 +892,6 @@ struct ASFResolutionContext<'a> {
custom_functions: Option<&'a CustomFunctionRegistry>,
parse_context: Option<&'a ParseContext>,
media_environment: Option<&'a FfiMediaEnvironment>,
- load_media_environment: Option<unsafe extern "C" fn(*mut c_void) -> *const c_void>,
- callback_context: *mut c_void,
/// What lengths in a style query resolve against: the element's last computed style.
style_query_length_resolution_context: Option<&'a crate::css::style_compute::FfiLengthResolutionContext>,
/// What colors in a style query resolve against, where the queried element's are known.
@@ -905,14 +899,11 @@ 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)>,
- /// Loads both from the callback context the first time a style query is evaluated.
- load_style_query_inputs: Option<LoadStyleQueryInputs>,
/// Where the custom properties 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>, *const c_void>>,
+ final_custom_properties: Option<&'a HashMap<Vec<u16>, RetainedStyleValueData>>,
function_local_scopes: Vec<FunctionLocalScope>,
token_cache: Option<&'a mut CustomPropertyTokenCache>,
- resolution_stats: Option<&'a VarResolutionStats>,
}
impl ASFResolutionContext<'_> {
@@ -921,33 +912,6 @@ impl ASFResolutionContext<'_> {
dependencies.get_or_insert_default().note(name);
}
}
-
- /// Load what a style query resolves against, if the host left it to be loaded.
- fn load_style_query_inputs(&mut self) {
- let Some(load) = self.load_style_query_inputs.take() else {
- return;
- };
- // SAFETY: The host keeps what it loads live for the resolution.
- let Some(inputs) = (unsafe { load(self.callback_context).as_ref() }) else {
- return;
- };
- self.style_query_length_resolution_context = Some(&inputs.length);
- self.style_query_color_resolution_input = Some(inputs.color_input());
- }
-
- fn media_environment(&mut self) -> Option<&FfiMediaEnvironment> {
- if self.media_environment.is_none()
- && let Some(load_media_environment) = self.load_media_environment
- {
- crate::css::ffi_stats::bump_cpp_callback(crate::css::ffi_stats::FfiOp::MediaEnvironmentCallback);
- self.media_environment = unsafe {
- load_media_environment(self.callback_context)
- .cast::<FfiMediaEnvironment>()
- .as_ref()
- };
- }
- self.media_environment
- }
}
/// The custom properties style queries read in one resolution, which the host records as the
@@ -1007,23 +971,6 @@ pub(crate) struct VarResolutionEnvironment {
attributes: HashMap<Vec<u16>, Vec<u16>>,
custom_functions: CustomFunctionRegistry,
token_cache: CustomPropertyTokenCache,
- resolution_stats: VarResolutionStats,
-}
-
-#[derive(Default)]
-struct VarResolutionStats {
- final_value_hits: std::cell::Cell<u64>,
- final_value_misses: std::cell::Cell<u64>,
-}
-
-impl VarResolutionEnvironment {
- pub(crate) fn final_value_hits(&self) -> u64 {
- self.resolution_stats.final_value_hits.get()
- }
-
- pub(crate) fn final_value_misses(&self) -> u64 {
- self.resolution_stats.final_value_misses.get()
- }
}
fn matching_close(kind: &OwnedTokenKind) -> Option<OwnedTokenKind> {
@@ -1225,21 +1172,14 @@ pub(crate) unsafe fn ffi_slice<'a, T>(items: *const T, count: usize) -> &'a [T]
}
}
-unsafe fn custom_function_registry_from_ffi(
- definitions: &[FfiSubstitutionFunctionDefinition],
+fn custom_function_registry(
+ definitions: &[SubstitutionFunctionDefinition],
caller_scope_identity: usize,
visibilities: &[FfiSubstitutionFunctionVisibility],
) -> Option<CustomFunctionRegistry> {
let mut parsed_definitions = Vec::with_capacity(definitions.len());
for definition in definitions {
- let signature = definition.signature.cast::<FunctionSignature>();
- if signature.is_null() {
- return None;
- }
- let signature = unsafe {
- Arc::increment_strong_count(signature);
- Arc::from_raw(signature)
- };
+ let signature = definition.signature.clone();
let mut parameter_defaults = Vec::with_capacity(signature.parameters.len());
for parameter in &signature.parameters {
parameter_defaults.push(match &parameter.default_value {
@@ -1247,17 +1187,10 @@ unsafe fn custom_function_registry_from_ffi(
None => None,
});
}
- let declarations = if definition.declaration_count == 0 {
- &[]
- } else {
- unsafe { std::slice::from_raw_parts(definition.declarations, definition.declaration_count) }
- };
- let mut parsed_declarations = Vec::with_capacity(declarations.len());
- for declaration in declarations {
- let name = unsafe { declaration.name.to_utf16() }?;
- let data = unsafe { &*declaration.data.cast::<StyleValueData>() };
- let (tokens, includes_substitution) = tokens_for_function_value(data)?;
- parsed_declarations.push((name, tokens, includes_substitution));
+ let mut parsed_declarations = Vec::with_capacity(definition.declarations.len());
+ for declaration in &definition.declarations {
+ let (tokens, includes_substitution) = tokens_for_function_value(&declaration.value)?;
+ parsed_declarations.push((declaration.name.units().to_vec(), tokens, includes_substitution));
}
parsed_definitions.push(CustomFunctionDefinition {
identity: definition.identity,
@@ -1285,38 +1218,25 @@ unsafe fn custom_function_registry_from_ffi(
}
/// Builds the element-wide immutable substitution inputs once for all declarations in a cascade.
-///
-/// # Safety
-/// Every FFI pointer must remain readable for this call.
-pub(crate) unsafe fn prepare_var_resolution_environment(
- attributes: *const FfiSubstitutionAttribute,
- attribute_count: usize,
- custom_functions: *const FfiSubstitutionFunctionDefinition,
- custom_function_count: usize,
+pub(crate) fn prepare_var_resolution_environment(
+ attributes: &[SubstitutionAttribute],
+ custom_functions: &[SubstitutionFunctionDefinition],
custom_function_scope_identity: usize,
- custom_function_visibilities: *const FfiSubstitutionFunctionVisibility,
- custom_function_visibility_count: usize,
+ custom_function_visibilities: &[FfiSubstitutionFunctionVisibility],
) -> Option<VarResolutionEnvironment> {
- let attributes = unsafe { ffi_slice(attributes, attribute_count) }
+ let attributes = attributes
.iter()
- .filter_map(|attribute| {
- Some((unsafe { attribute.name.to_utf16() }?, unsafe {
- attribute.value.to_utf16()
- }?))
- })
+ .map(|attribute| (attribute.name.to_vec(), attribute.value.to_vec()))
.collect();
- let custom_functions = unsafe {
- custom_function_registry_from_ffi(
- ffi_slice(custom_functions, custom_function_count),
- custom_function_scope_identity,
- ffi_slice(custom_function_visibilities, custom_function_visibility_count),
- )
- }?;
+ let custom_functions = custom_function_registry(
+ custom_functions,
+ custom_function_scope_identity,
+ custom_function_visibilities,
+ )?;
Some(VarResolutionEnvironment {
attributes,
custom_functions,
token_cache: HashMap::new(),
- resolution_stats: VarResolutionStats::default(),
})
}
@@ -1574,28 +1494,19 @@ fn resolve_custom_property_with_lookup(
}
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 let Some(data) = final_values
- .get(name)
- .and_then(|data| unsafe { data.cast::<StyleValueData>().as_ref() })
- {
- if let Some(stats) = context.resolution_stats {
- stats.final_value_hits.set(stats.final_value_hits.get() + 1);
- }
- if matches!(data, StyleValueData::GuaranteedInvalid) {
- return TokenResolution::Invalid;
- }
- let Some((tokens, includes_substitution, contains_attr_tainted_values)) =
- cached_tokens_for_custom_property_value(data, context)
- else {
- return TokenResolution::NotHandled;
- };
- context.contains_attr_tainted_values |= contains_attr_tainted_values;
- if !includes_substitution {
- return TokenResolution::Resolved(tokens.to_vec());
- }
- } else if let Some(stats) = context.resolution_stats {
- stats.final_value_misses.set(stats.final_value_misses.get() + 1);
+ if matches!(data, StyleValueData::GuaranteedInvalid) {
+ return TokenResolution::Invalid;
+ }
+ let Some((tokens, includes_substitution, contains_attr_tainted_values)) =
+ cached_tokens_for_custom_property_value(data, context)
+ else {
+ return TokenResolution::NotHandled;
+ };
+ 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));
@@ -2478,7 +2389,6 @@ fn evaluate_style_query(
Err(ConditionValidation::Invalid) => return ConditionEvaluation::Invalid,
Err(ConditionValidation::Valid) => unreachable!(),
};
- context.load_style_query_inputs();
evaluate_parsed_boolean_expression(&expression, &mut |feature| {
evaluate_style_feature(store, registry, feature, context, recursion_depth + 1)
})
@@ -2538,7 +2448,7 @@ fn evaluate_if_condition(
return evaluate_style_query(store, registry, &test[1..close], context, recursion_depth + 1);
}
if name.eq_ignore_ascii_case("media") {
- let Some(environment) = context.media_environment() else {
+ let Some(environment) = context.media_environment else {
return ConditionEvaluation::NotHandled;
};
let source = serialize_tokens(&test[1..close]);
@@ -3393,42 +3303,37 @@ fn serialize_tokens(tokens: &[OwnedToken]) -> Vec<u16> {
output
}
-#[allow(clippy::too_many_arguments)]
-pub(crate) unsafe fn resolve_vars(
- store: *const c_void,
- inheritance_store: *const c_void,
- registry: *const c_void,
- parse_context: Option<&ParseContext>,
- media_environment: Option<&FfiMediaEnvironment>,
- load_media_environment: Option<unsafe extern "C" fn(*mut c_void) -> *const c_void>,
+/// What a substitution reads beyond the value it substitutes.
+#[derive(Clone, Copy)]
+pub(crate) struct VarResolutionInputs<'a> {
+ pub(crate) store: Option<&'a CustomPropertyStore>,
+ pub(crate) inheritance_store: Option<&'a CustomPropertyStore>,
+ pub(crate) registry: Option<&'a CustomPropertyRegistry>,
+ pub(crate) parse_context: Option<&'a ParseContext>,
+ pub(crate) media_environment: Option<&'a FfiMediaEnvironment>,
+ pub(crate) attribute_names_are_ascii_case_insensitive: bool,
+ pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
+}
+
+pub(crate) fn resolve_vars(
+ inputs: &VarResolutionInputs,
property_id: u16,
- root_custom_property_name: FfiUtf16View,
- value_data: *const c_void,
+ root_custom_property_name: &[u16],
+ value_data: &StyleValueData,
environment: &mut VarResolutionEnvironment,
- attribute_names_are_ascii_case_insensitive: bool,
- callback_context: *mut c_void,
- style_query_inputs: Option<&crate::css::cascaded_properties::FfiStyleQueryInputs>,
- load_style_query_inputs: Option<LoadStyleQueryInputs>,
style_query_dependencies: Option<&mut Option<Box<StyleQueryDependencies>>>,
- final_custom_properties: Option<&HashMap<Vec<u16>, *const c_void>>,
+ final_custom_properties: Option<&HashMap<Vec<u16>, RetainedStyleValueData>>,
) -> NativeVarResolution {
- let store = if store.is_null() {
- None
- } else {
- Some(unsafe { &*store.cast::<CustomPropertyStore>() })
- };
- let registry = if registry.is_null() {
- None
- } else {
- Some(unsafe { &*registry.cast::<CustomPropertyRegistry>() })
- };
- let inheritance_store = if inheritance_store.is_null() {
- None
- } else {
- Some(unsafe { &*inheritance_store.cast::<CustomPropertyStore>() })
- };
- let value_data = unsafe { &*value_data.cast::<StyleValueData>() };
- let root_custom_property_name = unsafe { root_custom_property_name.to_utf16() }.filter(|name| !name.is_empty());
+ let VarResolutionInputs {
+ store,
+ inheritance_store,
+ registry,
+ parse_context,
+ media_environment,
+ attribute_names_are_ascii_case_insensitive,
+ style_query_inputs,
+ } = *inputs;
+ let root_custom_property_name = (!root_custom_property_name.is_empty()).then(|| root_custom_property_name.to_vec());
assert_eq!(
root_custom_property_name.is_some(),
property_id == crate::css::property_metadata::property_id::CUSTOM,
@@ -3444,7 +3349,6 @@ pub(crate) unsafe fn resolve_vars(
attributes,
custom_functions,
token_cache,
- resolution_stats,
} = environment;
let mut context = ASFResolutionContext {
attributes: Some(attributes),
@@ -3454,15 +3358,11 @@ pub(crate) unsafe fn resolve_vars(
custom_functions: Some(custom_functions),
parse_context,
media_environment,
- load_media_environment,
- callback_context,
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()),
- load_style_query_inputs,
style_query_dependencies,
final_custom_properties,
token_cache: Some(token_cache),
- resolution_stats: Some(resolution_stats),
..Default::default()
};
let Some((source, includes_substitution, contains_attr_tainted_values)) =
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs b/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
index 054abb9a129..3e4243aa53e 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
@@ -53,8 +53,6 @@ define_ffi_ops! {
SizesAttributeParseEntry => "sizesAttributeParseEntries",
// Ownership callbacks: Rust -> C++.
StringRetainReleaseCallback => "stringRetainReleaseCallbacks",
- // CSS parser callbacks: Rust -> C++.
- MediaEnvironmentCallback => "mediaEnvironmentCallbacks",
}
/// Counts owned by one bridge context. Atomics permit observation from another thread;
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 9b57bc7f944..d730fe0c85a 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
@@ -20,22 +20,18 @@ use std::sync::Arc;
use super::publication::{Drive, Unanswered};
use super::*;
use crate::css::cascaded_properties::{
- CallbackFreeParseOutcome, FfiCascadeResolutionContext, FfiCustomPropertyDriveInput,
- destroy_resolved_custom_properties, parse_substituted_source, parse_substituted_without_callbacks,
+ CallbackFreeParseOutcome, CascadeResolutionContext, parse_substituted_source, parse_substituted_without_callbacks,
resolve_declared_custom_properties,
};
use crate::css::custom_properties::{
- CustomPropertyFinalization, CustomPropertyStore, FfiSubstitutionFunctionDeclaration,
- FfiSubstitutionFunctionDefinition, FfiSubstitutionFunctionVisibility, NativeVarResolution,
+ CustomPropertyFinalization, CustomPropertyStore, FfiSubstitutionFunctionVisibility, NativeVarResolution,
+ SubstitutionAttribute, SubstitutionFunctionDeclaration, SubstitutionFunctionDefinition, VarResolutionInputs,
prepare_var_resolution_environment,
};
-use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::component_value::{ComponentKind, ComponentValue};
use crate::css::parser::value_parser::ParseOutcome;
use crate::css::rule::CompiledFunction;
-use crate::css::style_value::{
- RetainedStyleValueData, StyleValueData, release_style_value, utf16_equals_ascii_case_insensitive,
-};
+use crate::css::style_value::{RetainedStyleValueData, StyleValueData, utf16_equals_ascii_case_insensitive};
use custom_property_environments::{CascadedCustomProperty, CustomPropertyName};
/// The document's media features as the style update a transaction belongs to saw them, which
@@ -320,12 +316,9 @@ impl DocumentFunctionSnapshot {
/// The custom functions a node's calls may reach, as the resolver takes them: each definition with
/// the declarations its conditions select for the node, and which definition each scope's calls
-/// name. It points into the definitions the engine retains for the transaction, which outlive
-/// every drive in it.
+/// name.
pub(super) struct PreparedCustomFunctions {
- /// What `definitions` point into.
- _declarations: Vec<Vec<FfiSubstitutionFunctionDeclaration>>,
- definitions: Vec<FfiSubstitutionFunctionDefinition>,
+ definitions: Vec<SubstitutionFunctionDefinition>,
visibilities: Vec<FfiSubstitutionFunctionVisibility>,
caller_scope: usize,
/// Whether a selected declaration substitutes `attr()`, which reads the node's attributes.
@@ -344,72 +337,39 @@ pub(super) struct RegisteredValueContext {
pub color_scheme: u8,
}
-/// Draws the random base value of a registered value's random caching key for its element from
-/// the engine's own, as the host draws one.
-///
-/// # Safety
-/// `context` must point at the element and the engine's random base values, and `name` at
-/// `length` code units.
-unsafe extern "C" fn draw_engine_random_base_value(
- context: *mut c_void,
- name: *const u16,
- length: usize,
- element_shared: bool,
-) -> f64 {
- let (node, values) = unsafe { &mut *context.cast::<(StyleNodeID, &mut super::random_bases::RandomBaseValues)>() };
- let name = match length {
- 0 => &[],
- _ => unsafe { std::slice::from_raw_parts(name, length) },
- };
- values.ensure(Some(*node), name, element_shared)
-}
-
/// The resolution context the engine substitutes under: the stores alone, with no callback into
/// C++ - what the engine cannot resolve without one is left to C++ before this is built.
#[expect(
clippy::too_many_arguments,
reason = "the context borrows each resolution input on its own"
)]
-fn engine_resolution_context(
- parse_context: &crate::css::parser::value_parser::ParseContext,
- store: *const c_void,
- inheritance_store: *const c_void,
- registry: *const c_void,
- attributes: Option<&SubstitutionAttributes<'_>>,
- media_environment: &crate::css::parser::query_parser::FfiMediaEnvironment,
- style_query: Option<&crate::css::cascaded_properties::FfiStyleQueryInputs>,
- style_query_references: Option<&mut Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>,
- functions: Option<&PreparedCustomFunctions>,
-) -> FfiCascadeResolutionContext {
- let substitution_attributes = attributes.map_or(&[][..], |attributes| attributes.attributes.as_slice());
- FfiCascadeResolutionContext {
- parse_context: std::ptr::from_ref(parse_context).cast(),
- media_environment: std::ptr::from_ref(media_environment).cast(),
- load_media_environment: None,
- custom_property_store: store,
- inheritance_custom_property_store: inheritance_store,
- custom_property_registry: registry,
- root_custom_property_name: FfiUtf16View {
- ascii: std::ptr::null(),
- utf16: std::ptr::null(),
- length: 0,
+fn engine_resolution_context<'a>(
+ parse_context: &'a crate::css::parser::value_parser::ParseContext,
+ store: Option<&'a CustomPropertyStore>,
+ inheritance_store: Option<&'a CustomPropertyStore>,
+ registry: &'a crate::css::custom_properties::CustomPropertyRegistry,
+ attributes: Option<&'a SubstitutionAttributes<'a>>,
+ media_environment: &'a crate::css::parser::query_parser::FfiMediaEnvironment,
+ style_query: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
+ style_query_references: Option<&'a mut Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>,
+ functions: Option<&'a PreparedCustomFunctions>,
+) -> CascadeResolutionContext<'a> {
+ CascadeResolutionContext {
+ inputs: VarResolutionInputs {
+ store,
+ inheritance_store,
+ registry: Some(registry),
+ parse_context: Some(parse_context),
+ media_environment: Some(media_environment),
+ attribute_names_are_ascii_case_insensitive: attributes
+ .is_some_and(|attributes| attributes.names_are_ascii_case_insensitive),
+ style_query_inputs: style_query,
},
- attributes: substitution_attributes.as_ptr(),
- attribute_count: substitution_attributes.len(),
- attribute_names_are_ascii_case_insensitive: attributes
- .is_some_and(|attributes| attributes.names_are_ascii_case_insensitive),
- custom_functions: functions.map_or(std::ptr::null(), |functions| functions.definitions.as_ptr()),
- custom_function_count: functions.map_or(0, |functions| functions.definitions.len()),
+ attributes: attributes.map_or(&[][..], |attributes| attributes.attributes.as_slice()),
+ custom_functions: functions.map_or(&[][..], |functions| functions.definitions.as_slice()),
custom_function_scope_identity: functions.map_or(0, |functions| functions.caller_scope),
- custom_function_visibilities: functions.map_or(std::ptr::null(), |functions| functions.visibilities.as_ptr()),
- custom_function_visibility_count: functions.map_or(0, |functions| functions.visibilities.len()),
- callback_context: std::ptr::null_mut(),
- install_custom_properties: None,
- style_query_inputs: style_query.map_or(std::ptr::null(), std::ptr::from_ref),
- load_style_query_inputs: None,
- style_query_dependencies: style_query_references
- .map_or(std::ptr::null_mut(), |references| std::ptr::from_mut(references).cast()),
- note_substitution: None,
+ custom_function_visibilities: functions.map_or(&[][..], |functions| functions.visibilities.as_slice()),
+ style_query_dependencies: style_query_references,
}
}
@@ -555,29 +515,18 @@ pub(super) struct SubstitutionInputs<'a> {
/// attributes in no namespace, by local name, with its value's text, and whether names match ASCII
/// case-insensitively, as an HTML element's do. It points into the facts it borrows.
pub(super) struct SubstitutionAttributes<'a> {
- attributes: Vec<crate::css::custom_properties::FfiSubstitutionAttribute>,
+ attributes: Vec<SubstitutionAttribute<'a>>,
names_are_ascii_case_insensitive: bool,
- facts: std::marker::PhantomData<&'a index::ElementFactStore>,
}
impl<'a> SubstitutionAttributes<'a> {
pub(super) fn of(facts: &'a index::ElementFactStore, node: StyleNodeID, html_namespace: StyleAtomID) -> Self {
- use crate::css::custom_properties::FfiSubstitutionAttribute;
- let view = |text: &[u16]| FfiUtf16View {
- ascii: std::ptr::null(),
- utf16: text.as_ptr(),
- length: text.len(),
- };
Self {
attributes: facts
.substitution_attributes(node)
- .map(|(name, value)| FfiSubstitutionAttribute {
- name: view(name),
- value: view(value),
- })
+ .map(|(name, value)| SubstitutionAttribute { name, value })
.collect(),
names_are_ascii_case_insensitive: !html_namespace.is_none() && facts.namespace_of(node) == html_namespace,
- facts: std::marker::PhantomData,
}
}
}
@@ -1286,14 +1235,9 @@ impl RetainedState {
}
for descriptor in &input.declarations.descriptors {
reads_attributes |= value_reads_attributes(&descriptor.value);
- let name = descriptor.name.units();
- selected.push(FfiSubstitutionFunctionDeclaration {
- name: FfiUtf16View {
- ascii: std::ptr::null(),
- utf16: name.as_ptr(),
- length: name.len(),
- },
- data: Arc::as_ptr(&descriptor.value).cast(),
+ selected.push(SubstitutionFunctionDeclaration {
+ name: descriptor.name.clone(),
+ value: descriptor.value.clone(),
});
}
}
@@ -1301,19 +1245,15 @@ impl RetainedState {
}
let definitions = visible_definitions
.iter()
- .zip(&declarations)
- .map(
- |((function, scope, _), declarations)| FfiSubstitutionFunctionDefinition {
- identity: function.identity,
- scope_identity: *scope,
- signature: Arc::as_ptr(&function.signature).cast(),
- declarations: declarations.as_ptr(),
- declaration_count: declarations.len(),
- },
- )
+ .zip(declarations)
+ .map(|((function, scope, _), declarations)| SubstitutionFunctionDefinition {
+ identity: function.identity,
+ scope_identity: *scope,
+ signature: function.signature.clone(),
+ declarations,
+ })
.collect();
Some(PreparedCustomFunctions {
- _declarations: declarations,
definitions,
visibilities: visible.map_or_else(Vec::new, |visible| visible.visibilities.clone()),
caller_scope,
@@ -1530,7 +1470,7 @@ impl RetainedState {
reads_attributes.then(|| SubstitutionAttributes::of(&self.facts, node, self.html_element_namespace));
// SAFETY: The parent store is live for as long as a record names its environment, and the
// values are the program's interned values, live for the call.
- let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(parent_store, values) };
+ let cascaded_store = unsafe { Arc::from_raw(CustomPropertyStore::cascaded_child(parent_store, values).cast()) };
let mut random_function_index = 0_usize;
let mut parse_context = registry_ref.parse_context(&mut random_function_index);
parse_context.in_quirks_mode = inputs.in_quirks_mode;
@@ -1541,11 +1481,13 @@ impl RetainedState {
// The custom properties a `style()` query reads are the element's style query references,
// which the host records with its record.
let mut style_query_references = None;
- let resolution_context = engine_resolution_context(
+ // SAFETY: The store is live for as long as a record names its environment.
+ let inheritance_store = unsafe { inheritance_store.cast::<CustomPropertyStore>().as_ref() };
+ let mut resolution_context = engine_resolution_context(
&parse_context,
- cascaded_store,
+ Some(&cascaded_store),
inheritance_store,
- std::ptr::from_ref(registry_ref).cast(),
+ registry_ref,
attributes.as_ref(),
&media_environment,
style_query.as_ref(),
@@ -1565,40 +1507,28 @@ impl RetainedState {
.then(|| self.sibling_position(node))
.flatten()
.map(|position| (u64::from(position.count), u64::from(position.index)));
- let mut random_base_values = (node, &mut self.random_base_values);
+ let random_base_values = std::cell::RefCell::new(&mut self.random_base_values);
+ let draw_random_base_value = |name: &[u16], element_shared: bool| {
+ random_base_values.borrow_mut().ensure(Some(node), name, element_shared)
+ };
let finalization = CustomPropertyFinalization {
length: length.as_ref(),
tree_counting,
random_base_values: &[],
color_scheme: registered.as_ref().map_or(0, |registered| registered.color_scheme),
- draw_random_base_value: Some((
- draw_engine_random_base_value,
- std::ptr::from_mut(&mut random_base_values).cast(),
- )),
- };
- let drive = FfiCustomPropertyDriveInput {
- store: cascaded_store,
- resolved_parent_store: parent_store,
- reuse_resolved_parent_if_empty: !parent_store.is_null(),
- resolution_context: &raw const resolution_context,
- finalization_length_resolution_context: std::ptr::null(),
- finalization_environment: std::ptr::null(),
- finalization_color_scheme: 0,
- draw_random_base_value: None,
- random_base_context: std::ptr::null_mut(),
+ draw_random_base_value: Some(&draw_random_base_value),
};
- // SAFETY: Every pointer the drive reads is live for the call.
- let (resolved, reads) = unsafe { resolve_declared_custom_properties(&drive, finalization) };
- // The resolved values live in the store; the listing transfers references of its own.
- let properties = match resolved.count {
- 0 => &[],
- count => unsafe { std::slice::from_raw_parts(resolved.properties, count) },
+ // SAFETY: The parent store is live for as long as a record names its environment.
+ let (rust_store, reads) = unsafe {
+ resolve_declared_custom_properties(
+ &cascaded_store,
+ parent_store,
+ !parent_store.is_null(),
+ &mut resolution_context,
+ finalization,
+ )
};
- for property in properties {
- unsafe { release_style_value(property.data.cast()) };
- }
- unsafe { destroy_resolved_custom_properties(resolved.storage, resolved.count) };
- unsafe { Arc::decrement_strong_count(cascaded_store.cast::<CustomPropertyStore>()) };
+ 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.
@@ -1627,12 +1557,12 @@ impl RetainedState {
},
);
}
- let identity = if resolved.rust_store.is_null() {
+ let identity = if rust_store.is_null() {
inherited_environment
} else {
unsafe {
self.custom_property_environments.adopt_engine_environment(
- resolved.rust_store,
+ rust_store,
inherited_environment,
parent_store,
registry_ref,
@@ -1832,47 +1762,43 @@ fn substitute_against_stores(
let mut parse_context = registry_ref.parse_context(&mut random_function_index);
parse_context.in_quirks_mode = inputs.document.in_quirks_mode;
let media_environment = inputs.media.environment();
- let substitution_attributes = attributes.map_or(&[][..], |attributes| attributes.attributes.as_slice());
- let resolution_environment = unsafe {
- prepare_var_resolution_environment(
- substitution_attributes.as_ptr(),
- substitution_attributes.len(),
- functions.map_or(std::ptr::null(), |functions| functions.definitions.as_ptr()),
- functions.map_or(0, |functions| functions.definitions.len()),
- functions.map_or(0, |functions| functions.caller_scope),
- functions.map_or(std::ptr::null(), |functions| functions.visibilities.as_ptr()),
- functions.map_or(0, |functions| functions.visibilities.len()),
- )
- };
+ let resolution_environment = prepare_var_resolution_environment(
+ attributes.map_or(&[][..], |attributes| attributes.attributes.as_slice()),
+ functions.map_or(&[][..], |functions| functions.definitions.as_slice()),
+ functions.map_or(0, |functions| functions.caller_scope),
+ functions.map_or(&[][..], |functions| functions.visibilities.as_slice()),
+ );
let mut style_query_references = inputs.style_query_references.map(std::cell::RefCell::borrow_mut);
// A function definition whose declarations do not tokenize resolves nothing.
let resolution = match resolution_environment {
- // SAFETY: The store is live while a record names its environment, and the written
- // value is retained by the declaration that carries it.
- Some(mut resolution_environment) => unsafe {
- crate::css::custom_properties::resolve_vars(
+ Some(mut resolution_environment) => {
+ // SAFETY: The stores are null or live while a record names their environments.
+ let (store, inheritance_store) = unsafe {
+ (
+ store.cast::<CustomPropertyStore>().as_ref(),
+ inheritance_store.cast::<CustomPropertyStore>().as_ref(),
+ )
+ };
+ let resolution_inputs = VarResolutionInputs {
store,
inheritance_store,
- std::ptr::from_ref(registry_ref).cast(),
- Some(&parse_context),
- Some(&media_environment),
- None,
+ registry: Some(registry_ref),
+ parse_context: Some(&parse_context),
+ media_environment: Some(&media_environment),
+ attribute_names_are_ascii_case_insensitive: attributes
+ .is_some_and(|attributes| attributes.names_are_ascii_case_insensitive),
+ style_query_inputs: inputs.style_query,
+ };
+ crate::css::custom_properties::resolve_vars(
+ &resolution_inputs,
property,
- FfiUtf16View {
- ascii: std::ptr::null(),
- utf16: root_custom_property_name.as_ptr(),
- length: root_custom_property_name.len(),
- },
- written.pointer().cast(),
+ root_custom_property_name,
+ written.data(),
&mut resolution_environment,
- attributes.is_some_and(|attributes| attributes.names_are_ascii_case_insensitive),
- std::ptr::null_mut(),
- inputs.style_query,
- None,
style_query_references.as_deref_mut(),
None,
)
- },
+ }
None => NativeVarResolution::NotHandled,
};
// The substituted source parses as the C++ cascade parses it: without callbacks first,
diff --git a/Tests/LibWeb/Text/expected/css/ffi-parse-counters.txt b/Tests/LibWeb/Text/expected/css/ffi-parse-counters.txt
index 05bafa879eb..40c99683f64 100644
--- a/Tests/LibWeb/Text/expected/css/ffi-parse-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/ffi-parse-counters.txt
@@ -1,2 +1 @@
computed width: 1px
-mediaEnvironmentCallbacks: 0
diff --git a/Tests/LibWeb/Text/expected/css/if-condition-ffi-counters.txt b/Tests/LibWeb/Text/expected/css/if-condition-ffi-counters.txt
index a8efe2a7a57..d30d37a0d9e 100644
--- a/Tests/LibWeb/Text/expected/css/if-condition-ffi-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/if-condition-ffi-counters.txt
@@ -1,10 +1,5 @@
media result: 1px
-media media environment callbacks: 0
supports result: 1px
-supports media environment callbacks: 0
style result: 1px
-style media environment callbacks: 0
shared results: 1px, 1px
-shared media environment callbacks: 0
shared results: 1px, 1px
-shared media environment callbacks: 0
diff --git a/Tests/LibWeb/Text/input/css/ffi-parse-counters.html b/Tests/LibWeb/Text/input/css/ffi-parse-counters.html
index 15b0ea1582b..14b513e2d54 100644
--- a/Tests/LibWeb/Text/input/css/ffi-parse-counters.html
+++ b/Tests/LibWeb/Text/input/css/ffi-parse-counters.html
@@ -49,7 +49,6 @@
const sheet = new CSSStyleSheet();
sheet.replaceSync(source);
- const counters = internals.styleFfiCounters();
document.adoptedStyleSheets = [sheet];
const target = document.createElement("div");
@@ -57,9 +56,5 @@
target.dataset.index = "0";
document.body.appendChild(target);
println(`computed width: ${getComputedStyle(target).width}`);
-
- const names = ["mediaEnvironmentCallbacks"];
- for (const name of names)
- println(`${name}: ${counters[name]}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/if-condition-ffi-counters.html b/Tests/LibWeb/Text/input/css/if-condition-ffi-counters.html
index 8b977f2d174..fe956f936dd 100644
--- a/Tests/LibWeb/Text/input/css/if-condition-ffi-counters.html
+++ b/Tests/LibWeb/Text/input/css/if-condition-ffi-counters.html
@@ -12,7 +12,6 @@
internals.resetStyleFfiCounters();
println(`${name} result: ${getComputedStyle(target).width}`);
- println(`${name} media environment callbacks: ${internals.styleFfiCounters().mediaEnvironmentCallbacks}`);
target.remove();
}
@@ -31,7 +30,6 @@
internals.resetStyleFfiCounters();
internals.updateStyle();
println(`shared results: ${targets.map(target => getComputedStyle(target).width).join(", ")}`);
- println(`shared media environment callbacks: ${internals.styleFfiCounters().mediaEnvironmentCallbacks}`);
targets.forEach(target => target.remove());
}