Scripts: UnitValue pixels and percentages use the left object's base

With two UnitValues and a left one in px or %, the right one is now
converted with the left one's baseUnit, so a 1 px value with a 2 pt base
plus 1 in gives 37 px. Conversions keep their intermediate values in
range, so a result that is a finite number no longer fails because a
step on the way overflows or reaches 0.
This commit is contained in:
dotCooCoo
2026-11-21 20:25:38 -08:00
parent 1ab09c8978
commit 7e5b421db2
3 changed files with 105 additions and 23 deletions
+68 -21
View File
@@ -12,8 +12,8 @@
//!
//! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and
//! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in
//! its unit; with two, the right one is converted to the left one's unit first and the result is in
//! the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the
//! its unit; with two, the right one is converted to the left one's unit first, with the left one's
//! base for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the
//! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its
//! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not
//! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all
@@ -141,16 +141,45 @@ fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 {
a
}
/// `value` in unit `from`, given in unit `to`; both have a length.
fn between(value: f64, from: (u64, u64), to: (u64, u64)) -> f64 {
/// The ratio of a length in unit `from` to the same length in unit `to`, as a reduced fraction.
fn ratio(from: Unit, to: Unit) -> (f64, f64) {
let (from, to) = (from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1)));
// The products stay below 2^53, so the ratio's terms are exact.
let (n, d) = (from.0 * to.1, from.1 * to.0);
let g = greatest_common_divisor(n, d).max(1);
#[allow(clippy::cast_precision_loss)]
let (n, d) = ((n / g) as f64, (d / g) as f64);
let scaled = value * n;
// A large value is divided first, so a result that is finite does not overflow on the way.
if scaled.is_finite() { scaled / d } else { value / d * n }
(((n / g) as f64), ((d / g) as f64))
}
/// `x` as a significand in [0.5, 1) and a power of 2; zero, infinities and NaN as themselves.
fn split(x: f64) -> (f64, i32) {
if x == 0.0 || !x.is_finite() {
return (x, 0);
}
let (x, shift) = if x.is_normal() { (x, 0) } else { (x * 2f64.powi(64), -64) };
let bits = x.to_bits();
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
let exponent = ((bits >> 52) & 0x7ff) as i32 - 1022;
(f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), exponent + shift)
}
/// The product of `factors` divided by each of `divisors`, in that order. Each step rounds as
/// plain multiplication and division do, but no step overflows or reaches 0 on the way, so only
/// a result outside the range of numbers is infinite or 0.
fn product(factors: &[f64], divisors: &[f64]) -> f64 {
let (mut m, mut e) = (1.0, 0);
for (&x, divide) in factors.iter().map(|x| (x, false)).chain(divisors.iter().map(|x| (x, true))) {
let (xm, xe) = split(x);
let (rm, re) = split(if divide { m / xm } else { m * xm });
(m, e) = (rm, if divide { e - xe } else { e + xe } + re);
}
while e > 1000 {
(m, e) = (m * 2f64.powi(1000), e - 1000);
}
while e < -1000 {
(m, e) = (m * 2f64.powi(-1000), e + 1000);
}
m * 2f64.powi(e)
}
fn invalid(i: &mut Interp, what: &str) -> Abrupt {
@@ -171,26 +200,22 @@ fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult<f64> {
return Err(invalid(i, what));
};
let base = m.base;
let base_inches = base.unit.inches().unwrap_or((1, 1));
let r = match (from, to) {
(a, b) if a == b => m.value,
(Unit::Px, Unit::Percent) => m.value * 100.0,
(Unit::Percent, Unit::Px) => m.value / 100.0,
(Unit::Px | Unit::Percent, _) => {
let to = to.inches().unwrap_or((1, 1));
let bases = if from == Unit::Px { m.value } else { m.value / 100.0 };
// A large base is applied after the unit ratio, so a result that is finite does not
// overflow on the way.
let scaled = bases * base.value;
if scaled.is_finite() { between(scaled, base_inches, to) } else { between(bases, base_inches, to) * base.value }
let (n, d) = ratio(base.unit, to);
if from == Unit::Px { product(&[m.value, base.value, n], &[d]) } else { product(&[m.value, base.value, n], &[100.0, d]) }
}
(_, Unit::Px | Unit::Percent) => {
let from = from.inches().unwrap_or((1, 1));
let lengths = between(m.value, from, base_inches);
let bases = if lengths.is_finite() { lengths / base.value } else { between(m.value / base.value, from, base_inches) };
if to == Unit::Px { bases } else { bases * 100.0 }
let (n, d) = ratio(from, base.unit);
if to == Unit::Px { product(&[m.value, n], &[d, base.value]) } else { product(&[m.value, n, 100.0], &[d, base.value]) }
}
(_, _) => {
let (n, d) = ratio(from, to);
product(&[m.value, n], &[d])
}
(_, _) => between(m.value, from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))),
};
if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) }
}
@@ -478,7 +503,29 @@ pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsRe
let Some(unit) = l.unit else {
return Err(invalid(i, what));
};
let y = convert(i, &r, unit, what)?;
// Pixels and percentages of the left object are measured with its own base.
let y = match unit {
Unit::Px | Unit::Percent if r.base != l.base || !matches!(r.unit, Some(Unit::Px | Unit::Percent)) => match r.unit {
Some(from @ (Unit::Px | Unit::Percent)) => {
let (n, d) = ratio(r.base.unit, l.base.unit);
let mut factors = vec![r.value, r.base.value, n];
let mut divisors = vec![d, l.base.value];
if from == Unit::Percent {
divisors.push(100.0);
}
if unit == Unit::Percent {
factors.push(100.0);
}
let y = product(&factors, &divisors);
if !y.is_finite() {
return Err(not_finite(i, what));
}
y
}
_ => convert(i, &Measure { base: l.base, ..r }, unit, what)?,
},
_ => convert(i, &r, unit, what)?,
};
(l.value, y, l)
}
(Some(l), None, _, Value::Number(n)) => (l.value, *n, l),
+35
View File
@@ -38,6 +38,11 @@ fn close(got: f64, want: f64, what: &str) {
assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}");
}
/// `got` is within a millionth of `want`, which is not 0, however small `want` is.
fn relative(got: f64, want: f64, what: &str) {
assert!((got / want - 1.0).abs() <= 1e-6, "{what}: {got} is not {want}");
}
/// Each length unit with its length in inches.
const LENGTHS: [(&str, f64); 13] = [
("in", 1.0),
@@ -234,6 +239,36 @@ fn arithmetic_gives_a_new_unit_value_in_the_left_unit() {
assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript");
}
#[test]
fn the_left_objects_base_measures_its_pixels_and_percentages() {
let mut r = realm();
let pair = "var l = UnitValue(1, 'px'); l.baseUnit = UnitValue(2, 'pt'); var m = UnitValue(1, 'px'); \
m.baseUnit = UnitValue(4, 'pt'); var p = UnitValue(50, '%'); p.baseUnit = UnitValue(1, 'in');";
assert_eq!(text(&mut r, &format!("{pair} String(l + UnitValue(1, 'in'))")), "37 px");
assert_eq!(text(&mut r, &format!("{pair} String(l + m)")), "3 px");
close(number(&mut r, &format!("{pair} (p + l).value")), 50.0 + 200.0 / 72.0, "2 pt as a percentage of 1 in");
assert!(boolean(&mut r, &format!("{pair} l < m && m > l && l == UnitValue(2, 'pt')")));
let large = "var b = UnitValue(0, 'px'); b.baseUnit = UnitValue(1e308, 'pt'); var c = UnitValue(1e300, 'px'); \
c.baseUnit = UnitValue(1e10, 'pt'); [(b + UnitValue(1e304, 'km')).value, (b + c).value].join()";
let got: Vec<f64> = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect();
close(got[0], 1e304 / 1e308 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base");
close(got[1], 1e300 / 1e308 * 1e10, "large pixels of one large base in pixels of another");
let small = "var s = UnitValue(0, 'px'); s.baseUnit = UnitValue(1e-300, 'pt'); var t = UnitValue(1e-200, 'px'); \
t.baseUnit = UnitValue(1e-200, 'pt'); (s + t).value";
let units = "var u = UnitValue(0, 'px'); u.baseUnit = UnitValue(1e20, 'pt'); var v = UnitValue(1e308, 'px'); \
v.baseUnit = UnitValue(1e10, 'km'); (u + v).value";
close(number(&mut r, units), 1e298 * 1000.0 * 5000.0 / 127.0 * 72.0, "large pixels of a base in a larger unit");
let apart = "var w = UnitValue(0, 'px'); w.baseUnit = UnitValue(7e-16, 'km'); var x = UnitValue(1e-20, 'px'); \
x.baseUnit = UnitValue(1e308, 'pt'); (w + x).value";
close(number(&mut r, apart), 1e288 / (1000.0 * 5000.0 / 127.0 * 72.0) / 7e-16, "bases too far apart for their ratio");
relative(number(&mut r, small), 1e-100, "small pixels of one small base in pixels of another");
let tiny = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-200, 'km'); var z = UnitValue(1e-320, 'px'); (y + z).value";
relative(number(&mut r, tiny), 1e-320 * 1e200 / (1000.0 * 5000.0 / 127.0 * 72.0), "a tiny value in pixels of a tiny base");
let tinier = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-320, 'pt'); var z = UnitValue(1e-320, 'px'); \
z.baseUnit = UnitValue(1e-10, 'pt'); (y + z).value";
relative(number(&mut r, tinier), 1e-10, "a tiny value of a small base in pixels of a tiny base");
}
#[test]
fn comparisons_use_the_numbers_and_greater_is_the_negation() {
let mut r = realm();
+2 -2
View File
@@ -2736,8 +2736,8 @@ number in another unit and `convert(unit)` changes the object to it and returns
100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets
it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation,
such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and
give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit and the result is in
the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and
give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit, with the left one's
`baseUnit` for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and
`>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~`
inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators,
work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or