Truly independent web browser
LibWeb: Count a parse's random functions through a typed reference
Andreas Kling80deec28b0be
diff --git a/Libraries/LibWeb/CSS/Parser/Parser.h b/Libraries/LibWeb/CSS/Parser/Parser.hindex 848270df9c3..1c84977ee15 100644--- a/Libraries/LibWeb/CSS/Parser/Parser.h+++ b/Libraries/LibWeb/CSS/Parser/Parser.h@@ -155,6 +155,12 @@ private:bool in_quirks_mode() const;bool is_parsing_svg_presentation_attribute() const;+ // The rule contexts as the bytes the Rust parser reads them as.+ ReadonlyBytes rule_context_bytes() const+ {+ static_assert(sizeof(RuleContext) == sizeof(u8));+ return { reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size() };+ }GC::Ptr<DOM::Document const> m_document;ParsingMode m_parsing_mode { ParsingMode::Normal };diff --git a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cppindex c3ad1e1d02b..e0b9e4913ab 100644--- a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp+++ b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp@@ -205,8 +205,7 @@ RustRuleList RustStyleSheetParse::native_rules() constOptional<RustRule> Parser::parse_as_css_rule(Utf16View source, bool nested){auto context = make_parse_context(ParseContextMode::Syntax);- static_assert(sizeof(RuleContext) == sizeof(u8));- RustStyleSheetParse parse { rust_parse_css_rule_syntax(ffi_utf16_view(source), reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size(), nested, &context.context) };+ RustStyleSheetParse parse { rust_parse_css_rule_syntax(ffi_utf16_view(source), rule_context_bytes(), nested, &context.context) };report_diagnostics(parse);if (rust_css_syntax_root_count(parse.handle()) != 1)return {};@@ -222,8 +221,7 @@ Optional<RustRule> Parser::parse_as_keyframe_rule(Utf16View source)m_rule_context.append(RuleContext::AtKeyframes);ScopeGuard guard = [&] { m_rule_context.take_last(); };auto context = make_parse_context(ParseContextMode::Syntax);- static_assert(sizeof(RuleContext) == sizeof(u8));- RustStyleSheetParse parse { rust_parse_css_block_syntax(ffi_utf16_view(source), reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size(), &context.context, false) };+ RustStyleSheetParse parse { rust_parse_css_block_syntax(ffi_utf16_view(source), rule_context_bytes(), &context.context, false) };report_diagnostics(parse);if (rust_css_syntax_root_count(parse.handle()) != 1)return {};@@ -235,11 +233,10 @@ Optional<RustRule> Parser::parse_as_keyframe_rule(Utf16View source)RustDeclarationBlock Parser::parse_as_property_declaration_block(Utf16View source){- static_assert(sizeof(RuleContext) == sizeof(u8));auto context = make_parse_context(ParseContextMode::Syntax);// https://drafts.csswg.org/cssom/#parse-a-css-declaration-block// 1. Let declarations be the returned declarations from invoking parse a block’s contents with string.- auto* handle = rust_parse_css_block_syntax(ffi_utf16_view(source), reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size(), &context.context, false);+ auto* handle = rust_parse_css_block_syntax(ffi_utf16_view(source), rule_context_bytes(), &context.context, false);RustStyleSheetParse parse { handle };report_diagnostics(parse);rust_css_syntax_visit_declaration_errors(parse.handle(), report_declaration_error);@@ -269,9 +266,8 @@ RustDescriptorBlock Parser::parse_as_descriptor_declaration_block(Utf16View sourm_rule_context.append(context_type);ScopeGuard guard = [&] { m_rule_context.take_last(); };- static_assert(sizeof(RuleContext) == sizeof(u8));auto context = make_parse_context(ParseContextMode::Syntax);- auto* handle = rust_parse_css_block_syntax(ffi_utf16_view(source), reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size(), &context.context, false);+ auto* handle = rust_parse_css_block_syntax(ffi_utf16_view(source), rule_context_bytes(), &context.context, false);RustStyleSheetParse parse { handle };report_diagnostics(parse);rust_css_syntax_visit_declaration_errors(parse.handle(), report_declaration_error);@@ -280,9 +276,8 @@ RustDescriptorBlock Parser::parse_as_descriptor_declaration_block(Utf16View sourVector<DevToolsStyleDeclaration> Parser::parse_as_devtools_property_declaration_block(Utf16View source){- static_assert(sizeof(RuleContext) == sizeof(u8));auto context = make_parse_context(ParseContextMode::Syntax);- RustStyleSheetParse parse { rust_parse_css_block_syntax(ffi_utf16_view(source), reinterpret_cast<u8 const*>(m_rule_context.data()), m_rule_context.size(), &context.context, true) };+ RustStyleSheetParse parse { rust_parse_css_block_syntax(ffi_utf16_view(source), rule_context_bytes(), &context.context, true) };report_diagnostics(parse);Vector<DevToolsStyleDeclaration> result;rust_css_syntax_visit_root_declarations(parse.handle(), &result, [](void* context, u16 const* values, size_t value_count, FfiSyntaxDeclaration const* declaration_pointer) {diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 9cce7b54447..cd4d83fed15 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -2522,6 +2522,15 @@ fn main() -> Result<(), Box<dyn Error>> {];// A tree scope's counter styles are queued on the document host, which the layout header declares.declare_document_host_of_layout_header(&mut value_parser_config);+ // A parse context's random function counter is the `size_t` C++ lends.+ value_parser_config+ .export+ .rename+ .insert("RandomFunctionIndex".to_string(), "size_t".to_string());+ value_parser_config+ .export+ .exclude+ .push("RandomFunctionIndex".to_string());// A parse context names the lengths it resolves against as the computed values header declares them.value_parser_config.export.rename.insert("FfiLengthResolutionContext".to_string(),diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rsindex 0d62db95fe3..81c791db7c2 100644--- a/Libraries/LibWeb/Rust/src/css/calc.rs+++ b/Libraries/LibWeb/Rust/src/css/calc.rs@@ -353,10 +353,10 @@ pub(crate) fn serialize_context_free_calculation(crate::css::parser::calc_parser::CalcParserContext {percentages_resolve_as: None,property: 0,- random_function_index: std::ptr::null_mut(),+ random_function_index: None,allowed_color_channels: 0,allow_random_functions: false,- parse_context: std::ptr::null(),+ parse_context: None,},).ok()?;diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rsindex 261feeb6363..89f25bca5e7 100644--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs@@ -348,7 +348,7 @@ pub(crate) fn parse_substituted_value(contains_attr_tainted_values: bool,) -> RetainedStyleValueData {crate::css::ffi_stats::bump(crate::css::ffi_stats::FfiOp::SubstitutionParse);- let mut random_function_index = 0;+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();let value_context = FfiValueParsingContext {kind: FfiValueParsingContextKind::Property,value: property_id,@@ -359,7 +359,7 @@ pub(crate) fn parse_substituted_value(context.is_substituted_value = true;context.contains_attr_tainted_values = contains_attr_tainted_values;context.value_contexts = ak::Span::new(std::slice::from_ref(&value_context));- context.random_function_index = &raw mut random_function_index;+ context.random_function_index = Some(&random_function_index);match parse_css_value_from_source(&context, property_id, source) {ParseOutcome::Parsed(value) => RetainedStyleValueData::from_arc(value),ParseOutcome::Invalid | ParseOutcome::NotHandled => {diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex c71a23c2dcd..cbeaae5833a 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -30,7 +30,9 @@ use crate::css::parser::query_parser::{parse_and_evaluate_media_if_condition, parse_and_evaluate_supports_if_condition, parse_style_range_from_source,};use crate::css::parser::syntax::{SyntaxNode, SyntaxType, clone_syntax_handle, parse_syntax, parse_with_syntax};-use crate::css::parser::value_parser::{FfiValueParsingContext, FfiValueParsingContextKind, ParseContext};+use crate::css::parser::value_parser::{+ FfiValueParsingContext, FfiValueParsingContextKind, ParseContext, RandomFunctionIndex,+};use crate::css::retained_fly_string::RetainedUtf16FlyString;use crate::css::serialize::serialize_component_values_to_utf16;use crate::css::style_value::RetainedStyleValueData;@@ -312,7 +314,7 @@ impl CustomPropertyRegistry {)}- pub(crate) fn parse_context(&self, random_function_index: &mut usize) -> ParseContext<'_> {+ pub(crate) fn parse_context<'a>(&'a self, random_function_index: &'a RandomFunctionIndex) -> ParseContext<'a> {ParseContext {in_quirks_mode: false,is_svg_presentation_attribute: false,@@ -324,7 +326,7 @@ impl CustomPropertyRegistry {document_url: ak::Span::new(&self.document_url),document_base_url: ak::Span::new(&self.document_base_url),length_resolution_context: None,- random_function_index,+ random_function_index: Some(random_function_index),}}}@@ -374,14 +376,14 @@ impl CustomPropertyRegistry {registration: &RegisteredCustomProperty,source: &[u16],) -> Option<StyleValueData> {- let mut random_function_index = 0;+ let random_function_index = RandomFunctionIndex::default();let value_context = FfiValueParsingContext {kind: FfiValueParsingContextKind::Property,value: crate::css::property_metadata::property_id::CUSTOM,secondary_value: 0,name: Default::default(),};- let mut context = self.parse_context(&mut random_function_index);+ let mut context = self.parse_context(&random_function_index);context.value_contexts = ak::Span::new(std::slice::from_ref(&value_context));parse_with_syntax(&context, source, ®istration.syntax)}@@ -1448,8 +1450,8 @@ fn normalize_function_tokens(return TokenResolution::NotHandled;};let source = serialize_tokens(tokens);- let mut random_function_index = 0;- let context = registry.parse_context(&mut random_function_index);+ let random_function_index = RandomFunctionIndex::default();+ let context = registry.parse_context(&random_function_index);let Some(parsed) = parse_with_syntax(&context, &source, syntax) else {return TokenResolution::Invalid;};@@ -1999,8 +2001,8 @@ fn registered_style_query_values_are_equal(query_tokens: &[OwnedToken],resolution_context: &mut ASFResolutionContext,) -> bool {- let mut random_function_index = 0;- let context = registry.parse_context(&mut random_function_index);+ let random_function_index = RandomFunctionIndex::default();+ let context = registry.parse_context(&random_function_index);let Some(computed) = parse_with_syntax(&context, &serialize_tokens(computed_tokens), syntax) else {return false;};@@ -2160,12 +2162,12 @@ fn evaluate_style_range_value(TokenResolution::NotHandled => return Err(ConditionEvaluation::NotHandled),};let source = serialize_tokens(&resolved);- let mut random_function_index = 0;+ let random_function_index = RandomFunctionIndex::default();let registry_parse_context;let parse_context = match (context.parse_context, registry) {(Some(parse_context), _) => parse_context,(None, Some(registry)) => {- registry_parse_context = registry.parse_context(&mut random_function_index);+ registry_parse_context = registry.parse_context(&random_function_index);®istry_parse_context}(None, None) => return Ok(None),@@ -2987,8 +2989,8 @@ fn parse_attr_value_with_syntax(syntax: &SyntaxNode,) -> Option<Vec<OwnedToken>> {let registry = registry?;- let mut random_function_index = 0;- let parsed = parse_with_syntax(®istry.parse_context(&mut random_function_index), source, syntax)?;+ let random_function_index = RandomFunctionIndex::default();+ let parsed = parse_with_syntax(®istry.parse_context(&random_function_index), source, syntax)?;let serialized = crate::css::serialize::serialize_style_value_to_utf16(&parsed);Some(tokenize_owned(&serialized))}@@ -3447,8 +3449,8 @@ mod tests {#[test]fn style_queries_only_report_sibling_dependencies_for_tree_counting() {let registry = CustomPropertyRegistry::empty();- let mut random_index = 0;- let parse_context = registry.parse_context(&mut random_index);+ let random_index = RandomFunctionIndex::default();+ let parse_context = registry.parse_context(&random_index);let length = crate::css::style_compute::FfiLengthResolutionContext::default();for (source, expected, reads_sibling_position) in [("10px", 10.0, false),diff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rsindex 87a0dd411c9..09f133aa399 100644--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs@@ -642,7 +642,7 @@ mod tests {let input = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parse = unsafe { parse_shared_stylesheet(input, &context) };+ let parse = parse_shared_stylesheet(input, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parse);let rule = &rules.rule_at(0);rule.cascade_declarations().unwrap()@@ -710,7 +710,7 @@ mod tests {let input = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parse = unsafe { parse_shared_stylesheet(input, &context) };+ let parse = parse_shared_stylesheet(input, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parse);let rule = rules.rule_at(0);let nested = rule.child_rules().unwrap().rule_at(1);diff --git a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs b/Libraries/LibWeb/Rust/src/css/descriptor_block.rsindex a7ae440ebf8..bed5f5f71d5 100644--- a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs+++ b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs@@ -318,7 +318,7 @@ mod tests {let input = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parse = unsafe { parse_shared_stylesheet(input, &context) };+ let parse = parse_shared_stylesheet(input, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parse);let rule = rules.rule_at(0);let block = unsafe { &*rust_rule_payload(&rule).descriptors };diff --git a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rsindex 1448a59110b..8ed6561d8f9 100644--- a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs@@ -11,7 +11,8 @@use super::value_parser::{ANGLE_UNIT_NAMES, FLEX_UNIT_NAMES, FREQUENCY_UNIT_NAMES, NumericRange, ParseContext, RESOLUTION_UNIT_NAMES,- TIME_UNIT_NAMES, context_allows_tree_counting_functions, parse_calculated_numeric_value_with_ranges,+ RandomFunctionIndex, TIME_UNIT_NAMES, context_allows_tree_counting_functions,+ parse_calculated_numeric_value_with_ranges,};use crate::css::calc::{CalcNode, CalcNumericType, CalcNumericValue, CalcRoundingStrategy, resolve_as_for_value_type,@@ -38,25 +39,25 @@ pub(crate) enum CalcParseError {type Result<T> = std::result::Result<T, CalcParseError>;#[derive(Clone, Copy)]-pub(crate) struct CalcParserContext {+pub(crate) struct CalcParserContext<'a> {pub percentages_resolve_as: Option<u8>,pub property: u16,- pub random_function_index: *mut usize,+ pub random_function_index: Option<&'a RandomFunctionIndex>,pub allowed_color_channels: u64,pub allow_random_functions: bool,- pub parse_context: *const ParseContext<'static>,+ pub parse_context: Option<&'a ParseContext<'a>>,}-impl CalcParserContext {+impl CalcParserContext<'_> {#[cfg(test)]fn for_test(percentages_resolve_as: Option<u8>) -> Self {Self {percentages_resolve_as,property: 0,- random_function_index: std::ptr::null_mut(),+ random_function_index: None,allowed_color_channels: 0,allow_random_functions: false,- parse_context: std::ptr::null(),+ parse_context: None,}}}@@ -79,11 +80,11 @@ fn unit_index(unit: &[u16], names: &[&str]) -> Option<u8> {struct CalculationParser<'a> {values: Vec<&'a ComponentValue>,position: usize,- context: CalcParserContext,+ context: CalcParserContext<'a>,}impl<'a> CalculationParser<'a> {- fn new(values: &'a [ComponentValue], context: CalcParserContext) -> Self {+ fn new(values: &'a [ComponentValue], context: CalcParserContext<'a>) -> Self {Self {values: values.iter().filter(|value| !value.is_whitespace()).collect(),position: 0,@@ -207,7 +208,7 @@ fn parse_non_math_function(arguments: &[ComponentValue],context: CalcParserContext,) -> Result<Arc<CalcNode>> {- let parse_context = unsafe { context.parse_context.as_ref() }.ok_or(CalcParseError::NotHandled)?;+ let parse_context = context.parse_context.ok_or(CalcParseError::NotHandled)?;if (equals_ascii_case_insensitive(name, b"sibling-count") || equals_ascii_case_insensitive(name, b"sibling-index"))&& arguments.iter().all(ComponentValue::is_whitespace)&& context_allows_tree_counting_functions(parse_context)@@ -602,7 +603,7 @@ fn parse_random_value_sharing(StyleValueData::Number { value }}ComponentKind::Function { ref name, ref values } if math_function_from_name(name).is_some() => {- let parse_context = unsafe { context.parse_context.as_ref() }.ok_or(CalcParseError::NotHandled)?;+ let parse_context = context.parse_context.ok_or(CalcParseError::NotHandled)?;parse_calculated_numeric_value_with_ranges(parse_context,context.property,@@ -665,11 +666,11 @@ fn parse_random_value_sharing(}fn parse_random(arguments: &[&[ComponentValue]], context: CalcParserContext) -> Result<Arc<CalcNode>> {- if !context.allow_random_functions || context.random_function_index.is_null() {+ let Some(random_function_index) = context.random_function_index.filter(|_| context.allow_random_functions) else {return Err(CalcParseError::NotHandled);- }- let index = unsafe { *context.random_function_index };- unsafe { *context.random_function_index += 1 };+ };+ let index = random_function_index.get();+ random_function_index.set(index + 1);let auto_name = random_auto_name(context, index);let explicit_sharing = arguments.first()@@ -776,17 +777,17 @@ mod tests {let values =consume_a_list_of_component_values(tokenize_for_parser(b"random(element-shared, 1px, 3px)")).unwrap();let (name, values) = values[0].function().unwrap();- let mut random_function_index = 4;+ let random_function_index = RandomFunctionIndex::new(4);let context = CalcParserContext {percentages_resolve_as: None,property: 1,- random_function_index: &raw mut random_function_index,+ random_function_index: Some(&random_function_index),allowed_color_channels: 0,allow_random_functions: true,- parse_context: std::ptr::null(),+ parse_context: None,};let parsed = parse_a_calc_function_node(name, values, context).unwrap();assert!(matches!(&*parsed, CalcNode::Random { .. }));- assert_eq!(random_function_index, 5);+ assert_eq!(random_function_index.get(), 5);}}diff --git a/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/color_parser.rsindex 09fa0f155c4..c25479c3e51 100644--- a/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs@@ -374,7 +374,7 @@ fn parse_calculated_numeric(random_function_index: context.random_function_index,allowed_color_channels,allow_random_functions: context_allows_random_functions(context),- parse_context: std::ptr::from_ref(context).cast(),+ parse_context: Some(context),},) {Ok(root) => root,@@ -1085,19 +1085,7 @@ mod tests {use crate::css::parser::component_value::consume_a_list_of_component_values;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(source: &str) -> Option<StyleValueData> {diff --git a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rsindex ab82f094bd5..0633036c409 100644--- a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs@@ -535,19 +535,7 @@ mod tests {use std::sync::Arc;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(at_rule: u8, name: &str, source: &str) -> Option<StyleValueData> {diff --git a/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rsindex b294476a172..95301f9b1b4 100644--- a/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs@@ -687,19 +687,7 @@ mod tests {use crate::css::property_metadata::property_id;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}#[test]diff --git a/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rsindex 5c721c1db9d..ee7d58d29b4 100644--- a/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs@@ -1443,19 +1443,7 @@ mod tests {use crate::css::parser::component_value::consume_a_list_of_component_values;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(property: u16, source: &str) -> ParseOutcome {diff --git a/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rsindex 1ca2b06c8a2..0ddee98cf0c 100644--- a/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs@@ -723,19 +723,7 @@ mod tests {use crate::css::parser::component_value::consume_a_list_of_component_values;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(property: u16, source: &str) -> ParseOutcome {diff --git a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rsindex bc889d6e671..d8de4766926 100644--- a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs@@ -1625,19 +1625,7 @@ mod tests {use crate::css::parser::component_value::consume_a_list_of_component_values;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(property: u16, source: &str) -> ParseOutcome {diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rsindex 020b850ebf8..8f666c895a3 100644--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs@@ -2004,7 +2004,7 @@ fn media_value_parse_context<'a>(value_context: &'a FfiValueParsingContext<'a>)document_url: ak::Span::default(),document_base_url: ak::Span::default(),length_resolution_context: None,- random_function_index: std::ptr::null_mut(),+ random_function_index: None,}}diff --git a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rsindex 58fbcaec003..383a5ce9507 100644--- a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs@@ -5,7 +5,7 @@*/use super::syntax_parser::ParsedStyleSheet;-use super::value_parser::{FfiValueParsingContext, ParseContext};+use super::value_parser::{FfiValueParsingContext, ParseContext, RandomFunctionIndex};use crate::css::css_tokenizer::TokenizerInput;use crate::css::ffi_support::FfiUtf16View;use crate::css::style_compute::{FfiFontMetrics, FfiLengthResolutionContext};@@ -178,7 +178,7 @@ fn own_url(bytes: &[u8]) -> Option<Box<[u16]>> {}impl ContextKey {- unsafe fn new(context: &ParseContext) -> Option<Self> {+ fn new(context: &ParseContext) -> Option<Self> {// Keep this exhaustive so new parsing inputs cannot silently bypass the cache key.let ParseContext {in_quirks_mode,@@ -229,7 +229,7 @@ impl ContextKey {],value_contexts,declared_namespaces,- random_function_index: unsafe { random_function_index.as_ref() }.copied(),+ random_function_index: random_function_index.map(RandomFunctionIndex::get),},document_base_url: own_url(document_base_url.as_slice())?,length_resolution,@@ -374,15 +374,13 @@ fn find(entries: &Entries, hash: u64, key: &StyleSheetKey) -> Option<Arc<ParsedS})}-/// # Safety-/// All pointers in `context` must remain valid for this call, just as for parsing.-pub(super) unsafe fn parse_with_cache(+pub(super) fn parse_with_cache(source: TokenizerInput<'_>,context: Option<&ParseContext>,parse: impl FnOnce() -> ParsedStyleSheet,) -> Arc<ParsedStyleSheet> {let context_key = match context {- Some(context) => match unsafe { ContextKey::new(context) } {+ Some(context) => match ContextKey::new(context) {Some(key) => Some(key),None => return Arc::new(parse()),},@@ -422,13 +420,15 @@ pub(super) unsafe fn parse_with_cache(};if let Some(sheet) = cached {sheet.cache_metadata.as_ref().unwrap().dependencies.record();- if let Some(counter) = context.and_then(|context| unsafe { context.random_function_index.as_mut() }) {- *counter = sheet- .cache_metadata- .as_ref()- .unwrap()- .final_random_function_index- .unwrap();+ if let Some(counter) = context.and_then(|context| context.random_function_index) {+ counter.set(+ sheet+ .cache_metadata+ .as_ref()+ .unwrap()+ .final_random_function_index+ .unwrap(),+ );}return sheet;}@@ -456,8 +456,8 @@ pub(super) unsafe fn parse_with_cache(key,dependencies,final_random_function_index: context- .and_then(|context| unsafe { context.random_function_index.as_ref() })- .copied(),+ .and_then(|context| context.random_function_index)+ .map(RandomFunctionIndex::get),});let sheet = Arc::new(sheet);entries.entry(hash).or_default().push(Arc::downgrade(&sheet));diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rsindex ca7ddb8a1c3..a875a6eb036 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs@@ -511,8 +511,9 @@ pub unsafe extern "C" fn rust_parse_with_syntax(#[cfg(test)]mod tests {use super::*;+ use crate::css::parser::value_parser::RandomFunctionIndex;- fn context(random_function_index: &mut usize) -> ParseContext<'static> {+ fn context(random_function_index: &RandomFunctionIndex) -> ParseContext<'_> {ParseContext {in_quirks_mode: false,is_svg_presentation_attribute: false,@@ -524,7 +525,7 @@ mod tests {document_url: ak::Span::default(),document_base_url: ak::Span::default(),length_resolution_context: None,- random_function_index,+ random_function_index: Some(random_function_index),}}@@ -591,8 +592,8 @@ mod tests {#[test]fn parses_values_against_syntax() {- let mut random_function_index = 0;- let context = context(&mut random_function_index);+ let random_function_index = RandomFunctionIndex::default();+ let context = context(&random_function_index);let syntax = parse_syntax(&utf16("<length> | <number>#"), true).unwrap();assert!(parse_with_syntax(&context, &utf16("12px"), &syntax).is_some());assert!(parse_with_syntax(&context, &utf16("1, 2, calc(1 + 2)"), &syntax).is_some());diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rsindex 5004195b9a3..a9b233815e2 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs@@ -1951,8 +1951,8 @@ pub(crate) fn supports_declaration_matches(context: &ParseContext, source: &[u16value_context.value_contexts = ak::Span::new(std::slice::from_ref(&property_context));value_context.length_resolution_context = None;let outcome = parse_css_value_with_utf16_source(&value_context, property_id, &declaration.value, source.as_ref());- if let Some(random_function_index) = unsafe { context.random_function_index.as_mut() } {- *random_function_index = 0;+ if let Some(random_function_index) = context.random_function_index {+ random_function_index.set(0);}matches!(outcome, ParseOutcome::Parsed(_))}@@ -2126,7 +2126,7 @@ struct ParsedRule {}// Parser state is discarded before publishing the owned result.-struct SyntaxParseBuilder {+struct SyntaxParseBuilder<'a> {declarations_kind: NestedDeclarationsKind,values: Vec<u16>,declarations: Vec<ParsedDeclaration>,@@ -2141,7 +2141,7 @@ struct SyntaxParseBuilder {// Whether a top-level @import or @namespace rule appended next is still in its ordering window.import_rules_valid: bool,namespace_rules_valid: bool,- parse_context: *const ParseContext<'static>,+ parse_context: Option<&'a ParseContext<'a>>,preserve_property_source_text: bool,dedup: DeclarationDedup,}@@ -2723,9 +2723,9 @@ fn invalid_location_inner_name(rule: &Rule, rule_kind: ParsedRuleKind, outer_nam}}-impl SyntaxParseBuilder {+impl<'a> SyntaxParseBuilder<'a> {fn collect_declaration_errors(&self) -> Box<[usize]> {- fn visit_item(sheet: &SyntaxParseBuilder, item: &ParsedRuleChild, errors: &mut Vec<usize>) {+ fn visit_item(sheet: &SyntaxParseBuilder<'_>, item: &ParsedRuleChild, errors: &mut Vec<usize>) {match item {ParsedRuleChild::Declarations(list) => {for index in sheet.declaration_ranges[list.local_identity as usize].clone() {@@ -2747,7 +2747,7 @@ impl SyntaxParseBuilder {}}}- fn visit_rule(sheet: &SyntaxParseBuilder, rule: &ParsedRule, errors: &mut Vec<usize>) {+ fn visit_rule(sheet: &SyntaxParseBuilder<'_>, rule: &ParsedRule, errors: &mut Vec<usize>) {match rule.rule_kind {ParsedRuleKind::Qualified if rule.selector_list.is_some() => {}ParsedRuleKind::Container@@ -2836,8 +2836,8 @@ impl SyntaxParseBuilder {parsed}- pub(crate) fn new(parse_context: *const ParseContext, preserve_property_source_text: bool) -> Self {- let declared_namespaces = (unsafe { parse_context.as_ref() })+ pub(crate) fn new(parse_context: Option<&'a ParseContext<'a>>, preserve_property_source_text: bool) -> Self {+ let declared_namespaces = parse_context.map(declared_namespaces_from_context).unwrap_or_default().into_iter()@@ -2860,7 +2860,7 @@ impl SyntaxParseBuilder {declared_namespaces,import_rules_valid: true,namespace_rules_valid: true,- parse_context: parse_context.cast(),+ parse_context,preserve_property_source_text,dedup: DeclarationDedup::default(),}@@ -3007,14 +3007,13 @@ impl SyntaxParseBuilder {declaration: &Declaration,source_utf16: &[u16],) -> (u16, u8, FfiDeclarationRejection, Option<Arc<StyleValueData>>) {- if self.parse_context.is_null() {+ let Some(parse_context) = self.parse_context else {return (u16::MAX, u8::MAX, FfiDeclarationRejection::None, None);- }+ };if !declaration.is_property {let Some(at_rule) = descriptor_at_rule(declaration.rule_context) else {return (u16::MAX, u8::MAX, FfiDeclarationRejection::None, None);};- let parse_context = unsafe { &*self.parse_context };return match parse_descriptor(parse_context,at_rule,@@ -3042,7 +3041,6 @@ impl SyntaxParseBuilder {return (u16::MAX, u8::MAX, rejection, None);};- let parse_context = unsafe { &*self.parse_context };let mut value_contexts = parse_context.value_contexts.as_slice().to_vec();value_contexts.push(FfiValueParsingContext {kind: FfiValueParsingContextKind::Property,@@ -3054,8 +3052,8 @@ impl SyntaxParseBuilder {context.value_contexts = ak::Span::new(&value_contexts);let outcome = parse_css_value_with_utf16_source(&context, property_id, &declaration.value, source_utf16);- if let Some(random_function_index) = unsafe { parse_context.random_function_index.as_mut() } {- *random_function_index = 0;+ if let Some(random_function_index) = parse_context.random_function_index {+ random_function_index.set(0);}match outcome {ParseOutcome::Parsed(value) => (property_id, u8::MAX, FfiDeclarationRejection::None, Some(value)),@@ -3092,12 +3090,11 @@ impl SyntaxParseBuilder {font_feature_maximum_value_count: Option<usize>,) -> (usize, usize, Option<Arc<DescriptorBlockData>>) {let start = self.declarations.len();- if !self.parse_context.is_null()+ if let Some(context) = self.parse_context&& declarations.first().is_some_and(|declaration| descriptor_at_rule(declaration.rule_context).is_some()){- let context = unsafe { &*self.parse_context };let descriptors = collect_descriptors(declarations, context);for descriptor in &descriptors {self.append_collected_declaration(descriptor);@@ -3306,7 +3303,7 @@ impl SyntaxParseBuilder {),_ => None,};- let parse_context = unsafe { self.parse_context.as_ref() };+ let parse_context = self.parse_context;let declared_namespaces = self.declared_namespaces.iter()@@ -3697,24 +3694,20 @@ fn token_diagnostics(tokens: &[ParserToken]) -> Vec<FfiSyntaxDiagnostic> {.collect()}-/// # Safety-/// The parse context and its referenced data must remain valid during parsing.-pub(crate) unsafe fn parse_shared_stylesheet(+pub(crate) fn parse_shared_stylesheet(source: TokenizerInput<'_>,- parse_context: *const ParseContext,+ parse_context: Option<&ParseContext<'_>>,) -> Arc<ParsedStyleSheet> {- unsafe {- parse_with_cache(source, parse_context.as_ref(), || {- let mut parser = Parser::streaming(source);- let mut parse = SyntaxParseBuilder::new(parse_context, false);- while let Some(rule) = parser.consume_next_stylesheet_rule() {- parse.append_root(&rule);- }- // As in every other parse, the tokens' own diagnostics come ahead of the rules'.- parse.diagnostics.splice(0..0, parser.tokens.diagnostics);- parse.finish()- })- }+ parse_with_cache(source, parse_context, || {+ let mut parser = Parser::streaming(source);+ let mut parse = SyntaxParseBuilder::new(parse_context, false);+ while let Some(rule) = parser.consume_next_stylesheet_rule() {+ parse.append_root(&rule);+ }+ // As in every other parse, the tokens' own diagnostics come ahead of the rules'.+ parse.diagnostics.splice(0..0, parser.tokens.diagnostics);+ parse.finish()+ })}fn rule_contexts(contexts: &[u8]) -> Option<Vec<RuleContext>> {@@ -3730,50 +3723,39 @@ fn rule_contexts(contexts: &[u8]) -> Option<Vec<RuleContext>> {.collect()}-/// # Safety-/// The source and parse context must remain readable during this call.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_parse_css_stylesheet_syntax(+pub extern "C" fn rust_parse_css_stylesheet_syntax(source: FfiUtf16View,- parse_context: *const ParseContext,+ parse_context: Option<&ParseContext<'_>>,) -> *const ParsedStyleSheet {let Some(source) = source.units() else {return std::ptr::null();};- Arc::into_raw(unsafe { parse_shared_stylesheet(source, parse_context) })+ Arc::into_raw(parse_shared_stylesheet(source, parse_context))}/// Parses exactly one CSS rule into a Rust-owned arena.-///-/// # Safety-/// The source, context array, and parse context must remain readable during this call.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_parse_css_rule_syntax(+pub extern "C" fn rust_parse_css_rule_syntax(source: FfiUtf16View,- contexts: *const u8,- context_count: usize,+ contexts: ak::Span<'_, u8>,nested: bool,- parse_context: *const ParseContext,+ parse_context: Option<&ParseContext<'_>>,) -> *const ParsedStyleSheet {let Some(source) = source.units() else {return std::ptr::null_mut();};- let Some(contexts) = (unsafe { crate::bytes_from_raw(contexts, context_count) }) else {+ let Some(contexts) = rule_contexts(contexts.as_slice()) else {return std::ptr::null_mut();};- let Some(contexts) = rule_contexts(contexts) else {- return std::ptr::null_mut();- };- Arc::into_raw(unsafe { parse_shared_rule(source, contexts, nested, parse_context) })+ Arc::into_raw(parse_shared_rule(source, contexts, nested, parse_context))}-/// # Safety-/// The parse context and its referenced data must remain valid during parsing.-pub(crate) unsafe fn parse_shared_rule(+pub(crate) fn parse_shared_rule(source: TokenizerInput<'_>,contexts: Vec<RuleContext>,nested: bool,- parse_context: *const ParseContext,+ parse_context: Option<&ParseContext<'_>>,) -> Arc<ParsedStyleSheet> {let (parser, diagnostics) = Parser::from_source(source, contexts);let mut parse = SyntaxParseBuilder::new(parse_context, false);@@ -3903,35 +3885,31 @@ pub extern "C" fn rust_css_syntax_parse_descriptor_block(}/// Parses block contents into a Rust-owned arena.-///-/// # Safety-/// All pointers must remain readable for their accompanying lengths during this call.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_parse_css_block_syntax(+pub extern "C" fn rust_parse_css_block_syntax(source: FfiUtf16View,- contexts: *const u8,- context_count: usize,- parse_context: *const ParseContext,+ contexts: ak::Span<'_, u8>,+ parse_context: Option<&ParseContext<'_>>,preserve_property_source_text: bool,) -> *const ParsedStyleSheet {let Some(source) = source.units() else {return std::ptr::null_mut();};- let Some(contexts) = (unsafe { crate::bytes_from_raw(contexts, context_count) }) else {+ let Some(contexts) = rule_contexts(contexts.as_slice()) else {return std::ptr::null_mut();};- let Some(contexts) = rule_contexts(contexts) else {- return std::ptr::null_mut();- };- Arc::into_raw(unsafe { parse_shared_block(source, contexts, parse_context, preserve_property_source_text) })+ Arc::into_raw(parse_shared_block(+ source,+ contexts,+ parse_context,+ preserve_property_source_text,+ ))}-/// # Safety-/// The parse context and its referenced data must remain valid during parsing.-pub(crate) unsafe fn parse_shared_block(+pub(crate) fn parse_shared_block(source: TokenizerInput<'_>,contexts: Vec<RuleContext>,- parse_context: *const ParseContext,+ parse_context: Option<&ParseContext<'_>>,preserve_property_source_text: bool,) -> Arc<ParsedStyleSheet> {let (mut parser, diagnostics) = Parser::from_source(source, contexts);@@ -3976,19 +3954,7 @@ mod tests {}pub(super) fn parse_context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse_test_rule_prelude_with_context(rule: &Rule) -> ParsedRulePrelude {@@ -3998,7 +3964,7 @@ mod tests {fn parse_test_stylesheet(source: &[u8]) -> ParsedStyleSheet {let rules = parse_stylesheet(source);let context = parse_context();- let mut parse = SyntaxParseBuilder::new(&raw const context, false);+ let mut parse = SyntaxParseBuilder::new(Some(&context), false);parse.append_roots(&rules);parse.finish()}@@ -4026,16 +3992,14 @@ mod tests {move || {let context = parse_context();let input = crate::css::css_tokenizer::TokenizerInput::Utf16(&source);- unsafe {- super::super::stylesheet_cache::parse_with_cache(input, Some(&context), || {- parses.fetch_add(1, Ordering::SeqCst);- if let Some((started, may_finish)) = &held {- started.wait();- may_finish.wait();- }- parse_test_stylesheet(b"a { color: red } b { color: blue }")- })- }+ super::super::stylesheet_cache::parse_with_cache(input, Some(&context), || {+ parses.fetch_add(1, Ordering::SeqCst);+ if let Some((started, may_finish)) = &held {+ started.wait();+ may_finish.wait();+ }+ parse_test_stylesheet(b"a { color: red } b { color: blue }")+ })}};let first = std::thread::spawn(parse(@@ -4061,10 +4025,11 @@ mod tests {use crate::css::ffi_support::FfiUtf16View;let parsed = std::thread::spawn(|| {let source = utf16("@未来 {} @media all { .目 { height: 13px; & {} 未知: 雪; width: 赤; } }");+ // SAFETY: The parse hands over one strong reference.let parse = unsafe {std::sync::Arc::from_raw(super::rust_parse_css_stylesheet_syntax(FfiUtf16View::from_utf16(&source),- &parse_context(),+ Some(&parse_context()),))};assert_eq!(crate::css::ffi_stats::THREAD_UNSAFE_CPP_CALLBACK_COUNT.get(), 0);@@ -4118,9 +4083,8 @@ mod tests {let parse = unsafe {std::sync::Arc::from_raw(super::rust_parse_css_block_syntax(FfiUtf16View::from_utf16(&source),- contexts.as_ptr(),- contexts.len(),- &parse_context(),+ ak::Span::new(&contexts),+ Some(&parse_context()),true,))};@@ -4202,7 +4166,7 @@ mod tests {#[test]fn exposes_token_diagnostics_with_source_spans() {- let mut parse = SyntaxParseBuilder::new(std::ptr::null(), false);+ let mut parse = SyntaxParseBuilder::new(None, false);let tokens =crate::css::css_tokenizer::tokenize_for_parser(&utf16("a { color: \"bad\n; background: url(foo\"bar) }"));parse.diagnostics = token_diagnostics(&tokens);@@ -4492,7 +4456,7 @@ mod tests {#[test]fn parses_selector_preludes_from_component_values() {let rules = parse_stylesheet(b"a {} :heading(1.0) {} a { > b {} @scope (> .start) to (> .end) {} }");- let mut parse = SyntaxParseBuilder::new(std::ptr::null(), false);+ let mut parse = SyntaxParseBuilder::new(None, false);parse.append_roots(&rules);assert!(parse.rules[0].selector_list.is_some());@@ -4508,7 +4472,7 @@ mod tests {assert!(selectors.end.is_some());let rules = parse_stylesheet(b"@media all { > b {} @scope (> .start) {} }");- let mut parse = SyntaxParseBuilder::new(std::ptr::null(), false);+ let mut parse = SyntaxParseBuilder::new(None, false);parse.append_roots(&rules);let [ParsedRuleChild::Rule(group_child), ParsedRuleChild::Rule(scope_rule)] = &*parse.rules[0].children else {panic!("expected nested style and scope rules")@@ -4563,7 +4527,7 @@ mod tests {let rules = parse_stylesheet(b"@media screen and (width > 1px) {} @supports (display: grid) {} @container card (width > 1px), style(--theme: dark) {} @supports {}",);- let mut parse = SyntaxParseBuilder::new(std::ptr::null(), false);+ let mut parse = SyntaxParseBuilder::new(None, false);parse.append_roots(&rules);let media = &parse.rules[0];diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rsindex dddf39effc4..8cc786bf0b2 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs@@ -20,9 +20,8 @@ fn declarations(source: &str) -> crate::css::declaration_block::DeclarationBlockunsafe {let parse = std::sync::Arc::from_raw(super::rust_parse_css_block_syntax(view(&source),- contexts.as_ptr(),- contexts.len(),- &super::tests::parse_context(),+ ak::Span::new(&contexts),+ Some(&super::tests::parse_context()),false,));*Box::from_raw(super::rust_css_syntax_parse_declaration_block(&*parse))@@ -46,14 +45,14 @@ fn view(source: &[u16]) -> FfiUtf16View<'_> {}fn parse(source: &[u16], context: &crate::css::parser::value_parser::ParseContext) -> Arc<ParsedStyleSheet> {- unsafe { parse_shared_stylesheet(TokenizerInput::Utf16(source), context) }+ parse_shared_stylesheet(TokenizerInput::Utf16(source), Some(context))}fn parse_shared_on_worker(source: &'static str) -> Arc<ParsedStyleSheet> {std::thread::spawn(move || {let source = utf16(source);let context = super::tests::parse_context();- let parse = || unsafe { parse_shared_stylesheet(TokenizerInput::Utf16(&source), &context) };+ let parse = || parse_shared_stylesheet(TokenizerInput::Utf16(&source), Some(&context));let first = parse();let second = parse();assert!(Arc::ptr_eq(&first, &second));@@ -81,7 +80,7 @@ fn builder_constructs_one_rule_tree_with_dense_unique_identities() {b"@media all { .parent { & {} color: red; @supports (display: grid) { width: 13px; } } } @font-face { font-family: Test; src: url(font.woff); }",);let context = super::tests::parse_context();- let mut builder = super::SyntaxParseBuilder::new(&context, false);+ let mut builder = super::SyntaxParseBuilder::new(Some(&context), false);builder.append_roots(&rules);assert_eq!(builder.rules.len(), 2);let mut identities = std::collections::BTreeSet::new();@@ -730,13 +729,13 @@ fn cache_keys_include_parsing_context_and_replay_side_effects() {assert!(!Arc::ptr_eq(&tracked, &tracked_again));context.length_resolution_context = None;- let mut random_index = 7;- context.random_function_index = &raw mut random_index;+ let random_index = crate::css::parser::value_parser::RandomFunctionIndex::new(7);+ context.random_function_index = Some(&random_index);let with_counter = parse(&source, &context);- let final_index = random_index;- random_index = 7;+ let final_index = random_index.get();+ random_index.set(7);let with_counter_again = parse(&source, &context);- assert_eq!(random_index, final_index);+ assert_eq!(random_index.get(), final_index);assert!(Arc::ptr_eq(&with_counter, &with_counter_again));}@@ -744,7 +743,7 @@ fn cache_keys_include_parsing_context_and_replay_side_effects() {fn cache_shares_ascii_and_utf16_sources() {let source = b".cached { width: 13px }";let context = super::tests::parse_context();- let ascii = unsafe { parse_shared_stylesheet(TokenizerInput::Ascii(source), &context) };+ let ascii = parse_shared_stylesheet(TokenizerInput::Ascii(source), Some(&context));let wide = parse(&utf16(".cached { width: 13px }"), &context);assert!(Arc::ptr_eq(&ascii, &wide));}@@ -1168,14 +1167,12 @@ fn function_descriptor_blocks_retain_worker_parsed_values() {use crate::css::descriptor_block::FfiDescriptorBlock;let (data, parsed_values) = std::thread::spawn(|| {let source = utf16("--色: 13px; result: var(--色)");- let parse = unsafe {- super::parse_shared_block(- TokenizerInput::Utf16(&source),- vec![super::RuleContext::AtFunction],- &super::tests::parse_context(),- false,- )- };+ let parse = super::parse_shared_block(+ TokenizerInput::Utf16(&source),+ vec![super::RuleContext::AtFunction],+ Some(&super::tests::parse_context()),+ false,+ );assert_eq!(parse.items.len(), 1);let ParsedRuleChild::Declarations(list) = &parse.items[0] else {panic!()diff --git a/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rsindex 99d95704d05..36d8dbe7e90 100644--- a/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs@@ -822,19 +822,7 @@ mod tests {use crate::css::parser::component_value::consume_a_list_of_component_values;fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(property: u16, source: &str) -> ParseOutcome {diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rsindex 82ca780cdeb..bfb980302b6 100644--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs@@ -116,6 +116,26 @@ pub struct FfiValueParsingContext<'a> {pub name: FfiUtf16View<'a>,}+/// The counter a parse numbers its `random()` functions with, which C++ lends as a `size_t*`.+#[repr(transparent)]+#[derive(Default)]+pub struct RandomFunctionIndex(std::cell::Cell<usize>);++impl RandomFunctionIndex {+ #[cfg(test)]+ pub(crate) fn new(index: usize) -> Self {+ Self(std::cell::Cell::new(index))+ }++ pub(crate) fn get(&self) -> usize {+ self.0.get()+ }++ pub(crate) fn set(&self, index: usize) {+ self.0.set(index);+ }+}+/// Parser state required by CSS value parsing, borrowing what it names for `'a`.#[repr(C)]#[derive(Clone, Copy)]@@ -130,7 +150,7 @@ pub struct ParseContext<'a> {pub document_url: ak::Span<'a, u8>,pub document_base_url: ak::Span<'a, u8>,pub length_resolution_context: Option<&'a crate::css::style_compute::FfiLengthResolutionContext>,- pub random_function_index: *mut usize,+ pub random_function_index: Option<&'a RandomFunctionIndex>,}/// An empty context: no value contexts, namespaces or URLs, outside quirks mode.@@ -147,7 +167,7 @@ impl Default for ParseContext<'_> {document_url: ak::Span::default(),document_base_url: ak::Span::default(),length_resolution_context: None,- random_function_index: std::ptr::null_mut(),+ random_function_index: None,}}}@@ -1209,7 +1229,7 @@ pub(crate) fn parse_calculated_numeric_value_with_ranges(random_function_index: context.random_function_index,allowed_color_channels: 0,allow_random_functions: context_allows_random_functions(context),- parse_context: std::ptr::from_ref(context).cast(),+ parse_context: Some(context),},) {Ok(root) => root,@@ -3773,7 +3793,7 @@ pub(crate) fn parse_initial_value(property: u16) -> Option<Arc<StyleValueData>>document_url: ak::Span::default(),document_base_url: ak::Span::default(),length_resolution_context: None,- random_function_index: std::ptr::null_mut(),+ random_function_index: None,};let values = component_values_from_source(property_initial_value(property).as_bytes()).ok()?;let presence = SubstitutionFunctionsPresence::default();@@ -6276,19 +6296,7 @@ mod tests {}fn context() -> ParseContext<'static> {- ParseContext {- in_quirks_mode: false,- is_svg_presentation_attribute: false,- is_substituted_value: false,- contains_attr_tainted_values: false,- is_ua_style_sheet: false,- value_contexts: ak::Span::default(),- declared_namespaces: None,- document_url: ak::Span::default(),- document_base_url: ak::Span::default(),- length_resolution_context: None,- random_function_index: std::ptr::null_mut(),- }+ ParseContext::default()}fn parse(property: u16, source: &str) -> ParseOutcome {@@ -6986,7 +6994,7 @@ mod tests {] {assert!(matches!(parse(property, source), ParseOutcome::Parsed(_)), "{source}");}- let mut random_function_index = 0;+ let random_function_index = RandomFunctionIndex::default();let mut random_context = context();let value_context = FfiValueParsingContext {kind: FfiValueParsingContextKind::Property,@@ -6995,7 +7003,7 @@ mod tests {name: FfiUtf16View::default(),};random_context.value_contexts = ak::Span::new(std::slice::from_ref(&value_context));- random_context.random_function_index = &raw mut random_function_index;+ random_context.random_function_index = Some(&random_function_index);assert!(matches!(parse_with_context(&random_context,@@ -7323,7 +7331,7 @@ mod tests {};assert!(matches!(&*value, StyleValueData::OpacityValue { .. }));}- let mut random_function_index = 0;+ let random_function_index = RandomFunctionIndex::default();let mut random_context = context();let property_context = FfiValueParsingContext {kind: FfiValueParsingContextKind::Property,@@ -7332,19 +7340,19 @@ mod tests {name: FfiUtf16View::default(),};random_context.value_contexts = ak::Span::new(std::slice::from_ref(&property_context));- random_context.random_function_index = &raw mut random_function_index;+ random_context.random_function_index = Some(&random_function_index);let ParseOutcome::Parsed(value) = parse_with_context(&random_context, property_id::OPACITY, "random(0, 1)")else {panic!("random should parse with property parser state");};assert!(matches!(&*value, StyleValueData::OpacityValue { .. }));- assert_eq!(random_function_index, 1);+ assert_eq!(random_function_index.get(), 1);assert!(matches!(parse_with_context(&random_context, property_id::OPACITY, "random(0, random(0, 1))"),ParseOutcome::Parsed(_)));- assert_eq!(random_function_index, 3);+ assert_eq!(random_function_index.get(), 3);}#[test]@@ -7380,7 +7388,7 @@ mod tests {#[test]fn rejects_random_in_canvas_colors() {- let mut random_function_index = 0;+ let random_function_index = RandomFunctionIndex::default();let value_contexts = [FfiValueParsingContext {kind: FfiValueParsingContextKind::Special,@@ -7397,7 +7405,7 @@ mod tests {];let mut canvas_context = context();canvas_context.value_contexts = ak::Span::new(&value_contexts);- canvas_context.random_function_index = &raw mut random_function_index;+ canvas_context.random_function_index = Some(&random_function_index);assert!(matches!(parse_with_context(@@ -7407,7 +7415,7 @@ mod tests {),ParseOutcome::Invalid));- assert_eq!(random_function_index, 0);+ assert_eq!(random_function_index.get(), 0);}#[test]diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rsindex d88373569d4..5fbfeddcabd 100644--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs@@ -544,7 +544,7 @@ mod tests {let view = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parsed = unsafe { parse_shared_stylesheet(view, &context) };+ let parsed = parse_shared_stylesheet(view, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parsed);let media = MediaList::new(Default::default());NativeStyleSheet::new(rules, media)@@ -1186,9 +1186,8 @@ mod tests {let units: Vec<_> = source.encode_utf16().collect();let parsed = std::thread::spawn(move || {let context = ParseContext::default();- let parsed = unsafe {- parse_shared_stylesheet(crate::css::css_tokenizer::TokenizerInput::Utf16(&units), &context)- };+ let parsed =+ parse_shared_stylesheet(crate::css::css_tokenizer::TokenizerInput::Utf16(&units), Some(&context));assert_eq!(RULE_OWNER_ALLOCATIONS.get(), 0);assert_eq!(DECLARATION_OWNER_ALLOCATIONS.get(), 0);assert_eq!(crate::css::descriptor_block::DESCRIPTOR_OWNER_ALLOCATIONS.get(), 0);@@ -1571,7 +1570,7 @@ mod tests {for (source, expected) in [("色|item { color: red; }", 1), ("未知|item { color: red; }", 0)] {let units: Vec<_> = source.encode_utf16().collect();let view = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);- let parsed = unsafe { parse_shared_stylesheet(view, &context) };+ let parsed = parse_shared_stylesheet(view, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parsed);assert_eq!(rules.materialized_rules().len(), expected);}diff --git a/Libraries/LibWeb/Rust/src/css/rule/function.rs b/Libraries/LibWeb/Rust/src/css/rule/function.rsindex 0d495560b54..388ecde886a 100644--- a/Libraries/LibWeb/Rust/src/css/rule/function.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/function.rs@@ -125,12 +125,10 @@ pub extern "C" fn rust_compiled_function_retain(pub(crate) fn compile_functions_for_testing(source: &str) -> Vec<CompiledFunction> {let units: Vec<_> = source.encode_utf16().collect();let context = crate::css::parser::value_parser::ParseContext::default();- let parsed = unsafe {- crate::css::parser::syntax_parser::parse_shared_stylesheet(- crate::css::css_tokenizer::TokenizerInput::Utf16(&units),- &raw const context,- )- };+ let parsed = crate::css::parser::syntax_parser::parse_shared_stylesheet(+ crate::css::css_tokenizer::TokenizerInput::Utf16(&units),+ Some(&context),+ );let rules = super::NativeRuleList::from_parsed(parsed);let mut compiled = Vec::new();let _ = rules.visit_rules(&mut |rule| {diff --git a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs b/Libraries/LibWeb/Rust/src/css/rule/mutation.rsindex 1e9113932a9..983d65e3a26 100644--- a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/mutation.rs@@ -122,7 +122,7 @@ mod tests {let view = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parsed = unsafe { parse_shared_stylesheet(view, &context) };+ let parsed = parse_shared_stylesheet(view, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parsed);let media = MediaList::new(Default::default());NativeStyleSheet::new(rules, media)diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rsindex 9a54cf5aef6..19aeca73af3 100644--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs@@ -1772,8 +1772,8 @@ impl RetainedState {reads_attributes.then(|| SubstitutionAttributes::of(&self.facts, node, self.html_element_namespace));// SAFETY: The values are the program's interned values, live for the call.let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(parent_store.clone(), values) };- let mut random_function_index = 0_usize;- let mut parse_context = registry_ref.parse_context(&mut random_function_index);+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();+ let mut parse_context = registry_ref.parse_context(&random_function_index);parse_context.in_quirks_mode = inputs.in_quirks_mode;let media_environment = self.document_media.environment();let style_query = reads_conditions@@ -2059,8 +2059,8 @@ impl RetainedState {// SAFETY: The values are live for the call.let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(base.clone(), values) };let registry = self.document_style_computation_inputs.custom_property_registry();- let mut random_function_index = 0_usize;- let mut parse_context = registry.parse_context(&mut random_function_index);+ 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();// The `style()` queries the declarations read were noted as they resolved beneath the animations.@@ -2262,8 +2262,8 @@ fn substitute_against_stores(let attributes = inputs.attributes;let functions = inputs.functions;let registry_ref = inputs.document.custom_property_registry();- let mut random_function_index = 0_usize;- let mut parse_context = registry_ref.parse_context(&mut random_function_index);+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();+ let mut parse_context = registry_ref.parse_context(&random_function_index);parse_context.in_quirks_mode = inputs.document.in_quirks_mode;let media_environment = inputs.media.environment();let mut resolution_environment = prepare_var_resolution_environment(diff --git a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs b/Libraries/LibWeb/Rust/src/css/style/native_rules.rsindex a82cc3acfb4..5da2ab7f709 100644--- a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs+++ b/Libraries/LibWeb/Rust/src/css/style/native_rules.rs@@ -192,7 +192,7 @@ mod tests {let view = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parsed = unsafe { parse_shared_stylesheet(view, &context) };+ let parsed = parse_shared_stylesheet(view, Some(&context));let rules = crate::css::rule::NativeRuleList::from_parsed(parsed);let media = MediaList::new(Default::default());NativeStyleSheet::new(rules, media)diff --git a/Libraries/LibWeb/Rust/src/css/style/tests.rs b/Libraries/LibWeb/Rust/src/css/style/tests.rsindex 342670fc2e6..71523c64d62 100644--- a/Libraries/LibWeb/Rust/src/css/style/tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/tests.rs@@ -27,9 +27,10 @@ fn native_rules(source: &str) -> std::rc::Rc<crate::css::rule::NativeRuleList> {use crate::css::parser::syntax_parser::parse_shared_stylesheet;let units: Vec<_> = source.encode_utf16().collect();let context = crate::css::parser::value_parser::ParseContext::default();- unsafe {- crate::css::rule::NativeRuleList::from_parsed(parse_shared_stylesheet(TokenizerInput::Utf16(&units), &context))- }+ crate::css::rule::NativeRuleList::from_parsed(parse_shared_stylesheet(+ TokenizerInput::Utf16(&units),+ Some(&context),+ ))}impl StyleEngine {diff --git a/Libraries/LibWeb/Rust/src/css/style_rule.rs b/Libraries/LibWeb/Rust/src/css/style_rule.rsindex f30163d2549..a69019034a7 100644--- a/Libraries/LibWeb/Rust/src/css/style_rule.rs+++ b/Libraries/LibWeb/Rust/src/css/style_rule.rs@@ -63,7 +63,7 @@ mod tests {let source = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);// All context fields are booleans, integers, or nullable pointers.let context = ParseContext::default();- let parsed = unsafe { parse_shared_stylesheet(source, &context) };+ let parsed = parse_shared_stylesheet(source, Some(&context));crate::css::rule::NativeRuleList::from_parsed(parsed)}diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rsindex f8034e9ee19..3653107fb04 100644--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs@@ -666,7 +666,7 @@ mod tests {let units: Vec<_> = source.encode_utf16().collect();// All fields are booleans, integers, or nullable pointers; zero is an empty parser context.let context = ParseContext::default();- unsafe { parse_shared_stylesheet(crate::css::css_tokenizer::TokenizerInput::Utf16(&units), &context) }+ parse_shared_stylesheet(crate::css::css_tokenizer::TokenizerInput::Utf16(&units), Some(&context))}fn sheet(parsed: &std::sync::Arc<ParsedStyleSheet>) -> Rc<NativeStyleSheet> {diff --git a/Tests/LibWeb/TestCSSSyntaxParser.cpp b/Tests/LibWeb/TestCSSSyntaxParser.cppindex 30b78069eee..a422e0b244e 100644--- a/Tests/LibWeb/TestCSSSyntaxParser.cpp+++ b/Tests/LibWeb/TestCSSSyntaxParser.cpp@@ -244,7 +244,7 @@ TEST_CASE(native_function_fragments_preserve_declaration_context){ValueParserFFI::ParseContext context {};u8 rule_context = to_underlying(RuleContext::AtFunction);- auto* parse = ValueParserFFI::rust_parse_css_rule_syntax(ffi_utf16_view(u"@supports (display: block) { result: 50px; }"sv), &rule_context, 1, true, &context);+ auto* parse = ValueParserFFI::rust_parse_css_rule_syntax(ffi_utf16_view(u"@supports (display: block) { result: 50px; }"sv), ReadonlyBytes { &rule_context, 1 }, true, &context);RustRuleList rules { ValueParserFFI::rust_css_syntax_native_rules(parse) };ValueParserFFI::rust_css_syntax_parse_free(parse);EXPECT_EQ(rules.size(), 1u);@@ -252,7 +252,7 @@ TEST_CASE(native_function_fragments_preserve_declaration_context)EXPECT_EQ(ValueParserFFI::rust_rule_list_count(children), 1u);RustRule declarations { ValueParserFFI::rust_rule_list_at(children, 0) };EXPECT_EQ(declarations.type(), RustRule::Type::FunctionDeclarations);- parse = ValueParserFFI::rust_parse_css_block_syntax(ffi_utf16_view(u"result: 60px;"sv), &rule_context, 1, &context, false);+ parse = ValueParserFFI::rust_parse_css_block_syntax(ffi_utf16_view(u"result: 60px;"sv), ReadonlyBytes { &rule_context, 1 }, &context, false);RustRuleList block { ValueParserFFI::rust_css_syntax_native_rules(parse) };ValueParserFFI::rust_css_syntax_parse_free(parse);EXPECT_EQ(block.size(), 1u);@@ -354,7 +354,7 @@ static RustDeclarationBlock parse_native_declaration_block(Utf16View source)ValueParserFFI::ParseContext context {};u8 rule_context = to_underlying(RuleContext::Style);auto* parse = ValueParserFFI::rust_parse_css_block_syntax(- { nullptr, reinterpret_cast<u16 const*>(source.utf16_span().data()), source.length_in_code_units() }, &rule_context, 1, &context, false);+ { nullptr, reinterpret_cast<u16 const*>(source.utf16_span().data()), source.length_in_code_units() }, ReadonlyBytes { &rule_context, 1 }, &context, false);auto* block = ValueParserFFI::rust_css_syntax_parse_declaration_block(parse);ValueParserFFI::rust_css_syntax_parse_free(parse);return RustDeclarationBlock { block };