Expressions: a number and its unit are one value (10 mm / 2 mm is 5) (#6331)

* Expressions: a number and its unit are one value (10 mm / 2 mm is 5)

A unit written after a number was multiplied in at the precedence of `*` and
`/`, so `10 mm / 2 mm` was (10 mm / 2) mm = 5 mm² and `90 deg / 1 rad` a value
in angle², reported as a unit error. The number now takes the unit after it
before `*` and `/` apply; a fraction of numbers before a unit stays one value
(`1/2 in` is half an inch), and an exponent stays a plain number (`2^3 mm`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expressions: after a division, a fraction before a unit only when closed up

`width / 10 / 2 mm` read the `10 / 2 mm` as the fraction 5 mm and gave
width / (5 mm) = 8 instead of (width / 10) / 2 mm = 2. After a `/` the
fraction rule now needs the fraction written without spaces (`1 in / 1/2 in`
is still 2); elsewhere `1/2 in` and `10 / 2 mm` are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ivisaf
2026-10-26 12:24:34 +00:00
committed by GitHub
parent 91638cb1f3
commit 3bcf77ee32
2 changed files with 91 additions and 9 deletions
+87 -8
View File
@@ -611,6 +611,8 @@ pub fn length_unit_or_mm(units: &str) -> &str {
struct Parser<'a> {
toks: Vec<Tok>,
/// Each token's byte range in the source: whether a fraction is written closed up.
spans: Vec<(usize, usize)>,
pos: usize,
lookup: &'a dyn Fn(&str) -> Result<Value, DocError>,
depth: usize,
@@ -670,35 +672,79 @@ impl Parser<'_> {
}
}
fn unary(&mut self) -> Result<Value, DocError> {
self.signed(true)
}
/// A signed operand. `glue`: a number takes the unit written after it (not in an exponent).
fn signed(&mut self, glue: bool) -> Result<Value, DocError> {
match self.peek() {
Some(Tok::Op('-')) => {
self.pos += 1;
self.enter()?;
let v = self.unary()?;
let v = self.signed(glue)?;
self.depth -= 1;
Ok(Value { v: -v.v, ..v })
}
Some(Tok::Op('+')) => {
self.pos += 1;
self.enter()?;
let v = self.unary()?;
let v = self.signed(glue)?;
self.depth -= 1;
Ok(v)
}
_ => self.power(),
_ => self.power(glue),
}
}
fn power(&mut self) -> Result<Value, DocError> {
let base = self.atom()?;
fn power(&mut self, glue: bool) -> Result<Value, DocError> {
let number = matches!(self.peek(), Some(Tok::Num(_)));
let at = self.pos;
let mut base = self.atom()?;
// A number and the unit after it are one quantity, bound tighter than `*` and `/`:
// `10 mm / 2 mm` is 5, not (10 mm / 2) mm = 5 mm². The unit keeps its own power
// (`3 mm^2`). A name that is not a unit (`2 width`) stays an ordinary product.
if glue && number {
// A fraction of two numbers before a unit is one value, as sizes are written:
// `1/2"` and `1/2 in` are half an inch (as the mixed number `2 1/8"` is one value).
// After a division only written closed up: `1 in / 1/2 in` is 2, but
// `width / 10 / 2 mm` is (width / 10) / 2 mm.
if let (Some(Tok::Op('/')), Some(Tok::Num(d))) = (self.peek(), self.toks.get(self.pos + 1))
&& self.unit_at(self.pos + 2)
&& (!self.after_division(at) || self.closed_up(at, self.pos + 1))
{
let d = Value::num(*d);
self.pos += 2;
base = mul(base, d, true)?;
}
if self.unit_at(self.pos) {
let u = self.power(false)?;
return mul(base, u, false);
}
}
if let Some(Tok::Op('^')) = self.peek() {
self.pos += 1;
self.enter()?;
let e = self.unary()?;
// The exponent is a plain number: `2^3 mm` stays 8 mm.
let e = self.signed(false)?;
self.depth -= 1;
return pow(base, e);
}
Ok(base)
}
/// Whether the operand starting at token `i` is divided by: a `/` before it, past any signs.
fn after_division(&self, i: usize) -> bool {
let mut k = i;
while k > 0 && matches!(self.toks.get(k - 1), Some(Tok::Op('+' | '-'))) {
k -= 1;
}
k > 0 && matches!(self.toks.get(k - 1), Some(Tok::Op('/')))
}
/// Whether tokens `a` to `b` are written without spaces between them.
fn closed_up(&self, a: usize, b: usize) -> bool {
(a..b).all(|i| matches!((self.spans.get(i), self.spans.get(i + 1)), (Some(x), Some(y)) if x.1 == y.0))
}
/// Whether the token at `i` is a unit name, not called as a function.
fn unit_at(&self, i: usize) -> bool {
matches!(self.toks.get(i), Some(Tok::Id(id)) if unit(id).is_some()) && !matches!(self.toks.get(i + 1), Some(Tok::Op('(')))
}
fn atom(&mut self) -> Result<Value, DocError> {
match self.next() {
Some(Tok::Num(v)) => Ok(Value::num(v)),
@@ -931,11 +977,11 @@ pub fn eval_with(s: &str, lookup: &dyn Fn(&str) -> Result<Value, DocError>) -> R
/// Evaluate an expression reading bare numbers next to lengths / angles in `defaults`.
pub fn eval_with_defaults(s: &str, lookup: &dyn Fn(&str) -> Result<Value, DocError>, defaults: Defaults) -> Result<Value, DocError> {
let toks = lex(s)?;
let (toks, spans): (Vec<Tok>, Vec<(usize, usize)>) = lex_spans(s)?.into_iter().map(|(t, a, b)| (t, (a, b))).unzip();
if toks.is_empty() {
return Err(DocError::Expr("empty expression".into()));
}
let mut p = Parser { toks, pos: 0, lookup, depth: 0, defaults };
let mut p = Parser { toks, spans, pos: 0, lookup, depth: 0, defaults };
let v = p.expr()?;
if p.pos < p.toks.len() {
return Err(DocError::Expr(format!("unexpected input in `{s}`")));
@@ -1192,6 +1238,39 @@ mod tests {
}
}
#[test]
fn a_number_and_its_unit_are_one_quantity() {
// `10 mm / 2 mm` divides by 2 mm; it is not `(10 mm / 2) mm`, a value in mm².
assert_eq!(ev("10 mm / 2 mm", Kind::Unitless).unwrap(), 5.0);
assert_eq!(ev("10mm/2mm", Kind::Unitless).unwrap(), 5.0);
assert_eq!(ev("width / 4 mm", Kind::Unitless).unwrap(), 10.0);
assert_eq!(ev("6 mm / 2 mm * 3", Kind::Unitless).unwrap(), 9.0);
assert!((ev("90 deg / 1 rad", Kind::Unitless).unwrap() - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
assert!((ev("(ang - 30 deg) / 1 rad * width", Kind::Length).unwrap() - 40.0 * 60f64.to_radians()).abs() < 1e-12);
assert_eq!(ev("1 in / 1 mm", Kind::Unitless).unwrap(), 25.4);
assert_eq!(ev("2 1/2 in / 1 in", Kind::Unitless).unwrap(), 2.5);
assert_eq!(ev("1\" / 1 mm", Kind::Unitless).unwrap(), 25.4);
assert_eq!(ev("-10 mm / 2 mm", Kind::Unitless).unwrap(), -5.0);
// A fraction of numbers right before a unit stays one value: half an inch.
assert_eq!(ev("1/2 in", Kind::Length).unwrap(), 12.7);
assert_eq!(ev("width + 3/4\"", Kind::Length).unwrap(), 40.0 + 0.75 * 25.4);
assert_eq!(ev("1 in / 1/2 in", Kind::Unitless).unwrap(), 2.0);
assert_eq!(ev("10 / 2 mm", Kind::Length).unwrap(), 5.0);
// After a division, a spaced-out `/` divides again: (width / 10) / 2 mm.
assert_eq!(ev("width / 10 / 2 mm", Kind::Unitless).unwrap(), 2.0);
assert_eq!(ev("width / -10 / 2 mm", Kind::Unitless).unwrap(), -2.0);
assert_eq!(ev("width / 10/2 mm", Kind::Unitless).unwrap(), 8.0);
// The unit keeps its own power, and an exponent stays a plain number.
assert_eq!(ev("sqrt(9 mm^2)", Kind::Length).unwrap(), 3.0);
assert_eq!(ev("8 mm^3 / 2 mm^2", Kind::Length).unwrap(), 4.0);
assert_eq!(ev("2^3 mm", Kind::Length).unwrap(), 8.0);
// A number next to a name that is not a unit is a product, as before.
assert_eq!(ev("2 width", Kind::Length).unwrap(), 80.0);
// Unchanged: a unit alone, and a unit after a parenthesis.
assert_eq!(ev("width / mm", Kind::Unitless).unwrap(), 40.0);
assert_eq!(ev("(10 / 2) mm", Kind::Length).unwrap(), 5.0);
}
#[test]
fn arithmetic_and_units() {
assert_eq!(ev("10", Kind::Length).unwrap(), 10.0);
+4 -1
View File
@@ -40,7 +40,10 @@ and the preview follows each step. An expression such as `width / 2` is left as
Expressions are unit-aware: `2 * width + 5 mm`, `angle / 2`, `sqrt(area)`, `1 in + 3 mm`, using
`+ - * / ^`, parentheses, `sin cos tan asin acos atan atan2 sqrt abs min max floor ceil round mod
trunc` and unit conversion. A decimal comma works too, outside parentheses: `2,5 mm` is
trunc` and unit conversion. A number and the unit after it are one value: `10 mm / 2 mm` is 5
and `90 deg / 1 rad` is π/2, and a fraction of numbers before a unit is one value too (`1/2 in`
is half an inch; after a `/` only written without spaces: `1 in / 1/2 in` is 2, while
`width / 10 / 2 mm` divides by 10 and then by 2 mm). A decimal comma works too, outside parentheses: `2,5 mm` is
`2.5 mm` (inside a function's parentheses the comma separates its arguments, so write
`max(2.5, 3)` there). A mixed number is one value, as imperial sizes are written: `2 1/8"` and
`3 7/16 in` are 2.125 in and 3.4375 in (a whole number, a space, then a proper fraction of whole