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 new file mode 100644 index 00000000000..92d8e3c5f30 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/conversion.rs @@ -0,0 +1,364 @@ +use super::graph::{Graph, MAX_WORK, Node, Unit}; +use super::operations::{maximum, minimum}; +use super::*; +use std::collections::BTreeMap; + +type UnitMap = BTreeMap; + +#[derive(Clone)] +struct Term { + value: f64, + units: UnitMap, +} + +#[derive(Clone, Copy)] +enum Error { + Incompatible, + TooLarge, +} + +fn throw(scope: &mut v8::PinScope<'_, '_>, error: Error) { + match error { + Error::Incompatible => throw_type_error( + scope, + "CSS numeric value cannot be converted to these units", + ), + Error::TooLarge => { + crate::util::throw_range_error(scope, "CSS numeric conversion is too large") + } + } +} + +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(()) + } +} + +// 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) { + match unit { + "in" => ("px", 96.0), + "cm" => ("px", 96.0 / 2.54), + "mm" => ("px", 96.0 / 25.4), + "q" => ("px", 96.0 / 101.6), + "pt" => ("px", 96.0 / 72.0), + "pc" => ("px", 16.0), + "rad" => ("deg", 180.0 / std::f64::consts::PI), + "grad" => ("deg", 0.9), + "turn" => ("deg", 360.0), + "ms" => ("s", 0.001), + "khz" => ("hz", 1000.0), + "dpi" => ("dppx", 1.0 / 96.0), + "dpcm" => ("dppx", 2.54 / 96.0), + _ => (unit, 1.0), + } +} + +impl Unit { + fn convert(&self, unit: &str) -> Option { + if self.unit == unit { + return Some(self.value); + } + let (from, from_ratio) = canonical(&self.unit); + let (to, to_ratio) = canonical(unit); + (from == to).then(|| self.value * (from_ratio / to_ratio)) + } +} + +impl Term { + fn from_unit(unit: &Unit) -> Self { + let (name, ratio) = canonical(&unit.unit); + Self { + value: unit.value * ratio, + units: if name == "number" { + BTreeMap::new() + } else { + [(name.to_owned(), 1)].into() + }, + } + } + + fn into_unit(self) -> Result { + let unit = match self.units.len() { + 0 => "number".to_owned(), + 1 => { + let (unit, power) = self.units.into_iter().next().unwrap(); + if power != 1 { + return Err(Error::Incompatible); + } + unit + } + _ => return Err(Error::Incompatible), + }; + Ok(Unit { + value: self.value, + unit, + }) + } + + fn numeric_type(&self) -> Result { + let mut result = NumericType::default(); + for (unit, &power) in &self.units { + let mut next = NumericType::from_unit(unit).ok_or(Error::Incompatible)?; + for exponent in &mut next.powers { + *exponent *= power; + } + result = result.multiply(next).ok_or(Error::TooLarge)?; + } + Ok(result) + } + + fn cost(&self) -> usize { + 1 + self.units.len() + } +} + +fn combine(kind: Kind, args: &[&[Term]], budget: &mut Budget) -> Result, Error> { + match kind { + Kind::Sum => { + let mut values: Vec = Vec::new(); + let mut indices: BTreeMap = BTreeMap::new(); + for term in args.iter().flat_map(|arg| arg.iter()) { + budget.spend(term.cost())?; + if let Some(&index) = indices.get(&term.units) { + values[index].value += term.value; + } else { + indices.insert(term.units.clone(), values.len()); + values.push(term.clone()); + } + } + let mut numeric_type = values[0].numeric_type()?; + for term in &values[1..] { + numeric_type = numeric_type + .add(term.numeric_type()?) + .ok_or(Error::Incompatible)?; + } + Ok(values) + } + Kind::Product => { + let mut values = vec![Term { + value: 1.0, + units: BTreeMap::new(), + }]; + for arg in args { + let count = values.len().checked_mul(arg.len()).ok_or(Error::TooLarge)?; + budget.spend(count)?; + let mut next = Vec::with_capacity(count); + for a in &values { + for b in *arg { + budget.spend(a.units.len() + b.units.len())?; + let mut units = a.units.clone(); + for (unit, power) in &b.units { + let result = units.entry(unit.clone()).or_insert(0); + *result = result.checked_add(*power).ok_or(Error::TooLarge)?; + } + units.retain(|_, power| *power != 0); + next.push(Term { + value: a.value * b.value, + units, + }); + } + } + values = next; + } + Ok(values) + } + Kind::Negate | Kind::Invert => { + if kind == Kind::Invert && args[0].len() != 1 { + return Err(Error::Incompatible); + } + for term in args[0] { + budget.spend(term.cost())?; + } + let mut values = args[0].to_vec(); + for term in &mut values { + if kind == Kind::Negate { + term.value = -term.value; + } else { + term.value = 1.0 / term.value; + for power in term.units.values_mut() { + *power = power.checked_neg().ok_or(Error::TooLarge)?; + } + } + } + Ok(values) + } + Kind::Min | Kind::Max | Kind::Clamp => { + let first = &args[0][0]; + if args + .iter() + .any(|arg| arg.len() != 1 || arg[0].units != first.units) + { + return Err(Error::Incompatible); + } + budget.spend(first.cost() + args.len())?; + let mut result = first.clone(); + result.value = if kind == Kind::Clamp { + // CSS clamp gives the lower bound priority when lower > upper. + maximum( + args[0][0].value, + minimum(args[1][0].value, args[2][0].value), + ) + } else { + args[1..].iter().fold(first.value, |value, next| { + if kind == Kind::Min { + minimum(value, next[0].value) + } else { + maximum(value, next[0].value) + } + }) + }; + Ok(vec![result]) + } + } +} + +fn sum_value(graph: &Graph) -> Result, Error> { + let mut budget = Budget(MAX_WORK); + let mut results: Vec>> = vec![None; graph.nodes.len()]; + let root = graph.roots[0]; + let mut pending = vec![(root, false)]; + while let Some((index, ready)) = pending.pop() { + if results[index].is_some() { + continue; + } + budget.spend(1)?; + match &graph.nodes[index] { + Node::Unit(unit) => results[index] = Some(vec![Term::from_unit(unit)]), + Node::Math(kind, children) => { + if !ready { + pending.push((index, true)); + pending.extend(children.iter().rev().map(|&child| (child, false))); + } else { + let args = children + .iter() + .map(|&child| results[child].as_deref().unwrap()) + .collect::>(); + results[index] = Some(combine(*kind, &args, &mut budget)?); + } + } + } + } + Ok(results[root].take().unwrap()) +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "CSSNumericValue.to")] +struct ToArgs { + #[webidl(required, converter = "usv_string")] + unit: String, +} + +fn convert<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + names: Vec, + single: bool, +) -> Option> { + let Some(names) = names + .iter() + .map(|name| values::normalize_unit_name(name)) + .collect::>>() + else { + webidl::throw_dom_exception(scope, "SyntaxError", "Invalid CSS numeric unit"); + return None; + }; + let realm = object.get_creation_context(scope)?; + let graph = Graph::read(scope, &[object])?; + let values = sum_value(&graph).and_then(|terms| { + terms + .into_iter() + .map(Term::into_unit) + .collect::, _>>() + }); + let mut values = match values { + Ok(values) => values, + Err(error) => { + throw(scope, error); + return None; + } + }; + if single { + if values.len() == 1 + && let Some(value) = values[0].convert(&names[0]) + { + return Some( + Unit { + value, + unit: names[0].clone(), + } + .bind(scope, realm), + ); + } + throw(scope, Error::Incompatible); + return None; + } + let mut result = Vec::new(); + if names.is_empty() { + values.sort_by(|a, b| a.unit.cmp(&b.unit)); + result.extend(values.into_iter().map(|value| value.bind(scope, realm))); + } else { + // Greedily consume compatible terms in the requested order; retain + // explicit zero-valued entries, including repeated requested units. + for name in names { + let mut value = 0.0; + values.retain(|unit| { + if let Some(converted) = unit.convert(&name) { + value += converted; + false + } else { + true + } + }); + result.push(Unit { value, unit: name }.bind(scope, realm)); + } + if !values.is_empty() { + throw(scope, Error::Incompatible); + return None; + } + } + math_value(scope, Kind::Sum, &result, realm) +} + +pub(super) fn to_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + if let Some(value) = convert(scope, args.this(), vec![parsed.unit], true) { + rv.set(value.into()); + } +} + +pub(super) fn to_sum_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let mut names = Vec::new(); + for index in 0..args.length() { + match webidl::convert::( + scope, + args.get(index), + webidl::Context::argument("CSSNumericValue.toSum", index as usize + 1), + ) { + Ok(unit) => names.push(unit.0), + Err(error) => { + webidl::throw_error(scope, &error); + return; + } + } + } + if let Some(value) = convert(scope, args.this(), names, false) { + rv.set(value.into()); + } +} diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/graph.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/graph.rs new file mode 100644 index 00000000000..8f266addee1 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/graph.rs @@ -0,0 +1,160 @@ +use super::*; +use std::collections::HashSet; + +pub(super) const MAX_WORK: usize = 1_000_000; + +#[derive(Clone)] +pub(super) struct Unit { + pub value: f64, + pub unit: String, +} + +impl Unit { + pub fn read<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + ) -> Option { + Some(Self { + unit: values::css_unit_value_unit(scope, object)?, + value: values::css_unit_value_number(scope, object)?, + }) + } + + pub fn bind<'s>( + self, + scope: &mut v8::PinScope<'s, '_>, + realm: v8::Local<'s, v8::Context>, + ) -> v8::Local<'s, v8::Object> { + let scope = &mut v8::ContextScope::new(scope, realm); + values::unit_value(scope, self.value, self.unit) + } +} + +pub(super) enum Node { + Unit(Unit), + Math(Kind, Vec), +} + +pub(super) struct Graph { + pub nodes: Vec, + pub roots: Vec, +} + +fn intern<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + identities: v8::Local<'s, v8::Map>, + objects: &mut Vec>, +) -> Option { + let known = identities.get(scope, object.into())?; + if !known.is_undefined() { + return Some(known.uint32_value(scope)? as usize); + } + if objects.len() >= MAX_WORK { + crate::util::throw_range_error(scope, "CSS numeric graph is too large"); + return None; + } + let index = objects.len(); + let value = v8::Integer::new_from_unsigned(scope, index as u32); + identities.set(scope, object.into(), value.into())?; + objects.push(object); + Some(index) +} + +impl Graph { + /// Snapshot after all argument conversions. Values are mutable, but child + /// identities are not. A flat graph avoids native recursion (including Drop) + /// and visits a shared operand only once, without invoking author getters. + pub fn read<'s>( + scope: &mut v8::PinScope<'s, '_>, + roots: &[v8::Local<'s, v8::Object>], + ) -> Option { + let identities = v8::Map::new(scope); + let mut objects = Vec::new(); + let roots = roots + .iter() + .map(|&object| intern(scope, object, identities, &mut objects)) + .collect::>>()?; + let mut nodes = Vec::new(); + let mut edges = 0usize; + while nodes.len() < objects.len() { + let object = objects[nodes.len()]; + if let Some(unit) = Unit::read(scope, object) { + nodes.push(Node::Unit(unit)); + continue; + } + let kind = kind(scope, object)?; + let children = operands(scope, object)?; + edges += children.len(); + if edges > MAX_WORK { + crate::util::throw_range_error(scope, "CSS numeric graph is too large"); + return None; + } + let children = children + .into_iter() + .map(|child| intern(scope, child, identities, &mut objects)) + .collect::>>()?; + nodes.push(Node::Math(kind, children)); + } + Some(Self { nodes, roots }) + } +} + +/// Compare lazily so an early mismatch does not traverse unrelated subgraphs. +/// Argument conversion has already finished; only private native slots are read. +pub(super) fn equals<'s>( + scope: &mut v8::PinScope<'s, '_>, + receiver: v8::Local<'s, v8::Object>, + items: &[v8::Local<'s, v8::Object>], +) -> Option { + let identities = v8::Map::new(scope); + let mut objects = Vec::new(); + let left = intern(scope, receiver, identities, &mut objects)?; + let mut visited = HashSet::new(); + for &item in items { + let right = intern(scope, item, identities, &mut objects)?; + let mut pending = vec![(left, right)]; + while let Some((a, b)) = pending.pop() { + if !visited.insert((a, b)) { + continue; + } + if visited.len() > MAX_WORK { + crate::util::throw_range_error(scope, "CSS numeric comparison is too large"); + return None; + } + let (a, b) = (objects[a], objects[b]); + match (Unit::read(scope, a), Unit::read(scope, b)) { + (Some(a), Some(b)) => { + // Even identical objects can hold NaN after arithmetic. + if a.unit != b.unit || a.value != b.value { + return Some(false); + } + } + (None, None) => { + if kind(scope, a)? != kind(scope, b)? { + return Some(false); + } + let (a, b) = (operands(scope, a)?, operands(scope, b)?); + if a.len() != b.len() { + return Some(false); + } + if pending.len() + a.len() > MAX_WORK { + crate::util::throw_range_error( + scope, + "CSS numeric comparison is too large", + ); + return None; + } + for (a, b) in a.into_iter().zip(b).rev() { + pending.push(( + intern(scope, a, identities, &mut objects)?, + intern(scope, b, identities, &mut objects)?, + )); + } + } + _ => return Some(false), + } + } + } + Some(true) +} 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 bbd95949191..2e73049a26e 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 @@ -2,6 +2,9 @@ use super::*; use crate::web_api_interfaces; mod array; +mod conversion; +mod graph; +mod operations; mod serialization; mod types; @@ -121,6 +124,24 @@ math_class!( #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::CSSNumericValue, enumerable)] struct NumericPrototype { + #[webapi(method, callback = operations::add_callback, length = 0)] + add: (), + #[webapi(method, callback = operations::sub_callback, length = 0)] + sub: (), + #[webapi(method, callback = operations::mul_callback, length = 0)] + mul: (), + #[webapi(method, callback = operations::div_callback, length = 0)] + div: (), + #[webapi(method, callback = operations::min_callback, length = 0)] + min: (), + #[webapi(method, callback = operations::max_callback, length = 0)] + max: (), + #[webapi(method, callback = operations::equals_callback, length = 0)] + equals: (), + #[webapi(method, callback = conversion::to_callback, length = 1)] + to: (), + #[webapi(method = "toSum", callback = conversion::to_sum_callback, length = 0)] + to_sum: (), #[webapi(method = "type", callback = type_callback, length = 0)] numeric_type: (), } @@ -196,6 +217,16 @@ fn numberish<'s>( scope: &mut v8::PinScope<'s, '_>, value: v8::Local<'s, v8::Value>, context: webidl::Context, +) -> Result, webidl::WebIdlError> { + let realm = scope.get_current_context(); + numberish_in_realm(scope, value, context, realm) +} + +fn numberish_in_realm<'s>( + scope: &mut v8::PinScope<'s, '_>, + value: v8::Local<'s, v8::Value>, + context: webidl::Context, + realm: v8::Local<'s, v8::Context>, ) -> Result, webidl::WebIdlError> { if let Ok(object) = v8::Local::::try_from(value) && web_api_interfaces::CSSNumericValue::is_instance(scope, object) @@ -205,6 +236,7 @@ fn numberish<'s>( // The union's numeric branch performs ToNumber, including user conversion // and its exceptions; an author Proxy does not inherit the target's brand. let number = f64::from(webidl::convert::(scope, value, context)?); + let scope = &mut v8::ContextScope::new(scope, realm); Ok(values::unit_value(scope, number, "number".into())) } @@ -273,6 +305,45 @@ fn combined_type<'s>( Some(result) } +fn math_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + kind: Kind, + items: &[v8::Local<'s, v8::Object>], + realm: v8::Local<'s, v8::Context>, +) -> Option> { + let Some(numeric_type) = combined_type(scope, kind, items) else { + throw_type_error(scope, "Incompatible CSS numeric types"); + return None; + }; + // Validate in the callee realm, then allocate in the receiver realm. + let scope = &mut v8::ContextScope::new(scope, realm); + let numeric_type = type_array(scope, numeric_type); + let elements = items.iter().copied().map(Into::into).collect::>(); + let values = v8::Array::new_with_elements(scope, &elements); + // Bind intrinsic objects in the receiver's realm without calling an + // author-replaceable constructor or reparsing the public serialization. + let result = match kind { + Kind::Sum => SumDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Product => ProductDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Negate => NegateDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Invert => InvertDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Min => MinDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Max => MaxDeclaration::new(values, kind as u32, numeric_type).bind(scope), + Kind::Clamp => ClampDeclaration::new(values, kind as u32, numeric_type).bind(scope), + }; + Some(result.expect("CSS math object should bind")) +} + +fn operands<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> Option>> { + let children = children(scope, object)?; + (0..children.length()) + .map(|index| v8::Local::::try_from(children.get_index(scope, index)?).ok()) + .collect() +} + fn type_array<'s>( scope: &mut v8::PinScope<'s, '_>, value: NumericType, diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/operations.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/operations.rs new file mode 100644 index 00000000000..b71e1cab692 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/math/operations.rs @@ -0,0 +1,153 @@ +use super::graph::Unit; +use super::*; + +fn arguments<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: &v8::FunctionCallbackArguments<'s>, +) -> Option>> { + let realm = args.this().get_creation_context(scope)?; + (0..args.length()) + .map(|i| { + numberish_in_realm( + scope, + args.get(i), + webidl::Context::argument("CSSNumericValue", i as usize + 1), + realm, + ) + .map_err(|error| webidl::throw_error(scope, &error)) + .ok() + }) + .collect() +} + +fn unary<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + operation: Kind, + realm: v8::Local<'s, v8::Context>, +) -> Option> { + if kind(scope, object) == Some(operation) { + return operands(scope, object)?.first().copied(); + } + if let Some(mut value) = Unit::read(scope, object) { + if operation == Kind::Negate { + value.value = -value.value; + return Some(value.bind(scope, realm)); + } + if value.unit == "number" { + if value.value == 0.0 { + crate::util::throw_range_error(scope, "Cannot divide by zero"); + return None; + } + value.value = 1.0 / value.value; + return Some(value.bind(scope, realm)); + } + } + math_value(scope, operation, &[object], realm) +} + +// Preserve NaN and signed zero instead of Rust's min/max NaN suppression. +pub(super) fn minimum(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if a == b && a == 0.0 { + if a.is_sign_negative() || b.is_sign_negative() { + -0.0 + } else { + 0.0 + } + } else { + a.min(b) + } +} + +pub(super) fn maximum(a: f64, b: f64) -> f64 { + -minimum(-a, -b) +} + +fn arithmetic<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: &v8::FunctionCallbackArguments<'s>, + operation: Kind, + transform: Option, +) -> Option> { + // The binding checks this before conversion. Finish converting *all* + // arguments before reading mutable operands or testing types/zero divisors. + let realm = args.this().get_creation_context(scope)?; + let mut items = arguments(scope, args)?; + if let Some(transform) = transform { + for item in &mut items { + *item = unary(scope, *item, transform, realm)?; + } + } + let mut all = if kind(scope, args.this()) == Some(operation) { + operands(scope, args.this())? + } else { + vec![args.this()] + }; + all.extend(items); + let units = all + .iter() + .map(|&item| Unit::read(scope, item)) + .collect::>>(); + if let Some(units) = units { + let first = &units[0]; + let mut result = first.clone(); + let simplify = if operation == Kind::Product { + let mut dimension = units.iter().filter(|v| v.unit != "number"); + result.unit = dimension + .next() + .map_or("number", |v| v.unit.as_str()) + .to_owned(); + dimension.next().is_none() + } else { + units.iter().all(|v| v.unit == first.unit) + }; + if simplify { + for unit in &units[1..] { + result.value = match operation { + Kind::Sum => result.value + unit.value, + Kind::Product => result.value * unit.value, + Kind::Min => minimum(result.value, unit.value), + Kind::Max => maximum(result.value, unit.value), + _ => unreachable!(), + }; + } + return Some(result.bind(scope, realm)); + } + } + math_value(scope, operation, &all, realm) +} + +macro_rules! operation { + ($callback:ident, $kind:ident, $transform:expr) => { + pub(super) fn $callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, + ) { + if let Some(value) = arithmetic(scope, &args, Kind::$kind, $transform) { + rv.set(value.into()); + } + } + }; +} +operation!(add_callback, Sum, None); +operation!(sub_callback, Sum, Some(Kind::Negate)); +operation!(mul_callback, Product, None); +operation!(div_callback, Product, Some(Kind::Invert)); +operation!(min_callback, Min, None); +operation!(max_callback, Max, None); + +pub(super) fn equals_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let Some(items) = arguments(scope, &args) else { + return; + }; + if let Some(equal) = graph::equals(scope, args.this(), &items) { + rv.set_bool(equal); + } +} diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs index b0992f960f3..c27418d9f0b 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs @@ -2,11 +2,12 @@ use super::*; use style::typed_om::{NumericValue, TypedValue}; use moli_webapi::css_values::{ CssKeywordValueObjectDeclaration, CssUnitValueObjectDeclaration, - css_unit_value_number, css_unit_value_unit, css_keyword_value, + css_keyword_value, }; pub(super) use moli_webapi::css_values::{ css_keyword_value_constructor_callback, css_unit_value_constructor_callback, style_value_from_text, unit_value, opaque_style_value, associated_property, + css_unit_value_number, css_unit_value_unit, normalize_unit_name, }; mod number; 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 2c253069238..ef7872bea13 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 @@ -64,6 +64,7 @@ mod css_computed_font; mod css_computed_map_enumeration; mod css_math; mod css_numeric_factories; +mod css_numeric_operations; 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_operations.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_operations.js new file mode 100644 index 00000000000..53bca5e8c99 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_operations.js @@ -0,0 +1,130 @@ +(() => { + 'use strict'; + const check = (ok, label) => { if (!ok) throw new Error(label); }; + const eq = (a, b, label) => check(Object.is(a, b), label); + const close = (a, b, label) => check(Math.abs(a - b) <= 1e-12 * Math.max(1, Math.abs(b)), label); + const throws = (fn, C = TypeError) => { + let caught; + try { fn(); } catch (e) { caught = e; } + check(caught instanceof C, `expected ${C.name}`); + return caught; + }; + const methods = ['add', 'sub', 'mul', 'div', 'min', 'max', 'equals', 'to', 'toSum']; + for (const name of methods) { + const desc = Object.getOwnPropertyDescriptor(CSSNumericValue.prototype, name); + check(desc.enumerable && desc.writable && desc.configurable, `${name} descriptor`); + eq(desc.value.length, name === 'to' ? 1 : 0, `${name} length`); + } + eq(CSS.number(2 ** 53).add(1, -(2 ** 53)).value, 0, 'addition is left to right'); + eq(CSS.number(1e-200).mul(1e-200, 1e200).value, 0, 'multiplication is left to right'); + eq(CSS.px(16777217).add(CSS.px(2)).value, 16777219, 'no f32 rounding'); + eq(CSS.px(16777217).to('px').value, 16777217, 'conversion retains double precision'); + const leaf = CSS.px(3), em = CSS.em(2); + const sum = new CSSMathSum(leaf, em); + const appended = sum.add(CSS.percent(4)); + check(appended !== sum && appended.values[0] === leaf && appended.values[1] === em, 'flatten receiver, retain children'); + eq(leaf.add(sum).values[1], sum, 'do not flatten argument'); + eq(CSS.px(1).sub(new CSSMathNegate(em)).values[1], em, 'unwrap native negate'); + eq(CSS.px(1).div(new CSSMathInvert(em)).values[1], em, 'unwrap native inverse'); + const clone = leaf.add(); + check(clone !== leaf, 'unit result is fresh'); + leaf.value = 7; + eq(clone.value, 3, 'arithmetic result is a snapshot'); + check(sum.equals(new CSSMathSum(CSS.px(7), CSS.em(2))), 'structural equality'); + check(!sum.equals(new CSSMathSum(CSS.em(2), CSS.px(7))), 'equality preserves order'); + check(!CSS.in(1).equals(CSS.px(96)), 'equality does not convert units'); + check(sum.equals() && CSS.number(5).equals('5', 5), 'empty and numberish equality'); + const sentinel = {}; + const failNumber = {valueOf() { throw sentinel; }}; + const failString = {toString() { throw sentinel; }}; + for (const fn of [ + () => CSS.number(1).div(0, failNumber), + () => CSS.number(1).add(CSS.px(1), failNumber), + () => CSS.number(1).equals(2, failNumber), + () => CSS.px(1).toSum('invalid', failString), + ]) { + let caught; + try { fn(); } catch (e) { caught = e; } + eq(caught, sentinel, 'convert all arguments before native operation'); + } + const mutable = CSS.number(1), order = []; + eq(mutable.add( + {valueOf() { order.push(1); mutable.value = 4; return 2; }}, + {valueOf() { order.push(2); mutable.value = 5; return 3; }}, + ).value, 10, 'read mutable slots after conversion'); + eq(order.join(), '1,2', 'WebIDL conversion order'); + for (const zero of [0, -0]) throws(() => CSS.number(1).div(zero), RangeError); + eq(throws(() => leaf.to('lemon'), DOMException).name, 'SyntaxError', 'invalid unit'); + throws(() => leaf.to()); + eq(leaf.to('PX').unit, 'px', 'unit normalization'); + eq(CSS.in(1).to('px').value, 96, 'absolute length'); + close(CSS.Q(40).to('cm').value, 1, 'quarter millimetres'); + close(CSS.rad(Math.PI).to('deg').value, 180, 'radians'); + eq(CSS.kHz(1).to('hz').value, 1000, 'frequency'); + eq(CSS.ms(1000).to('s').value, 1, 'time'); + eq(CSS.dpi(96).to('dppx').value, 1, 'resolution'); + close(CSS.dpcm(1).to('dpi').value, 2.54, 'resolution ratio'); + throws(() => CSS.em(1).to('px')); + throws(() => CSS.vw(1).to('vh')); + throws(() => CSS.percent(1).to('number')); + const distributed = new CSSMathProduct(new CSSMathSum(CSS.px(1), CSS.em(2)), 3).toSum('em', 'px'); + eq(distributed.values[0].value, 6, 'distributive product em'); + eq(distributed.values[1].value, 3, 'distributive product px'); + const greedy = new CSSMathSum(CSS.cm(1), CSS.mm(10)).toSum('mm', 'cm', 'mm'); + close(greedy.values[0].value, 20, 'greedy conversion'); + eq(greedy.values[1].value, 0, 'unconsumed compatible unit'); + eq(greedy.values[2].value, 0, 'duplicate requested unit'); + eq([...sum.toSum().values].map(v => v.unit).join(), 'em,px', 'sort unit names'); + throws(() => sum.toSum('px')); + throws(() => leaf.toSum('px', 's')); + const opaque = new CSSMathSum(CSS.px(1), CSS.em(2)); + const unit = opaque.values[0]; + for (const [object, keys] of [[unit, ['value','unit','toString',Symbol.toPrimitive]], [opaque, ['values','operator','constructor']]]) { + for (const key of keys) Object.defineProperty(object, key, {get() { throw sentinel; }}); + } + check(opaque.equals(new CSSMathSum(CSS.px(1), CSS.em(2))), 'comparison uses native slots'); + eq(opaque.toSum('px','em').values[0].value, 1, 'conversion uses native slots'); + eq(opaque.add(CSS.percent(1)).values[0], unit, 'arithmetic uses native slots'); + let proxyReads = 0; + const numberProxy = new Proxy(CSS.px(3), {get(target, key) { proxyReads++; if (key === Symbol.toPrimitive) return () => 4; throw sentinel; }}); + eq(CSS.number(2).add(numberProxy).value, 6, 'author Proxy uses numeric union'); + eq(proxyReads, 1, 'single ToNumber hook'); + const realms = [globalThis]; + if (typeof document !== 'undefined') realms.push(document.querySelector('iframe').contentWindow); + for (const realm of realms) { + throws(() => realm.CSSNumericValue.prototype.div.call(CSS.number(1), 0), realm.RangeError); + throws(() => realm.CSSNumericValue.prototype.add.call(CSS.px(1), CSS.s(1)), realm.TypeError); + eq(throws(() => realm.CSSNumericValue.prototype.to.call(CSS.px(1), 'lemon'), realm.DOMException).name, 'SyntaxError', 'callee exception realm'); + const receiver = CSS.px(1); + for (const name of methods) { + const method = realm.CSSNumericValue.prototype[name]; + const revoked = Proxy.revocable(receiver, {}); revoked.revoke(); + let conversions = 0, traps = 0; + const badArgument = {valueOf() { conversions++; throw sentinel; }, toString() { conversions++; throw sentinel; }}; + for (const bad of [{}, Object.create(receiver), Object.create(CSSNumericValue.prototype), new Proxy(receiver, {get() { traps++; throw sentinel; }}), revoked.proxy]) { + throws(() => method.call(bad, badArgument), realm.TypeError); + } + eq(conversions, 0, `${name} brand check precedes conversion`); + eq(traps, 0, `${name} brand check ignores Proxy traps`); + for (const owner of realms) { + const receiver = owner.CSS.number(1); + const arg = name === 'to' || name === 'toSum' ? 'number' : 1; + const good = method.call(receiver, arg); + if (name !== 'equals') check(good instanceof (name === 'toSum' ? owner.CSSMathSum : owner.CSSUnitValue), `${name} receiver realm`); + const U = owner.CSSUnitValue, S = owner.CSSMathSum; + owner.CSSUnitValue = owner.CSSMathSum = function () { throw sentinel; }; + try { + check(realm.CSSNumericValue.prototype.add.call(owner.CSS.px(1), CSS.percent(1)) instanceof S, 'intrinsic math constructor'); + check(realm.CSSNumericValue.prototype.to.call(receiver, 'number') instanceof U, 'intrinsic unit constructor'); + } finally { owner.CSSUnitValue = U; owner.CSSMathSum = S; } + const product = realm.CSSNumericValue.prototype.mul.call(new owner.CSSMathProduct(owner.CSS.px(1), owner.CSS.px(1)), 2); + check(product instanceof owner.CSSMathProduct && product.values[2] instanceof U, 'rectified argument realm'); + const inverse = realm.CSSNumericValue.prototype.div.call(owner.CSS.px(1), realm.CSS.em(2)); + check(inverse.values[1] instanceof owner.CSSMathInvert, 'inverse realm'); + const converted = realm.CSSNumericValue.prototype.toSum.call(owner.CSS.px(1)); + check(converted.values[0] instanceof U, 'converted child realm'); + } + } + } + return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_operations.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_operations.rs new file mode 100644 index 00000000000..8ea57296a75 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_operations.rs @@ -0,0 +1,68 @@ +use super::*; + +#[test] +fn css_numeric_operations_preserve_brands_realms_and_conversion_order() { + let mut vm = new_parsed_test_vm( + "https://css-numeric-operations.test/", + "", + ); + assert_eq!( + vm.eval(include_str!("css_numeric_operations.js")).unwrap(), + "true" + ); +} + +#[test] +fn css_numeric_operations_retain_special_values_and_type_constraints() { + let mut vm = new_storage_test_vm("https://css-numeric-special-values.test/"); + assert_eq!(vm.eval(r#"(() => { + const check = (ok, message) => { if (!ok) throw new Error(message); }; + check(Object.is(CSS.number(0).min(-0).value, -0), 'min signed zero'); + check(Object.is(CSS.number(-0).max(0).value, 0), 'max signed zero'); + check(Object.is(new CSSMathMin(0, -0).to('number').value, -0), 'sum min signed zero'); + check(Object.is(new CSSMathMax(-0, 0).to('number').value, 0), 'sum max signed zero'); + const infinity = CSS.number(Number.MAX_VALUE).mul(2); + const nan = infinity.sub(infinity); + check(infinity.value === Infinity && Number.isNaN(nan.value), 'double overflow and NaN'); + check(!nan.equals(nan), 'NaN is unequal even on the same object'); + check(Number.isNaN(CSS.number(1).min(nan).value), 'min propagates NaN'); + check(Number.isNaN(CSS.number(1).max(nan).value), 'max propagates NaN'); + check(Number.isNaN(new CSSMathClamp(0, nan, 10).to('number').value), 'clamp propagates NaN'); + check(new CSSMathClamp(20, 0, 10).to('number').value === 20, 'clamp lower bound wins'); + const length = CSS.px(1).add(CSS.percent(2)); + const angle = CSS.deg(1).add(CSS.percent(2)); + for (const method of ['mul', 'div']) { + try { length[method](angle); return false; } catch (e) { if (!(e instanceof TypeError)) throw e; } + } + for (const method of ['min', 'max']) { + try { CSS.number(1)[method](CSS.px(1)); return false; } catch (e) { if (!(e instanceof TypeError)) throw e; } + } + return true; + })()"#).unwrap(), "true"); +} + +#[test] +fn css_numeric_operations_bound_expansion_and_share_deep_graph_work() { + let mut vm = new_storage_test_vm("https://css-numeric-graphs.test/"); + assert_eq!(vm.eval(r#"(() => { + const check = (ok, message) => { if (!ok) throw new Error(message); }; + let a = CSS.number(1), b = CSS.number(1); + for (let i = 0; i < 3000; ++i) { + a = new CSSMathNegate(a); b = new CSSMathNegate(b); + } + check(a.equals(b) && a.to('number').value === 1, 'deep graph'); + const leaf = CSS.number(1); + a = leaf; b = CSS.number(1); + for (let i = 0; i < 200; ++i) { + a = new CSSMathSum(a, a); b = new CSSMathSum(b, b); + } + check(a.equals(b) && a.to('number').value === 2 ** 200, 'shared DAG'); + leaf.value = 3; + check(!a.equals(b) && a.to('number').value === 3 * 2 ** 200, 'fresh mutable values'); + let expansion = new CSSMathSum(CSS.px(1), CSS.em(1)); + for (let i = 0; i < 6; ++i) expansion = new CSSMathProduct(expansion, expansion); + try { expansion.toSum(); return false; } catch (e) { if (!(e instanceof RangeError)) throw e; } + check(CSS.px(4).to('px').value === 4, 'realm remains usable after resource limit'); + return true; + })()"#).unwrap(), "true"); +} diff --git a/moli-webapi/src/css_values.rs b/moli-webapi/src/css_values.rs index 5287e2ecbe8..1ef886d080b 100644 --- a/moli-webapi/src/css_values.rs +++ b/moli-webapi/src/css_values.rs @@ -279,7 +279,7 @@ fn parse_single_unit_value(text: &str) -> Option<(f64, String)> { .ok() } -fn normalize_unit_name(unit: &str) -> Option { +pub fn normalize_unit_name(unit: &str) -> Option { let unit = unit.to_ascii_lowercase(); VALID_UNIT_NAMES.contains(&unit.as_str()).then_some(unit) }