refactor(css): adapt native consumers to Stylo 0.22

Use owned parser errors and typed math payloads, keep the 128-level numeric parsing limit and preserve RangeError classification. Pin the native font shorthand port on Stylo 0.22 instead of adding callback exceptions.
This commit is contained in:
ldm0
2026-11-22 02:02:04 +08:00
parent d609e5fda3
commit 992d7c28d2
15 changed files with 75 additions and 88 deletions
+1 -2
View File
@@ -108,8 +108,7 @@ fn serialized_declaration_suffix_matches(suffix: &str, important: bool) -> bool
fn eof_open_curly_block_starts(css_text: &str) -> Vec<usize> {
let mut open_blocks = Vec::new();
let input = css_text;
let mut input = Parser::new(input);
let mut input = Parser::new(css_text);
collect_eof_open_curly_block_starts(&mut input, &mut open_blocks);
open_blocks
}
+2 -4
View File
@@ -185,8 +185,7 @@ mod tests {
use cssparser::Parser;
fn serialize(source: &str) -> String {
let input = source;
let mut parser = Parser::new(input);
let mut parser = Parser::new(source);
let token = parser.next().unwrap().clone();
let mut result = String::new();
serialize_css_token(&token, source, &mut result).unwrap();
@@ -253,8 +252,7 @@ mod tests {
("-2\\65 -foo", "e-foo", -2.0),
] {
let text = serialize(source);
let input = &text;
let mut parser = Parser::new(input);
let mut parser = Parser::new(&text);
let token = parser.next().unwrap().clone();
assert!(
matches!(&token, Token::Dimension { unit: parsed, .. } if parsed.as_ref() == unit),
+1 -2
View File
@@ -278,8 +278,7 @@ pub fn parse_property_rule_view_with_stylo(css_text: &str) -> Option<CssProperty
fn normalize_css_property_rule_view_name(mut view: CssPropertyRuleView) -> CssPropertyRuleView {
let decoded_name = {
let input = &view.name;
let mut parser = Parser::new(input);
let mut parser = Parser::new(&view.name);
parser
.expect_ident_cloned()
.ok()
+2 -4
View File
@@ -74,8 +74,7 @@ pub fn parse_typed_style_value(
return None;
}
// Empty or comment-only text cannot produce a CSSStyleValue for parse().
let input = css_text;
Parser::new(input).next().ok()?;
Parser::new(css_text).next().ok()?;
let base_url = base_url
.cloned()
.unwrap_or_else(|| url::Url::parse("about:blank").expect("static URL"));
@@ -154,8 +153,7 @@ pub fn reify_unparsed_style_value(
&fallback_url
}
};
let input = css_text;
let value = Parser::new(input)
let value = Parser::new(css_text)
.parse_entirely(|input| SpecifiedValue::parse(input, None, url_data))
.ok()?;
tokens::reify(value.css_text())
+1 -2
View File
@@ -32,8 +32,7 @@ impl Frame {
// Consume raw tokens without cssparser's component parser skipping nested
// blocks; the input has already passed Stylo's declaration-value validation.
fn next<'a>(source: &mut &'a str) -> Option<(Token<'a>, &'a str)> {
let input = *source;
let mut parser = Parser::new(input);
let mut parser = Parser::new(source);
let token = parser
.next_including_whitespace_and_comments()
.ok()?
@@ -1,7 +1,7 @@
use super::graph::Unit;
use super::*;
use crate::context_bootstrap::exposed_interfaces::TemplateBuildProfile;
use cssparser::{ParseError, ParseErrorKind};
use cssparser::{BasicParseErrorKind, ParseError, ParseErrorKind};
mod expression;
use expression::Expression;
@@ -39,7 +39,7 @@ enum Error {
// Bound parser recursion and native object creation independently of how much
// eager algebraic simplification reduces the resulting expression.
const MAX_DEPTH: usize = 128;
const MAX_DEPTH: u8 = 128;
const MAX_NODES: usize = 32_768;
struct Budget(usize);
@@ -103,27 +103,28 @@ pub(in crate::context_bootstrap::css_runtime::typed_om) fn from_declared<'s>(
}
fn parse_expression(source: &str) -> Result<Expression, Error> {
let mut input = ParserInput::new(source);
let mut parser = Parser::new(&mut input);
let mut parser = Parser::new(source);
parser.set_nested_block_limit(MAX_DEPTH);
let mut budget = Budget(MAX_NODES);
parser
.parse_entirely(|p| parse_value(p, &mut budget, 0, false))
.map_err(|error| match error.kind {
ParseErrorKind::Custom(error) => error,
ParseErrorKind::Basic(BasicParseErrorKind::TooManyNestedBlocks) => Error::TooLarge,
_ => Error::Syntax,
})
}
fn parse_value<'i>(
input: &mut Parser<'i, '_>,
input: &mut Parser<'i>,
budget: &mut Budget,
depth: usize,
in_math: bool,
) -> Result<Expression, ParseError<'i, Error>> {
if depth > MAX_DEPTH {
return Err(input.new_custom_error(Error::TooLarge));
) -> Result<Expression, ParseError<Error>> {
if depth > usize::from(MAX_DEPTH) {
return Err(ParseError::custom(Error::TooLarge));
}
budget.spend(1).map_err(|e| input.new_custom_error(e))?;
budget.spend(1).map_err(ParseError::custom)?;
input.skip_whitespace();
let start = input.position();
let token = input.next()?.clone();
@@ -133,7 +134,7 @@ fn parse_value<'i>(
Token::Dimension { unit, .. } => {
let unit = values::normalize_unit_name(unit)
.filter(|name| name != "number" && name != "percent")
.ok_or_else(|| input.new_custom_error(Error::Syntax))?;
.ok_or_else(|| ParseError::custom(Error::Syntax))?;
Some(unit)
}
_ => None,
@@ -142,7 +143,7 @@ fn parse_value<'i>(
// cssparser identifies and unescapes tokens; recover the source number
// as f64 rather than exposing the tokenizer's f32 rounding to WebIDL.
let value = moli_css_parse::css_numeric_token_value(&token, input.slice_from(start))
.ok_or_else(|| input.new_custom_error(Error::Syntax))?;
.ok_or_else(|| ParseError::custom(Error::Syntax))?;
return Ok(Expression::unit(Unit { value, unit }, in_math));
}
match token {
@@ -156,7 +157,7 @@ fn parse_value<'i>(
"infinity" => f64::INFINITY,
"-infinity" => f64::NEG_INFINITY,
"nan" => f64::NAN,
_ => return Err(input.new_custom_error(Error::Syntax)),
_ => return Err(ParseError::custom(Error::Syntax)),
};
Ok(Expression::unit(
Unit {
@@ -173,7 +174,7 @@ fn parse_value<'i>(
"min" | "max" => {
let children = p.parse_comma_separated(|p| parse_sum(p, budget, depth + 1))?;
let kind = if name == "min" { Kind::Min } else { Kind::Max };
Expression::operation(kind, children, budget).map_err(|e| p.new_custom_error(e))
Expression::operation(kind, children, budget).map_err(ParseError::custom)
}
"clamp" => {
let lower = optional_bound(p, budget, depth + 1)?;
@@ -187,28 +188,27 @@ fn parse_value<'i>(
(None, Some(b)) => (Kind::Min, vec![value, b]),
(None, None) => return Ok(value),
};
Expression::operation(kind, children, budget).map_err(|e| p.new_custom_error(e))
Expression::operation(kind, children, budget).map_err(ParseError::custom)
}
_ => Err(p.new_custom_error(Error::Syntax)),
_ => Err(ParseError::custom(Error::Syntax)),
})?;
// A calc() that reduces to a scalar still reifies as CSSMathSum;
// internal calc/parentheses do not create redundant wrapper nodes.
if name == "calc" && !in_math && expression.is_unit() {
Expression::unsimplified(Kind::Sum, vec![expression])
.map_err(|e| input.new_custom_error(e))
Expression::unsimplified(Kind::Sum, vec![expression]).map_err(ParseError::custom)
} else {
Ok(expression)
}
}
_ => Err(input.new_custom_error(Error::Syntax)),
_ => Err(ParseError::custom(Error::Syntax)),
}
}
fn optional_bound<'i>(
input: &mut Parser<'i, '_>,
input: &mut Parser<'i>,
budget: &mut Budget,
depth: usize,
) -> Result<Option<Expression>, ParseError<'i, Error>> {
) -> Result<Option<Expression>, ParseError<Error>> {
if input.try_parse(|p| p.expect_ident_matching("none")).is_ok() {
Ok(None)
} else {
@@ -217,10 +217,10 @@ fn optional_bound<'i>(
}
fn parse_sum<'i>(
input: &mut Parser<'i, '_>,
input: &mut Parser<'i>,
budget: &mut Budget,
depth: usize,
) -> Result<Expression, ParseError<'i, Error>> {
) -> Result<Expression, ParseError<Error>> {
let mut children = vec![parse_product(input, budget, depth)?];
loop {
let start = input.state();
@@ -238,23 +238,23 @@ fn parse_sum<'i>(
}
};
if !matches!(input.next_including_whitespace(), Ok(Token::WhiteSpace(_))) {
return Err(input.new_custom_error(Error::Syntax));
return Err(ParseError::custom(Error::Syntax));
}
let mut child = parse_product(input, budget, depth)?;
if subtract {
child = Expression::operation(Kind::Negate, vec![child], budget)
.map_err(|e| input.new_custom_error(e))?;
.map_err(ParseError::custom)?;
}
children.push(child);
}
Expression::operation(Kind::Sum, children, budget).map_err(|e| input.new_custom_error(e))
Expression::operation(Kind::Sum, children, budget).map_err(ParseError::custom)
}
fn parse_product<'i>(
input: &mut Parser<'i, '_>,
input: &mut Parser<'i>,
budget: &mut Budget,
depth: usize,
) -> Result<Expression, ParseError<'i, Error>> {
) -> Result<Expression, ParseError<Error>> {
let mut children = vec![parse_value(input, budget, depth, true)?];
loop {
let start = input.state();
@@ -269,9 +269,9 @@ fn parse_product<'i>(
let mut child = parse_value(input, budget, depth, true)?;
if divide {
child = Expression::operation(Kind::Invert, vec![child], budget)
.map_err(|e| input.new_custom_error(e))?;
.map_err(ParseError::custom)?;
}
children.push(child);
}
Expression::operation(Kind::Product, children, budget).map_err(|e| input.new_custom_error(e))
Expression::operation(Kind::Product, children, budget).map_err(ParseError::custom)
}
@@ -49,12 +49,16 @@ fn reify_native<'s>(
Work::Value(NumericValue::Math(value)) => {
let (kind, children): (_, &[NumericValue]) = match value {
MathValue::Sum(sum) => (Kind::Sum, &sum.values),
MathValue::Product(children) => (Kind::Product, children),
MathValue::Min(children) => (Kind::Min, children),
MathValue::Max(children) => (Kind::Max, children),
MathValue::Clamp(children) => (Kind::Clamp, children.as_ref()),
MathValue::Negate(child) => (Kind::Negate, std::slice::from_ref(child)),
MathValue::Invert(child) => (Kind::Invert, std::slice::from_ref(child)),
MathValue::Product(product) => (Kind::Product, &product.values),
MathValue::Min(min) => (Kind::Min, &min.values),
MathValue::Max(max) => (Kind::Max, &max.values),
MathValue::Clamp(clamp) => (Kind::Clamp, clamp.values.as_ref()),
MathValue::Negate(negate) => {
(Kind::Negate, std::slice::from_ref(&negate.value))
}
MathValue::Invert(invert) => {
(Kind::Invert, std::slice::from_ref(&invert.value))
}
};
// The style engine wraps a scalar calculation in a unary sum.
// At computed-value time it is the scalar CSSUnitValue.
@@ -73,8 +73,7 @@ fn serialize_tokens(mut source: &str) -> String {
// Read one raw token at a time, without a component-value parser consuming
// nested blocks or synthesizing closing tokens for arbitrary string input.
while !source.is_empty() {
let mut input = ParserInput::new(source);
let mut parser = Parser::new(&mut input);
let mut parser = Parser::new(source);
let Ok(token) = parser.next_including_whitespace_and_comments().cloned() else {
break;
};
@@ -1,12 +1,11 @@
use cssparser::{Parser, ParserInput, Token};
use cssparser::{Parser, Token};
// The property grammar and numeric type have already been established by
// Stylo. Recover a single numeric token's original double precision instead
// of exposing Stylo/cssparser's f32 rounding as a WebIDL double. Expressions
// and property-specific conversions beyond number/percentage use Stylo's value.
pub(super) fn from_literal(source: &str, target_unit: &str) -> Option<f64> {
let mut input = ParserInput::new(source);
let mut parser = Parser::new(&mut input);
let mut parser = Parser::new(source);
parser.skip_whitespace();
let start = parser.position();
let token = parser.next().ok()?.clone();
@@ -11,7 +11,7 @@ use crate::protocol_types::EmulatedMediaOverrides;
use crate::style_engine::{StyleViewport, media_list::evaluate_source_size_list};
use crate::types::{ImageRequestCorsMode, ImageRequestKey, SubresourceRequestInitiatorType};
use crate::util::{context_host_ptr_from_global_bridge, v8_string};
use cssparser::{Parser, ParserInput};
use cssparser::Parser;
use crate::style_engine::media_list::evaluate_media_query_list;
@@ -1040,8 +1040,7 @@ fn source_size_for_sizes_attribute(
) -> f64 {
let sizes = sizes.unwrap_or_default();
if allows_auto_sizes {
let mut input = ParserInput::new(sizes);
let mut parser = Parser::new(&mut input);
let mut parser = Parser::new(sizes);
if parser.expect_ident_matching("auto").is_ok()
&& (parser.is_exhausted() || parser.expect_comma().is_ok())
{
@@ -50,8 +50,10 @@ fn css_numeric_parse_bounds_input_work_and_recovers_after_errors() {
vm.eval(
r#"(() => {
const parse = CSSNumericValue.parse;
const good = 'calc('.repeat(64) + '1px' + ')'.repeat(64);
if (parse(good).to('px').value !== 1) return false;
for (const depth of [64, 96]) {
const good = 'calc('.repeat(depth) + '1px' + ')'.repeat(depth);
if (parse(good).to('px').value !== 1) return false;
}
for (const input of [
'calc('.repeat(2000) + '1px' + ')'.repeat(2000),
'calc(' + Array(40000).fill('1px').join(' + ') + ')',
@@ -14,7 +14,7 @@ use style::{
generics::calc::CalcUnits,
specified::{
Length, NoCalcLength,
calc::{CalcNode, CalcParseFlags, Leaf},
calc::{CalcNode, CalcNodeParseInPlaceOperations, CalcParseFlags, Leaf},
length::LengthUnit,
},
},
@@ -22,12 +22,11 @@ use style::{
pub(super) fn evaluate(sizes: &str, parser_context: &ParserContext, device: &Device) -> f64 {
Context::for_media_query_evaluation(device, QuirksMode::NoQuirks, |context| {
let input = sizes;
let mut parser = Parser::new(input);
let mut parser = Parser::new(sizes);
loop {
let result = parser.parse_until_before(Delimiter::Comma, |component| {
source_size(component, parser_context, context)
.ok_or_else(|| cssparser::ParseError::custom(()))
.ok_or_else(|| cssparser::ParseError::<()>::custom(()))
});
if let Ok(size) = result {
return size;
@@ -74,8 +73,7 @@ fn source_size<'i>(
let size = source_length(input.slice(value_start..value_end), parser_context, context)?;
let condition = input.slice(start..value_start);
let normalized = normalize_zero_math(condition, parser_context, context)?;
let condition_input = normalized.as_str();
let mut condition_parser = Parser::new(condition_input);
let mut condition_parser = Parser::new(&normalized);
if condition_parser.is_exhausted() {
return Some(size);
}
@@ -93,8 +91,7 @@ fn source_size<'i>(
}
fn source_length(raw: &str, parser_context: &ParserContext, context: &Context) -> Option<f64> {
let input = raw;
let mut parser = Parser::new(input);
let mut parser = Parser::new(raw);
let state = parser.state();
let function = matches!(parser.next().ok()?, Token::Function(_));
parser.reset(&state);
@@ -114,20 +111,21 @@ fn source_length(raw: &str, parser_context: &ParserContext, context: &Context) -
}
fn math_value(raw: &str, parser_context: &ParserContext, context: &Context) -> Option<Leaf> {
let input = raw;
let mut parser = Parser::new(input);
let location = parser.current_source_location();
let mut parser = Parser::new(raw);
let Token::Function(name) = parser.next().ok()?.clone() else {
return None;
};
let function = CalcNode::math_function(parser_context, &name, location).ok()?;
let function = CalcNode::math_function(parser_context, &name).ok()?;
let node = CalcNode::parse(
parser_context,
&mut parser,
function,
// Keep division and multiplication until after unit conversion, so
// CSS property conversion cannot hide a non-finite math result.
CalcParseFlags::new(CalcUnits::LENGTH).new_without_in_place_operations(),
CalcParseFlags {
in_place_operations: CalcNodeParseInPlaceOperations::No,
..CalcParseFlags::new(CalcUnits::LENGTH)
},
)
.ok()?;
parser.expect_exhausted().ok()?;
@@ -144,8 +142,7 @@ fn normalize_zero_math(
parser_context: &ParserContext,
context: &Context,
) -> Option<String> {
let input = raw;
let mut parser = Parser::new(input);
let mut parser = Parser::new(raw);
let mut copied = parser.position();
let mut replacements = Vec::new();
zero_math_ranges(&mut parser, parser_context, context, &mut replacements)?;
@@ -186,7 +183,7 @@ fn zero_math_ranges<'i>(
input
.parse_nested_block::<_, _, ()>(|block| {
zero_math_ranges(block, parser_context, context, replacements)
.ok_or_else(|| cssparser::ParseError::custom(()))
.ok_or_else(|| cssparser::ParseError::<()>::custom(()))
})
.ok()?;
}
+5 -8
View File
@@ -243,8 +243,7 @@ fn unused_forgiving_selector_marker(
}
fn outermost_forgiving_selector_argument_ranges(selector_text: &str) -> Option<Vec<Range<usize>>> {
let input = selector_text;
let mut parser = Parser::new(input);
let mut parser = Parser::new(selector_text);
let mut ranges = Vec::new();
collect_outermost_forgiving_selector_argument_ranges(&mut parser, &mut ranges)?;
Some(ranges)
@@ -274,7 +273,7 @@ fn collect_outermost_forgiving_selector_argument_ranges(
Ok(())
} else {
collect_outermost_forgiving_selector_argument_ranges(input, ranges)
.ok_or_else(|| ParseError::custom(()))
.ok_or_else(|| cssparser::ParseError::<()>::custom(()))
}
});
nested.ok()?;
@@ -286,7 +285,7 @@ fn collect_outermost_forgiving_selector_argument_ranges(
Token::ParenthesisBlock | Token::CurlyBracketBlock => {
let nested: Result<(), ParseError<()>> = input.parse_nested_block(|input| {
collect_outermost_forgiving_selector_argument_ranges(input, ranges)
.ok_or_else(|| ParseError::custom(()))
.ok_or_else(|| cssparser::ParseError::<()>::custom(()))
});
nested.ok()?;
previous_was_colon = false;
@@ -302,8 +301,7 @@ fn collect_outermost_forgiving_selector_argument_ranges(
}
fn top_level_comma_separated_selector_item_ranges(argument: &str) -> Option<Vec<Range<usize>>> {
let input = argument;
let mut parser = Parser::new(input);
let mut parser = Parser::new(argument);
let mut ranges = Vec::new();
let mut item_start = 0;
while !parser.is_exhausted() {
@@ -854,8 +852,7 @@ pub(crate) fn dom_api_selector_list_contains_known_pseudo_element(selector_text:
pub(crate) fn webkit_compat_pseudo_element_validation_selector(
selector_text: &str,
) -> Option<String> {
let input = selector_text;
let mut parser = Parser::new(input);
let mut parser = Parser::new(selector_text);
let mut replacements = Vec::new();
while !parser.is_exhausted() {
+1 -3
View File
@@ -701,9 +701,7 @@ impl SelectorsElement for QueryElement<'_> {
case_sensitivity: CaseSensitivity,
) -> bool {
if let Some(actual_units) = self.element().attribute_utf16_units("id") {
let expected_units = AsRef::<str>::as_ref(&**id)
.encode_utf16()
.collect::<Vec<_>>();
let expected_units = id.encode_utf16().collect::<Vec<_>>();
return match case_sensitivity {
CaseSensitivity::CaseSensitive => actual_units == expected_units.as_slice(),
CaseSensitivity::AsciiCaseInsensitive => self
+1 -2
View File
@@ -77,8 +77,7 @@ fn validate_dom_api_pseudo_element_selector_list(selector: &str) -> bool {
}
fn slotted_pseudo_element_validation_selector(selector_text: &str) -> Option<String> {
let input = selector_text;
let mut parser = cssparser::Parser::new(input);
let mut parser = cssparser::Parser::new(selector_text);
let mut replacements = Vec::new();
while !parser.is_exhausted() {