From 1261ba517615711e3be2dcaf0fca32495eb7cccd Mon Sep 17 00:00:00 2001 From: ldm0 Date: Mon, 28 Sep 2026 20:39:14 +0800 Subject: [PATCH] feat(css): parse numeric values and basic math expressions Add Window-only CSSNumericValue.parse with native Typed OM objects, f64 token recovery, type checking, and bounded calc/min/max/clamp algebra. Preserve WebIDL conversion and callee realms, and support the x resolution unit alias. Cover grammar, simplification, precision, realms, and limits. --- .../css_runtime/typed_om/math/conversion.rs | 3 +- .../css_runtime/typed_om/math/mod.rs | 3 + .../css_runtime/typed_om/math/parsing.rs | 244 ++++++++++++++ .../typed_om/math/parsing/expression.rs | 299 ++++++++++++++++++ .../css_runtime/typed_om/math/types.rs | 2 +- .../css_runtime/typed_om/mod.rs | 2 +- .../script_vm/tests/dom_xhr/computed_style.rs | 1 + .../computed_style/css_numeric_parse.js | 78 +++++ .../computed_style/css_numeric_parse.rs | 68 ++++ moli-webapi/src/css_values.rs | 2 +- 10 files changed, 698 insertions(+), 4 deletions(-) create mode 100644 moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing.rs create mode 100644 moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing/expression.rs create mode 100644 moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.js create mode 100644 moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.rs diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/conversion.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/conversion.rs index 92d8e3c5f30..6ae35c2a835 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/conversion.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/conversion.rs @@ -41,7 +41,7 @@ impl Budget { // DOM quantities must stay f64. Stylo's NoCalcNumeric/SumValue use f32 and // currently omit frequency/resolution/flex; only the fixed CSS ratios live // here. Relative units remain independent of layout and of one another. -fn canonical(unit: &str) -> (&str, f64) { +pub(super) fn canonical(unit: &str) -> (&str, f64) { match unit { "in" => ("px", 96.0), "cm" => ("px", 96.0 / 2.54), @@ -56,6 +56,7 @@ fn canonical(unit: &str) -> (&str, f64) { "khz" => ("hz", 1000.0), "dpi" => ("dppx", 1.0 / 96.0), "dpcm" => ("dppx", 2.54 / 96.0), + "x" => ("dppx", 1.0), _ => (unit, 1.0), } } diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/mod.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/mod.rs index 2e73049a26e..f955ec95bdf 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/mod.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/mod.rs @@ -5,6 +5,7 @@ mod array; mod conversion; mod graph; mod operations; +mod parsing; mod serialization; mod types; @@ -196,7 +197,9 @@ pub(super) fn install<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, name: &str, + profile: crate::context_bootstrap::exposed_interfaces::TemplateBuildProfile, ) { + parsing::install(scope, template, name, profile); let prototype = template.prototype_template(scope); match name { "CSSNumericValue" => NumericPrototype::initialize_prototype_template(scope, prototype), diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing.rs new file mode 100644 index 00000000000..fd651b106f5 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing.rs @@ -0,0 +1,244 @@ +use super::graph::Unit; +use super::*; +use crate::context_bootstrap::exposed_interfaces::TemplateBuildProfile; +use cssparser::{ParseError, ParseErrorKind}; + +mod expression; +use expression::Expression; + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::CSSNumericValue, enumerable)] +struct NumericConstructor { + #[webapi(static_method, callback = parse_callback, length = 1)] + parse: (), +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "CSSNumericValue.parse")] +struct ParseArgs { + #[webidl(required, converter = "usv_string")] + css_text: String, +} + +pub(super) fn install<'s>( + scope: &mut v8::PinScope<'s, '_, ()>, + template: v8::Local<'s, v8::FunctionTemplate>, + name: &str, + profile: TemplateBuildProfile, +) { + if name == "CSSNumericValue" && profile == TemplateBuildProfile::Window { + NumericConstructor::initialize_template(scope, template); + } +} + +#[derive(Clone, Copy, Debug)] +enum Error { + Syntax, + TooLarge, +} + +// 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_NODES: usize = 32_768; + +struct Budget(usize); + +impl Budget { + fn spend(&mut self, amount: usize) -> Result<(), Error> { + self.0 = self.0.checked_sub(amount).ok_or(Error::TooLarge)?; + Ok(()) + } +} + +fn parse_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + // This is a static operation: its this value does not participate in + // receiver validation. Convert USVString once before inspecting syntax. + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + let mut input = ParserInput::new(&parsed.css_text); + let mut parser = Parser::new(&mut input); + let mut budget = Budget(MAX_NODES); + match parser.parse_entirely(|p| parse_value(p, &mut budget, 0, false)) { + Ok(expression) => { + if let Some(value) = expression.bind(scope) { + rv.set(value.into()); + } + } + Err(error) => match error.kind { + ParseErrorKind::Custom(Error::TooLarge) => { + crate::util::throw_range_error(scope, "CSS numeric expression is too large") + } + _ => { + webidl::throw_dom_exception(scope, "SyntaxError", "Invalid CSS numeric expression") + } + }, + } +} + +fn parse_value<'i>( + input: &mut Parser<'i, '_>, + budget: &mut Budget, + depth: usize, + in_math: bool, +) -> Result> { + if depth > MAX_DEPTH { + return Err(input.new_custom_error(Error::TooLarge)); + } + budget.spend(1).map_err(|e| input.new_custom_error(e))?; + input.skip_whitespace(); + let start = input.position(); + let token = input.next()?.clone(); + let unit = match &token { + Token::Number { .. } => Some("number".to_owned()), + Token::Percentage { .. } => Some("percent".to_owned()), + 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))?; + Some(unit) + } + _ => None, + }; + if let Some(unit) = unit { + // 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))?; + return Ok(Expression::unit(Unit { value, unit }, in_math)); + } + match token { + Token::ParenthesisBlock if in_math => { + input.parse_nested_block(|p| parse_sum(p, budget, depth + 1)) + } + Token::Ident(name) if in_math => { + let value = match name.to_ascii_lowercase().as_str() { + "e" => std::f64::consts::E, + "pi" => std::f64::consts::PI, + "infinity" => f64::INFINITY, + "-infinity" => f64::NEG_INFINITY, + "nan" => f64::NAN, + _ => return Err(input.new_custom_error(Error::Syntax)), + }; + Ok(Expression::unit( + Unit { + value, + unit: "number".into(), + }, + false, + )) + } + Token::Function(name) => { + let name = name.to_ascii_lowercase(); + let expression = input.parse_nested_block(|p| match name.as_str() { + "calc" => parse_sum(p, budget, depth + 1), + "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)) + } + "clamp" => { + let lower = optional_bound(p, budget, depth + 1)?; + p.expect_comma()?; + let value = parse_sum(p, budget, depth + 1)?; + p.expect_comma()?; + let upper = optional_bound(p, budget, depth + 1)?; + let (kind, children) = match (lower, upper) { + (Some(a), Some(b)) => (Kind::Clamp, vec![a, value, b]), + (Some(a), None) => (Kind::Max, vec![a, value]), + (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)) + } + _ => Err(p.new_custom_error(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)) + } else { + Ok(expression) + } + } + _ => Err(input.new_custom_error(Error::Syntax)), + } +} + +fn optional_bound<'i>( + input: &mut Parser<'i, '_>, + budget: &mut Budget, + depth: usize, +) -> Result, ParseError<'i, Error>> { + if input.try_parse(|p| p.expect_ident_matching("none")).is_ok() { + Ok(None) + } else { + parse_sum(input, budget, depth).map(Some) + } +} + +fn parse_sum<'i>( + input: &mut Parser<'i, '_>, + budget: &mut Budget, + depth: usize, +) -> Result> { + let mut children = vec![parse_product(input, budget, depth)?]; + loop { + let start = input.state(); + // Comments alone are not whitespace around a binary + or -. + if !matches!(input.next_including_whitespace(), Ok(Token::WhiteSpace(_))) { + input.reset(&start); + break; + } + let subtract = match input.next() { + Ok(Token::Delim('+')) => false, + Ok(Token::Delim('-')) => true, + _ => { + input.reset(&start); + break; + } + }; + if !matches!(input.next_including_whitespace(), Ok(Token::WhiteSpace(_))) { + return Err(input.new_custom_error(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))?; + } + children.push(child); + } + Expression::operation(Kind::Sum, children, budget).map_err(|e| input.new_custom_error(e)) +} + +fn parse_product<'i>( + input: &mut Parser<'i, '_>, + budget: &mut Budget, + depth: usize, +) -> Result> { + let mut children = vec![parse_value(input, budget, depth, true)?]; + loop { + let start = input.state(); + let divide = match input.next() { + Ok(Token::Delim('*')) => false, + Ok(Token::Delim('/')) => true, + _ => { + input.reset(&start); + break; + } + }; + 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))?; + } + children.push(child); + } + Expression::operation(Kind::Product, children, budget).map_err(|e| input.new_custom_error(e)) +} diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing/expression.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing/expression.rs new file mode 100644 index 00000000000..83265851eb4 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/parsing/expression.rs @@ -0,0 +1,299 @@ +use super::*; +use std::collections::BTreeMap; + +enum Node { + Unit(Unit), + Math(Kind, Vec), +} + +pub(super) struct Expression { + node: Node, + numeric_type: NumericType, +} + +impl Expression { + pub fn unit(mut unit: Unit, canonicalize: bool) -> Self { + if canonicalize { + let (name, ratio) = conversion::canonical(&unit.unit); + unit.value *= ratio; + unit.unit = name.to_owned(); + } + Self { + numeric_type: NumericType::from_unit(&unit.unit).expect("validated CSS numeric unit"), + node: Node::Unit(unit), + } + } + + pub fn is_unit(&self) -> bool { + matches!(self.node, Node::Unit(_)) + } + + pub fn unsimplified(kind: Kind, children: Vec) -> Result { + let mut numeric_type = children.first().ok_or(Error::Syntax)?.numeric_type; + if kind == Kind::Invert { + numeric_type = numeric_type.invert().ok_or(Error::Syntax)?; + } else { + for child in &children[1..] { + numeric_type = if kind == Kind::Product { + numeric_type.multiply(child.numeric_type) + } else { + numeric_type.add(child.numeric_type) + } + .ok_or(Error::Syntax)?; + } + } + Ok(Self { + node: Node::Math(kind, children), + numeric_type, + }) + } + + // CSS Values calculation-tree simplification is distinct from the public + // Typed OM arithmetic methods: it canonicalizes and combines like units, + // flattens nested operators, and distributes scalar multiplication. + pub fn operation(kind: Kind, children: Vec, budget: &mut Budget) -> Result { + budget.spend(1 + children.len())?; + // Check the complete expression before simplification can erase a + // zero-valued term or an incompatible branch of a comparison. + let expression = Self::unsimplified(kind, children)?; + let Node::Math(_, mut children) = expression.node else { + unreachable!() + }; + match kind { + Kind::Negate | Kind::Invert => { + let child = children.pop().unwrap(); + match child.node { + Node::Unit(mut unit) if kind == Kind::Negate || unit.unit == "number" => { + unit.value = if kind == Kind::Negate { + -unit.value + } else { + 1.0 / unit.value + }; + Ok(Self::unit(unit, false)) + } + Node::Math(child_kind, mut values) if child_kind == kind => { + Ok(values.pop().unwrap()) + } + Node::Math(Kind::Sum, values) if kind == Kind::Negate => { + let values = values + .into_iter() + .map(|value| Self::operation(Kind::Negate, vec![value], budget)) + .collect::>()?; + Self::operation(Kind::Sum, values, budget) + } + _ => Self::unsimplified(kind, vec![child]), + } + } + Kind::Sum | Kind::Product => { + let mut flat = Vec::new(); + for child in children { + match child.node { + Node::Math(child_kind, values) if child_kind == kind => flat.extend(values), + _ => flat.push(child), + } + } + budget.spend(flat.len())?; + if kind == Kind::Sum { + Self::sum(flat) + } else { + Self::product(flat, budget) + } + } + Kind::Min | Kind::Max => Self::comparison(kind, children), + Kind::Clamp => { + if let [a, b, c] = children.as_slice() + && let (Node::Unit(a), Node::Unit(b), Node::Unit(c)) = + (&a.node, &b.node, &c.node) + && comparable(a) + && a.unit == b.unit + && a.unit == c.unit + { + return Ok(Self::unit( + Unit { + value: operations::maximum( + a.value, + operations::minimum(b.value, c.value), + ), + unit: a.unit.clone(), + }, + false, + )); + } + Self::unsimplified(kind, children) + } + } + } + + fn sum(children: Vec) -> Result { + let mut result: Vec = Vec::new(); + let mut positions: BTreeMap = BTreeMap::new(); + for child in children { + if let Node::Unit(unit) = &child.node { + if let Some(&index) = positions.get(&unit.unit) { + let Node::Unit(previous) = &mut result[index].node else { + unreachable!() + }; + previous.value += unit.value; + continue; + } + positions.insert(unit.unit.clone(), result.len()); + } + result.push(child); + } + Self::collapse(Kind::Sum, result) + } + + fn product(children: Vec, budget: &mut Budget) -> Result { + let mut number: Option = None; + let mut combined: Vec = Vec::with_capacity(children.len()); + for child in children { + if let Node::Unit(unit) = &child.node + && unit.unit == "number" + { + if let Some(previous) = number { + let Node::Unit(target) = &mut combined[previous].node else { + unreachable!() + }; + target.value *= unit.value; + continue; + } + number = Some(combined.len()); + } + combined.push(child); + } + let mut children = combined; + if children.len() == 2 + && let Some(number) = number + { + let other = 1 - number; + if let Node::Math(Kind::Sum, terms) = &children[other].node + && terms.iter().all(Self::is_unit) + { + let Node::Unit(scalar) = &children[number].node else { + unreachable!() + }; + let value = scalar.value; + let Node::Math(_, terms) = children.remove(other).node else { + unreachable!() + }; + budget.spend(terms.len())?; + let terms = terms + .into_iter() + .map(|term| { + let Node::Unit(mut unit) = term.node else { + unreachable!() + }; + unit.value *= value; + Self::unit(unit, false) + }) + .collect(); + return Self::collapse(Kind::Sum, terms); + } + } + // Cancel units only when their conversion is independent of layout. + // px/em remains an expression even though its dimensional type is a + // number. Matching relative units can cancel one another. + let mut units: BTreeMap<&str, i32> = BTreeMap::new(); + let mut value = 1.0; + let mut all_numeric = true; + for child in &children { + let (unit, power) = match &child.node { + Node::Unit(unit) => (unit, 1), + Node::Math(Kind::Invert, values) => match &values[0].node { + Node::Unit(unit) => (unit, -1), + _ => { + all_numeric = false; + break; + } + }, + _ => { + all_numeric = false; + break; + } + }; + value *= if power == 1 { + unit.value + } else { + 1.0 / unit.value + }; + if unit.unit != "number" { + *units.entry(&unit.unit).or_default() += power; + } + } + units.retain(|_, power| *power != 0); + if all_numeric + && (units.is_empty() || (units.len() == 1 && units.values().next() == Some(&1))) + { + let unit = units.keys().next().copied().unwrap_or("number").to_owned(); + return Ok(Self::unit(Unit { value, unit }, false)); + } + Self::collapse(Kind::Product, children) + } + + fn comparison(kind: Kind, children: Vec) -> Result { + let mut result: Vec = Vec::new(); + let mut positions: BTreeMap = BTreeMap::new(); + for child in children { + if let Node::Unit(unit) = &child.node + && comparable(unit) + { + if let Some(&index) = positions.get(&unit.unit) { + let Node::Unit(previous) = &mut result[index].node else { + unreachable!() + }; + previous.value = if kind == Kind::Min { + operations::minimum(previous.value, unit.value) + } else { + operations::maximum(previous.value, unit.value) + }; + continue; + } + positions.insert(unit.unit.clone(), result.len()); + } + result.push(child); + } + Self::collapse(kind, result) + } + + fn collapse(kind: Kind, mut children: Vec) -> Result { + if children.len() == 1 { + Ok(children.pop().unwrap()) + } else { + Self::unsimplified(kind, children) + } + } + + pub fn bind<'s>(self, scope: &mut v8::PinScope<'s, '_>) -> Option> { + let realm = scope.get_current_context(); + match self.node { + Node::Unit(unit) => Some(unit.bind(scope, realm)), + Node::Math(kind, children) => { + let mut values = Vec::with_capacity(children.len()); + for (index, mut child) in children.into_iter().enumerate() { + // Reify subtraction in a sum as a native negate operand. + let negative = kind == Kind::Sum + && index != 0 + && matches!(&child.node, Node::Unit(unit) if unit.value < 0.0); + if negative && let Node::Unit(unit) = &mut child.node { + unit.value = -unit.value; + } + let mut value = child.bind(scope)?; + if negative { + value = math_value(scope, Kind::Negate, &[value], realm)?; + } + values.push(value); + } + math_value(scope, kind, &values, realm) + } + } + } +} + +fn comparable(unit: &Unit) -> bool { + // Percentages can have a negative basis; relative lengths still require + // contextual information. Neither can be compared at parse time. + matches!( + unit.unit.as_str(), + "number" | "px" | "deg" | "s" | "hz" | "dppx" + ) +} diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/types.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/types.rs index 1a13cc0e4ce..80e25de7951 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/types.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/types.rs @@ -29,7 +29,7 @@ impl NumericType { "deg" | "grad" | "rad" | "turn" => 1, "s" | "ms" => 2, "hz" | "khz" => 3, - "dpi" | "dpcm" | "dppx" => 4, + "dpi" | "dpcm" | "dppx" | "x" => 4, "fr" => 5, _ if LengthUnit::from_str(unit).is_ok() => 0, _ => return None, diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/mod.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/mod.rs index 798dcac00a5..bcc4d0c4b73 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/mod.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/mod.rs @@ -41,5 +41,5 @@ pub(in crate::context_bootstrap) fn install_css_typed_om_template_bindings<'s>( unparsed::install_template_bindings(scope, template, interface_name); map::install_computed_style_map_template_bindings(scope, template, interface_name); values::install_typed_value_template_bindings(scope, template, interface_name); - math::install(scope, template, interface_name); + math::install(scope, template, interface_name, profile); } diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs index ef7872bea13..0f82869176b 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs @@ -65,6 +65,7 @@ mod css_computed_map_enumeration; mod css_math; mod css_numeric_factories; mod css_numeric_operations; +mod css_numeric_parse; mod css_numeric_serialization; mod css_style_property_map; mod css_style_value_parse; diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.js new file mode 100644 index 00000000000..35a8cd7f7bb --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.js @@ -0,0 +1,78 @@ +(() => { + 'use strict'; + const check = (ok, message) => {if (!ok) throw new Error(message);}; + const eq = (a,b,message) => check(Object.is(a,b),message); + const throws = (fn,C) => {let caught;try{fn();}catch(e){caught=e;}check(caught instanceof C,`expected ${C.name}`);return caught;}; + const parse = CSSNumericValue.parse; + const desc = Object.getOwnPropertyDescriptor(CSSNumericValue,'parse'); + check(desc.enumerable && desc.configurable && desc.writable,'descriptor'); + eq(parse.length,1,'arity'); + eq(parse.name,'parse','name'); + throws(()=>parse(),TypeError); + throws(()=>parse(Symbol()),TypeError); + throws(()=>new parse('1px'),TypeError); + for (const invalid of [ + '', ' ', 'auto', '1 2', '1px;', '1px !important', '1xyz', '1number', '1percent', + '(1px)', 'var(--x)', 'env(foo)', 'url(1px)', 'calc(var(--x))', + 'calc()', 'min()', 'min(1px,)', 'max(,1px)', 'clamp(1px,2px)', 'clamp(1px,2px,3px,4px)', + 'calc(1px + 2s)', 'min(1px,0s)', 'calc(calc(1px * 2s) + 3%)', + 'calc(1px+ 2px)', 'calc(1px +2px)', 'calc(1px/**/+ 2px)', 'calc(1px +/**/2px)', + 'calc(1px))', 'calc(-(1px))', 'calc(1px, 2px)', 'calc([1px])', + ]) eq(throws(()=>parse(invalid),DOMException).name,'SyntaxError',invalid); + for (const source of [' 1px ', '1PX', '1\\70 x', '1px/**/']) { + const v=parse(source);check(v instanceof CSSUnitValue && v.value===1 && v.unit==='px',source); + } + for (const source of ['calc(1px + 2px)', 'calc(1px /**/+ 2px)', 'calc(1px + /**/ 2px)', 'calc(1px/**/ + 2px)', 'calc(1px\n+\t2px)']) { + check(parse(source).equals(new CSSMathSum(CSS.px(3))),source); + } + check(parse('calc(10px)').equals(new CSSMathSum(CSS.px(10))),'calc wrapper'); + check(parse('calc(1px + 1in)').equals(new CSSMathSum(CSS.px(97))),'canonicalize lengths'); + check(parse('calc(calc(1px + 2em) + 3rem)').equals(new CSSMathSum(CSS.px(1),CSS.em(2),CSS.rem(3))),'flatten nested sums'); + check(parse('calc(1em + 2px + 3em)').equals(new CSSMathSum(CSS.em(4),CSS.px(2))),'combine same units'); + check(parse('calc(1px - 2 * 3em)').equals(new CSSMathSum(CSS.px(1),new CSSMathNegate(CSS.em(6)))),'precedence and subtraction'); + check(parse('calc((1px + 2em) * 3)').equals(new CSSMathSum(CSS.px(3),CSS.em(6))),'distribute multiplication'); + check(parse('calc((1px + 2em) / 2)').equals(new CSSMathSum(CSS.px(.5),CSS.em(1))),'distribute division'); + check(parse('min(1px,2em)').equals(new CSSMathMin(CSS.px(1),CSS.em(2))),'unresolved minimum'); + check(parse('max(1px,2em)').equals(new CSSMathMax(CSS.px(1),CSS.em(2))),'unresolved maximum'); + check(parse('clamp(1px,2%,3px)').equals(new CSSMathClamp(CSS.px(1),CSS.percent(2),CSS.px(3))),'unresolved clamp'); + eq(parse('min(1in,2px)').value,2,'resolved minimum'); + eq(parse('clamp(20px,0px,10px)').value,20,'lower clamp wins'); + check(parse('calc(min(1px,2em))') instanceof CSSMathMin,'no redundant nested wrapper'); + eq(parse('16777217px').value,16777217,'literal f64'); + eq(parse('calc(16777217px + 2px)').to('px').value,16777219,'expression f64'); + eq(parse('0.12345678901234567%').value,0.12345678901234567,'percentage f64'); + eq(parse('-0').value,-0,'literal negative zero'); + eq(parse('calc(-0)').values[0].value,-0,'math negative zero'); + eq(parse('1e999px').value,3.4028234663852886e38,'CSS token numeric range'); + eq(parse('calc(1px / 0)').values[0].value,Infinity,'CSS division by zero'); + check(Number.isNaN(parse('calc(0 / 0)').values[0].value),'CSS zero over zero'); + eq(parse('calc(pi)').values[0].value,Math.PI,'pi'); + eq(parse('calc(e)').values[0].value,Math.E,'e'); + eq(parse('calc(-infinity)').values[0].value,-Infinity,'negative infinity'); + check(parse('calc(1px').equals(new CSSMathSum(CSS.px(1))),'CSS EOF closes function'); + eq(parse('1x').unit,'x','resolution alias token'); + eq(parse('1x').to('dppx').value,1,'resolution alias conversion'); + eq(new CSSUnitValue(2,'x').type().resolution,1,'resolution alias type'); + eq(new CSSUnitValue(2,'x').to('dpi').value,192,'resolution alias constructor'); + const realms=[globalThis,document.querySelector('iframe').contentWindow]; + for(const realm of realms) { + const method=realm.CSSNumericValue.parse; + const U=realm.CSSUnitValue,S=realm.CSSMathSum; + const sentinel={};let calls=0; + let caught;try{method({toString(){calls++;throw sentinel;}});}catch(e){caught=e;} + eq(caught,sentinel,'conversion exception identity');eq(calls,1,'one USVString conversion'); + eq(throws(()=>method('invalid'),realm.DOMException).name,'SyntaxError','exception realm'); + throws(()=>method(),realm.TypeError); + const revoked=Proxy.revocable({},{});revoked.revoke(); + for(const receiver of [null,{},revoked.proxy]) check(method.call(receiver,'1px') instanceof U,'static method accepts arbitrary this'); + const result=method('calc(1px + 2em)'); + check(result instanceof S && result.values[0] instanceof U && result.values[1] instanceof U,'callee realm for entire graph'); + realm.CSSUnitValue=realm.CSSMathSum=function(){throw sentinel;}; + try {check(method('calc(1px)') instanceof S && method('1px') instanceof U,'intrinsic allocation');} + finally {realm.CSSUnitValue=U;realm.CSSMathSum=S;} + let ignored=0;check(method('1px',{toString(){ignored++;throw sentinel;}}) instanceof U,'ignore surplus arguments');eq(ignored,0,'no surplus conversion'); + const value=method({toString(){calls++;return 'calc(2px + 3px)';}}); + eq(calls,2,'single successful conversion');eq(value.to('px').value,5,'converted source'); + } + return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.rs new file mode 100644 index 00000000000..d8040a081ff --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_parse.rs @@ -0,0 +1,68 @@ +use super::*; + +#[test] +fn css_numeric_parse_preserves_syntax_types_precision_and_realms() { + let mut vm = new_parsed_test_vm( + "https://css-numeric-parse.test/", + "", + ); + assert_eq!( + vm.eval(include_str!("css_numeric_parse.js")).unwrap(), + "true" + ); +} + +#[test] +fn css_numeric_parse_handles_dimensional_algebra_and_unresolved_percentages() { + let mut vm = new_storage_test_vm("https://css-numeric-parse-algebra.test/"); + assert_eq!(vm.eval(r#"(() => { + const check = (ok, message) => {if (!ok) throw new Error(message);}; + const parse = CSSNumericValue.parse; + const ratio = parse('calc(6px / 2s)'); + check(ratio instanceof CSSMathProduct && ratio.values[1] instanceof CSSMathInvert, 'dimension inverse'); + check(ratio.type().length === 1 && ratio.type().time === -1, 'inverse type'); + check(parse('calc(6px / 2px)').to('number').value === 3, 'unit cancellation'); + const relative = parse('calc(6px / 2em)'); + check(relative instanceof CSSMathProduct && Object.keys(relative.type()).length === 0, 'relative ratio remains unresolved'); + try {relative.to('number'); return false;} catch(e) {if (!(e instanceof TypeError)) throw e;} + check(parse('calc(6em / 2em)').to('number').value === 3, 'matching relative units cancel'); + const min = parse('min(3px, 2%, 1px)'); + check(min.values.length === 2 && min.values[0].value === 1 && min.values[1].unit === 'percent', 'partial comparison simplification'); + check(parse('min(2%,1%)') instanceof CSSMathMin, 'percentages may have a negative basis'); + check(parse('calc(0px + 0%)').values.length === 2, 'zero terms preserve units'); + check(parse('clamp(none, 2%, 10px)') instanceof CSSMathMin, 'unbounded lower clamp'); + check(parse('clamp(10px, 2%, none)') instanceof CSSMathMax, 'unbounded upper clamp'); + check(parse('clamp(none, 2px, none)').value === 2, 'unbounded clamp'); + check(parse('calc(1khz + 1hz)').to('hz').value === 1001, 'frequency'); + check(parse('calc(1fr * 2)').to('fr').value === 2, 'flex type'); + check(parse('calc(1s + 2%)').type().percentHint === 'time', 'property-independent percent hint'); + check(Object.is(parse('max(-0,0)').value,0), 'max signed zero'); + check(Object.is(parse('min(0,-0)').value,-0), 'min signed zero'); + check(Number.isNaN(parse('max(1,NaN)').value), 'NaN propagation'); + return true; + })()"#).unwrap(), "true"); +} + +#[test] +fn css_numeric_parse_bounds_input_work_and_recovers_after_errors() { + let mut vm = new_storage_test_vm("https://css-numeric-parse-limits.test/"); + assert_eq!( + 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 input of [ + 'calc('.repeat(2000) + '1px' + ')'.repeat(2000), + 'calc(' + Array(40000).fill('1px').join(' + ') + ')', + 'min(' + Array(40000).fill('1px').join(',') + ')', + ]) { + try {parse(input); return false;} catch(e) {if (!(e instanceof RangeError)) throw e;} + } + return parse('calc(1px + 2px)').to('px').value === 3; + })()"# + ) + .unwrap(), + "true" + ); +} diff --git a/moli-webapi/src/css_values.rs b/moli-webapi/src/css_values.rs index 1ef886d080b..421b6e1eb7c 100644 --- a/moli-webapi/src/css_values.rs +++ b/moli-webapi/src/css_values.rs @@ -281,7 +281,7 @@ fn parse_single_unit_value(text: &str) -> Option<(f64, String)> { pub fn normalize_unit_name(unit: &str) -> Option { let unit = unit.to_ascii_lowercase(); - VALID_UNIT_NAMES.contains(&unit.as_str()).then_some(unit) + (VALID_UNIT_NAMES.contains(&unit.as_str()) || unit == "x").then_some(unit) } pub fn css_style_value_to_string_callback<'s>(