From aa27f55ab520fd727cefd7cb4f9dadba5178fb2b Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Sat, 26 Sep 2026 15:11:16 -0700 Subject: [PATCH] Add matrices, with swizzle and range literals, to the math expression parser (#4611) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add matrices to the math expression parser as a second sort beside values * Add Transform input and output to the Math f(x) node * Add ranges and boxes to the math expression parser with inside, clamp, and remap over them * Add Transform lists to the Math f(…) node with reducers composing, averaging, and counting them * Lex a number's trailing e as Euler's number unless an exponent's digits follow it * Fix matrix inversion scaling, exact matrix powers, infinite shears, matrix means, kept axes, and the Transform default * Make shared box parts flat, give composed regions their inner map's axes, and fix lone logic items, spaced ranges, and the Math f(…) tooltip * Transpose across spaces, name fractional matrix powers, check matrix builtin arities when parsing, read range literals by their corners, and let host functions shadow matrix builtins * Make inside and clamp hold a region's uncovered parts at zero, so a box contains only the points between its corners * Require hosts to declare the functions they provide, name the region functions' syntax node after its builtin, and remap onto ranges with equal infinite corners * Apply a matrix to the whole product after it, so M 2 v is M (2 v) * Pin prefix NOT's precedence above products, comparisons, and AND with tests * Rename inside to within, since a range's ends count and the geometry predicates with a point first use that name * Keep a range's corners as written, so clamp orders an integer past the reals' limit exactly * Give within a tolerance of a billionth of the region's scale, so a point a float error off an edge or a flat side counts * Write a unit part as its basis alone, so the identity displays as [1;i;j;k] * Add tests for product folds, mixed chains, remap, and rejected inputs * Evaluate matrix operands, builder arguments, regions, and comparison chains on the stack instead of the heap * Build the expression parsers once per thread, since building the combinator tree cost as much as parsing a short expression * Compare a chain reducer's items by their order directly, and reject an item with no order rather than reading it as false * Send a host-built list of builder arguments or regions past the stack buffers to the heap instead of rejecting it --- libraries/math-parser/Cargo.toml | 2 +- libraries/math-parser/src/ast.rs | 143 +++++- libraries/math-parser/src/constants.rs | 218 +++++++-- libraries/math-parser/src/context.rs | 22 + libraries/math-parser/src/executer.rs | 340 +++++++++++--- libraries/math-parser/src/lexer.rs | 69 ++- libraries/math-parser/src/lib.rs | 520 +++++++++++++++++++-- libraries/math-parser/src/matrix.rs | 570 ++++++++++++++++++++++++ libraries/math-parser/src/object.rs | 94 ++++ libraries/math-parser/src/parser.rs | 297 ++++++++---- libraries/math-parser/src/quaternion.rs | 9 +- libraries/math-parser/src/reducer.rs | 167 ++++++- libraries/math-parser/src/sort.rs | 243 ++++++++++ libraries/math-parser/src/value.rs | 1 + node-graph/nodes/math/src/lib.rs | 222 +++++++-- 15 files changed, 2635 insertions(+), 282 deletions(-) create mode 100644 libraries/math-parser/src/matrix.rs create mode 100644 libraries/math-parser/src/object.rs create mode 100644 libraries/math-parser/src/sort.rs diff --git a/libraries/math-parser/Cargo.toml b/libraries/math-parser/Cargo.toml index 7a767fd71d..25975a5867 100644 --- a/libraries/math-parser/Cargo.toml +++ b/libraries/math-parser/Cargo.toml @@ -18,7 +18,7 @@ workspace = true thiserror = "2.0" num-complex = "0.4" unicode-ident = "1.0" -chumsky = { version = "0.10", default-features = false, features = ["std"] } +chumsky = { version = "0.10", default-features = false, features = ["std", "unstable"] } [dev-dependencies] criterion = { workspace = true } diff --git a/libraries/math-parser/src/ast.rs b/libraries/math-parser/src/ast.rs index 68bbd96c28..7300920599 100644 --- a/libraries/math-parser/src/ast.rs +++ b/libraries/math-parser/src/ast.rs @@ -1,3 +1,4 @@ +use crate::constants::{MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix}; use crate::value::Value; #[derive(Debug, Clone, PartialEq)] @@ -62,40 +63,162 @@ pub enum UnaryOp { Not, /// The magnitude bars `|x|`: absolute value on the reals, extending to the Euclidean magnitude. Magnitude, + /// The postfix `A^T`, swapping a linear matrix's rows and columns. + Transpose, } +/// The tree as written, before each subexpression's sort is read from its spelling. #[derive(Debug, PartialEq)] -pub enum Node { +pub enum Syntax { Lit(Literal), Var(String), FnCall { name: String, - expr: Vec, + expr: Vec, }, BinOp { - lhs: Box, + lhs: Box, op: BinaryOp, - rhs: Box, + rhs: Box, }, UnaryOp { - expr: Box, + expr: Box, op: UnaryOp, }, /// A chain of two or more comparisons like `a < b < c`, each operator paired with the operand after it: one predicate over each adjacent pair, or over every pair for `!=`. Comparison { - first: Box, - rest: Vec<(BinaryOp, Node)>, + first: Box, + rest: Vec<(BinaryOp, Syntax)>, + }, + /// A chain of three or more factors joined by `*`, `/`, or juxtaposition, each operator paired with the factor after it, left flat for + /// the sort pass to group, since a matrix applies to every factor after it. + Product { + first: Box, + rest: Vec<(BinaryOp, Syntax)>, }, /// The cases of math's `cases` notation, `{a if cond, b otherwise}`: disjoint conditions in no meaningful order, with `otherwise` holding when none of them do. Piecewise { cases: Vec, - otherwise: Option>, + otherwise: Option>, + }, + /// A matrix literal of up to four whole values: rows like `[a;b]`, or columns like `[a,b]`, the images of the basis directions. + Matrix { + entries: Vec, + by_rows: bool, + }, + /// The range `a..b`, the map sending parameter `0` to `a` and `1` to `b`, which vector corners make a box. + Range { + from: Box, + to: Box, }, } /// One case of a piecewise, the value it takes where its condition holds. #[derive(Debug, PartialEq)] pub struct Case { - pub value: Node, - pub condition: Node, + pub value: Syntax, + pub condition: Syntax, +} + +/// A parsed expression, whose every subexpression has the sort its spelling fixes: a value or a matrix. +#[derive(Debug)] +pub enum Node { + Value(ValueNode), + Matrix(MatrixNode), +} + +/// A subexpression evaluating to a value. +#[derive(Debug)] +pub enum ValueNode { + Lit(Literal), + Var(String), + FnCall { + name: String, + expr: Vec, + }, + BinOp { + lhs: Box, + op: BinaryOp, + rhs: Box, + }, + UnaryOp { + expr: Box, + op: UnaryOp, + }, + Comparison { + first: Box, + rest: Vec<(BinaryOp, ValueNode)>, + }, + Piecewise { + cases: Vec>, + otherwise: Option>, + }, + /// A matrix applied to a value, `M v`. + Apply { + matrix: Box, + value: Box, + }, + /// A function of a matrix with a value result, like `det(A)`. + OfMatrix { + function: MatrixToValue, + matrix: Box, + }, + /// A function of a value and regions with a value result, like `within(p, R)`. + OfValueAndRegions { + function: ValueOfRegions, + value: Box, + regions: Vec, + }, + /// A chain of `==`, or of `!=`, over matrices, pointwise. + MatrixComparison { + matrices: Vec, + distinct: bool, + }, +} + +/// A subexpression evaluating to a matrix. +#[derive(Debug)] +pub enum MatrixNode { + Var(String), + Literal { + entries: Vec, + by_rows: bool, + }, + /// A function building a matrix from values, like `rotation(angle)`. + FromValues { + function: ValuesToMatrix, + arguments: Vec, + }, + /// The range `a..b`. + Range { + from: Box, + to: Box, + }, + /// A function of a matrix with a matrix result, like `linear(A)`. + OfMatrix { + function: MatrixToMatrix, + matrix: Box, + }, + /// An operation with a matrix result: composition, a value acting on a matrix, sums, translation attached, division, or a power. + BinOp { + lhs: Box, + op: BinaryOp, + rhs: Box, + }, + /// Negation, the identity `+`, or the transpose. + UnaryOp { + expr: Box, + op: UnaryOp, + }, + Piecewise { + cases: Vec>, + otherwise: Option>, + }, +} + +/// One case of a sorted piecewise, whose condition is a value whatever the sort of its cases. +#[derive(Debug)] +pub struct SortedCase { + pub value: T, + pub condition: ValueNode, } diff --git a/libraries/math-parser/src/constants.rs b/libraries/math-parser/src/constants.rs index 49bbeb7220..5d04b39554 100644 --- a/libraries/math-parser/src/constants.rs +++ b/libraries/math-parser/src/constants.rs @@ -1,10 +1,13 @@ use crate::ast::BinaryOp; +use crate::executer::EvalError; +use crate::matrix::{Matrix, Region}; use crate::quaternion::Quaternion; use crate::value::{Complex, Number, Value, complex_divide, complex_log_gamma, part_product, power_of_two_scale}; use num_complex::ComplexFloat; use std::array; use std::cmp::Ordering; use std::f64::consts::{LN_2, PI, TAU}; +use std::ops::RangeInclusive; pub type BuiltinFunction = fn(&[Value]) -> Option; @@ -179,7 +182,7 @@ fn projection(a: Quaternion, b: Quaternion) -> Option { } /// The mean of `count` numbers given as their `N` parts, each part averaged on its own over its [`power_of_two_scale`] so its sum cannot overflow. -fn mean_of(numbers: impl Iterator + Clone, count: usize) -> [f64; N] { +pub(crate) fn mean_of(numbers: impl Iterator + Clone, count: usize) -> [f64; N] { array::from_fn(|index| { let parts = numbers.clone().map(|parts| parts[index]); let scale = power_of_two_scale(parts.clone()); @@ -229,15 +232,6 @@ fn lerp(a: f64, b: f64, t: f64) -> f64 { a + difference * t } -/// The fraction of the way `value` lies from `a` to `b`, halving every operand first (which keeps the ratio) when a difference of finite ones would overflow. -fn inverse_lerp(value: f64, a: f64, b: f64) -> f64 { - let (numerator, denominator) = (value - a, b - a); - if (numerator.is_infinite() || denominator.is_infinite()) && [value, a, b].iter().all(|operand| operand.is_finite()) { - return (value / 2. - a / 2.) / (b / 2. - a / 2.); - } - numerator / denominator -} - /// Computes the greatest common divisor of two nonnegative integers by the Euclidean algorithm. pub fn gcd(a: u128, b: u128) -> u128 { let (mut a, mut b) = (a, b); @@ -366,25 +360,51 @@ pub fn suffixed_function(name: &str) -> Option<(BuiltinFunction, f64)> { } let base = suffix.parse::().ok().filter(|base| base.is_finite())?; - Some((builtin_function(function)?.function, base)) + match builtin_function(function)? { + Builtin::Values { function, .. } => Some((function, base)), + _ => None, + } } -/// A built-in math function and whether it's variadic. -#[derive(Clone, Copy)] -pub struct Builtin { - pub function: BuiltinFunction, - /// Takes any count of arguments, like `min(a, b, c)`, which makes its name usable as a lone reducer token. - pub variadic: bool, +/// A built-in function of a matrix with a value result, like `det`. +pub type MatrixToValue = fn(Matrix) -> Value; +/// A built-in function of a matrix with a matrix result, like `linear`. +pub type MatrixToMatrix = fn(Matrix) -> Matrix; +/// A built-in function building a matrix from values, like `rotation`. +pub type ValuesToMatrix = fn(&[Value]) -> Option; +/// A built-in function of a value and regions with a value result, like `within`. +pub type ValueOfRegions = fn(Value, &[Region]) -> Result; + +/// A built-in math function, by the sorts it takes and gives. Those taking matrices have their argument counts checked as the +/// expression is parsed. +#[derive(Clone)] +pub enum Builtin { + Values { + function: BuiltinFunction, + /// Takes any count of arguments, like `min(a, b, c)`, which makes its name usable as a lone reducer token. + variadic: bool, + }, + OfMatrix(MatrixToValue), + MatrixOfMatrix(MatrixToMatrix), + MatrixOfValues { + function: ValuesToMatrix, + arity: RangeInclusive, + }, + /// A value, then `regions` regions. + OfValueAndRegions { + function: ValueOfRegions, + regions: usize, + }, } /// Defines a built-in function taking a particular count of arguments, or a few like `log(x)` and `log(x, base)`. fn fixed_arity(function: BuiltinFunction) -> Builtin { - Builtin { function, variadic: false } + Builtin::Values { function, variadic: false } } /// Defines a built-in function taking any count of arguments. fn variadic(function: BuiltinFunction) -> Builtin { - Builtin { function, variadic: true } + Builtin::Values { function, variadic: true } } /// Looks up a built-in math function by name, holding a plain function pointer so dispatch avoids hashing and dynamic allocation. @@ -528,17 +548,6 @@ pub fn builtin_function(name: &str) -> Option { x.binary_op(BinaryOp::Sub, quotient.binary_op(BinaryOp::Mul, *modulus)?).map(Value::Number) }), - "clamp" => fixed_arity(|values| { - let [Value::Number(x), Value::Number(min), Value::Number(max)] = values else { return None }; - // The bounds apply in turn, so the upper one wins where they cross - let real_clamp = || { - let at_least = if min.real_ordering(*x)? == Ordering::Greater { min } else { x }; - Some(if max.real_ordering(*at_least)? == Ordering::Less { *max } else { *at_least }) - }; - let quaternion_clamp = || Number::Quaternion(x.to_quaternion().zip(min.to_quaternion(), f64::max).zip(max.to_quaternion(), f64::min)); - Some(Value::Number(real_clamp().unwrap_or_else(quaternion_clamp))) - }), - // Variadic, exact over reals and otherwise part by part "min" => variadic(|values| extremum(values, Ordering::Less).or_else(|| zipping(values, f64::min))), "max" => variadic(|values| extremum(values, Ordering::Greater).or_else(|| zipping(values, f64::max))), @@ -683,11 +692,6 @@ pub fn builtin_function(name: &str) -> Option { a.binary_op(BinaryOp::Add, step).map(Value::Number) }), - "remap" => fixed_arity(|values| { - let [value, in_a, in_b, out_a, out_b] = reals(values)?; - Some(Value::from_f64(lerp(out_a, out_b, inverse_lerp(value, in_a, in_b)))) - }), - // Spherical interpolation between unit quaternions, `a (a⁻¹ b)^t`, along the shorter arc since `q` and `-q` are one rotation "slerp" => fixed_arity(|values| { let [Value::Number(a), Value::Number(b), Value::Number(t)] = values else { return None }; @@ -811,6 +815,150 @@ pub fn builtin_function(name: &str) -> Option { })) }), + // Matrix functions + "det" => Builtin::OfMatrix(|matrix| Value::from_f64(matrix.determinant())), + "linear" => Builtin::MatrixOfMatrix(|matrix| Matrix { + translation: Quaternion::ZERO, + ..matrix + }), + // The image of the origin, `A 0` + "translation" => Builtin::OfMatrix(|matrix| Value::from(matrix.translation)), + + // Left multiplication by the value, `L_q` + "matrix" => Builtin::MatrixOfValues { + arity: 1..=1, + function: |values| { + let [q] = quaternions(values)?; + Some(Matrix::left_multiplication(q)) + }, + }, + + "rotation" => Builtin::MatrixOfValues { + arity: 1..=2, + function: |values| { + let (values, axis) = with_axis(values, 1)?; + let [angle] = reals(values)?; + Some(Matrix::rotation(rotor(angle, axis)?, axis)) + }, + }, + + "scale" => Builtin::MatrixOfValues { + arity: 1..=1, + function: |values| { + let [q] = quaternions(values)?; + Some(Matrix::scale(q)) + }, + }, + + "shear" => Builtin::MatrixOfValues { + arity: 3..=3, + function: |values| { + let [along, by, factor] = values else { return None }; + let [along, by] = quaternions(&[*along, *by])?; + Some(Matrix::shear(along, by, factor.as_real()?)) + }, + }, + + // Range functions treat a region as exactly the points it holds: a range literal's, between its corners on every part, which may be + // infinite, like `within(x, 0..inf)` for `x >= 0`, and any other region's, with a parameter in `0..1` where it extends and 0 elsewhere + "within" => Builtin::OfValueAndRegions { + regions: 1, + function: |p, regions| { + let [region] = regions else { return Err(EvalError::TypeError) }; + let Value::Number(p) = p; + let clamped = clamp_to_region(p, *region)?; + if clamped == p { + return Ok(Value::from_bool(true)); + } + + // A value is within the region when clamping moves it by no more than the tolerance on any part + let tolerance = WITHIN_TOLERANCE * region.scale(); + let moved = clamped.binary_op(BinaryOp::Sub, p).ok_or(EvalError::OperatorTypeError)?; + Ok(Value::from_bool(moved.to_quaternion().parts().iter().all(|part| part.abs() <= tolerance))) + }, + }, + + "clamp" => Builtin::OfValueAndRegions { + regions: 1, + function: |x, regions| { + let [region] = regions else { return Err(EvalError::TypeError) }; + let Value::Number(x) = x; + Ok(Value::Number(clamp_to_region(x, *region)?)) + }, + }, + + // From one range to another, `B A⁻¹ x`, where a flat axis of `A` leaves the parameter undefined + "remap" => Builtin::OfValueAndRegions { + regions: 2, + function: |x, regions| { + let [from, to] = regions else { return Err(EvalError::TypeError) }; + let Value::Number(x) = x; + let RangeParameter { parameter, flat, .. } = range_parameter(from.matrix(), x.to_quaternion())?; + if flat.contains(&true) { + return Err(EvalError::FlatRemapSource); + } + Ok(Value::from(to.matrix().region().apply(parameter))) + }, + }, + _ => return None, }) } + +/// How far outside a region a value may lie and still be within it, as a fraction of the region's scale, so a point that float +/// arithmetic put a hair off an edge or a flat side counts. +const WITHIN_TOLERANCE: f64 = 1e-9; + +/// Clamps a value into a region: on each part between a range literal's corners, ordered exactly for reals so an integer past a +/// matrix's precision keeps its storage, and for any other region on its parameter, `0..1` where it extends and 0 elsewhere, mapped +/// back. A value already within the region is itself. +fn clamp_to_region(x: Number, region: Region) -> Result { + match region { + Region::Range(a, b) if x.as_real().is_some() && a.as_real().is_some() && b.as_real().is_some() => { + let (low, high) = if a.real_ordering(b) == Some(Ordering::Greater) { (b, a) } else { (a, b) }; + Ok(if x.real_ordering(low) == Some(Ordering::Less) { + low + } else if x.real_ordering(high) == Some(Ordering::Greater) { + high + } else { + x + }) + } + Region::Range(a, b) => { + let (a, b, parts) = (a.to_quaternion().parts(), b.to_quaternion().parts(), x.to_quaternion().parts()); + let clamped = array::from_fn(|axis| parts[axis].clamp(a[axis].min(b[axis]), a[axis].max(b[axis]))); + Ok(if clamped == parts { x } else { Number::Quaternion(Quaternion::from_parts(clamped)) }) + } + Region::Map(range) => { + let RangeParameter { parameter, region, extends, .. } = range_parameter(range, x.to_quaternion())?; + let parameter_parts = parameter.parts(); + let clamped = Quaternion::from_parts(array::from_fn(|axis| if extends[axis] { parameter_parts[axis].clamp(0., 1.) } else { 0. })); + Ok(if clamped == parameter { x } else { Number::Quaternion(region.apply(clamped)) }) + } + } +} + +/// Where a value lies against a range: its parameter `R⁻¹ p`, the invertible region that maps the parameter back, and the axes the +/// range extends along, on each other of which the parameter measures how far the value lies off the range. +struct RangeParameter { + parameter: Quaternion, + region: Matrix, + extends: [bool; 4], + /// The spanned axes with no extent. + flat: [bool; 4], +} + +fn range_parameter(range: Matrix, p: Quaternion) -> Result { + if !range.is_finite() { + return Err(EvalError::Indeterminate); + } + + let (region, flat) = range.invertible_region(); + let parameter = region.inverse().ok_or(EvalError::SingularRange)?.apply(p); + if Number::Quaternion(parameter).is_nan() { + return Err(EvalError::Indeterminate); + } + + let extends = array::from_fn(|axis| range.axes[axis] && !flat[axis]); + Ok(RangeParameter { parameter, region, extends, flat }) +} diff --git a/libraries/math-parser/src/context.rs b/libraries/math-parser/src/context.rs index 6804b7468e..c0eb3c6331 100644 --- a/libraries/math-parser/src/context.rs +++ b/libraries/math-parser/src/context.rs @@ -1,3 +1,4 @@ +use crate::matrix::Matrix; use crate::value::Value; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; @@ -5,10 +6,19 @@ use std::ops::{Deref, DerefMut}; //TODO: editor integration, implement these traits for whatever is needed, maybe merge them if needed pub trait ValueProvider { fn get_value(&self, name: &str) -> Option; + + /// The matrix bound to an uppercase-initial name, which the case rule reserves for matrices. + fn get_matrix(&self, _name: &str) -> Option { + None + } } pub trait FunctionProvider { fn run_function(&self, name: &str, args: &[Value]) -> Option; + + /// Whether the host supplies a function of this name, true for every name `run_function` answers. It is read when parsing, since + /// the host's function shadows any builtin of the same name and gives a value where the builtin might give a matrix. + fn provides(&self, name: &str) -> bool; } #[derive(Default)] @@ -20,6 +30,10 @@ impl ValueProvider for &V { fn get_value(&self, name: &str) -> Option { (**self).get_value(name) } + + fn get_matrix(&self, name: &str) -> Option { + (**self).get_matrix(name) + } } impl ValueProvider for NothingMap { @@ -50,6 +64,10 @@ impl FunctionProvider for NothingMap { fn run_function(&self, _: &str, _: &[Value]) -> Option { None } + + fn provides(&self, _: &str) -> bool { + false + } } pub struct EvalContext { @@ -75,6 +93,10 @@ impl EvalContext { self.values.get_value(name) } + pub fn get_matrix(&self, name: &str) -> Option { + self.values.get_matrix(name) + } + pub fn run_function(&self, name: &str, args: &[Value]) -> Option { self.functions.run_function(name, args) } diff --git a/libraries/math-parser/src/executer.rs b/libraries/math-parser/src/executer.rs index cc7308a570..6302b82265 100644 --- a/libraries/math-parser/src/executer.rs +++ b/libraries/math-parser/src/executer.rs @@ -1,7 +1,10 @@ -use crate::ast::{BinaryOp, Literal, Node, UnaryOp}; -use crate::constants::{Builtin, builtin_function, suffixed_function}; +use crate::ast::{BinaryOp, Literal, MatrixNode, Node, SortedCase, UnaryOp, ValueNode}; +use crate::constants::{Builtin, MatrixToValue, ValueOfRegions, builtin_function, suffixed_function}; use crate::context::{EvalContext, FunctionProvider, ValueProvider}; use crate::lexer::Constant; +use crate::matrix::{Matrix, Region}; +use crate::object::Object; +use crate::quaternion::Quaternion; use crate::value::{Number, Value}; use thiserror::Error; @@ -31,6 +34,21 @@ pub enum EvalError { #[error("No piecewise case holds, and there is no `otherwise` case")] NoCaseHolds, + #[error("A singular matrix has no inverse")] + SingularMatrix, + + #[error("A matrix power must be a whole number")] + FractionalMatrixPower, + + #[error("A singular range has no interior")] + SingularRange, + + #[error("Remapping from a flat range is ambiguous, since a value lies at every position along its flat side")] + FlatRemapSource, + + #[error("Only a matrix without translation has a transpose")] + AffineTranspose, + #[error("Value of {0} is not a number")] NotANumber(String), } @@ -47,6 +65,14 @@ fn settle(value: Value) -> Result { Ok(Value::Number(number.canonical())) } +/// Settles a matrix result like [`settle`] does a value, with signed zeros made plain zero. +pub(crate) fn settle_matrix(matrix: Matrix) -> Result { + if matrix.is_nan() { + return Err(EvalError::Indeterminate); + } + Ok(matrix.map(|entry| if entry == 0. { 0. } else { entry })) +} + /// The canonical form of a value the host supplied for `name`, like [`settle`], except that NaN (which only a host can /// supply) is an error naming its source. #[inline(always)] @@ -69,15 +95,99 @@ fn resolve_value(context: &EvalContext(context: &EvalContext, name: &str) -> Option { + let constant = |name: &str| (name == "I").then_some(Matrix::IDENTITY); + + match name.strip_prefix('\\') { + Some(builtin_name) => constant(builtin_name), + None => context.get_matrix(name).or_else(|| constant(name)), + } +} + +/// The case whose condition holds, or `None` where none does: every condition is evaluated and must be a truth value, and +/// at most one may hold, since the cases are unordered. +#[inline(always)] +fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(context: &EvalContext, cases: &'a [SortedCase]) -> Result, EvalError> { + let mut holding = None; + let mut overlapping = false; + for case in cases { + let Value::Number(condition) = case.condition.eval(context)?; + match condition.as_bool() { + Some(false) => {} + Some(true) if holding.is_none() => holding = Some(&case.value), + Some(true) => overlapping = true, + None => return Err(EvalError::NotATruthValue), + } + } + if overlapping { + return Err(EvalError::OverlappingCases); + } + Ok(holding) +} + +/// An operand of a matrix operation, holding a matrix on the stack since the operation consumes it at once. +enum Operand { + Value(Value), + Matrix(Matrix), +} + impl Node { + fn operand(&self, context: &EvalContext) -> Result { + match self { + Node::Value(value) => value.eval(context).map(Operand::Value), + Node::Matrix(matrix) => matrix.eval(context).map(Operand::Matrix), + } + } +} + +/// An operation with a matrix result: a value on the left acts as `L_q`, matrices compose, sums are pointwise or attach a +/// value as translation, division is times-inverse, and powers are whole. +fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand) -> Result { + use BinaryOp as Op; + match (lhs, op, rhs) { + (Operand::Value(Value::Number(q)), Op::Mul, Operand::Matrix(b)) => settle_matrix(Matrix::left_multiplication(q.to_quaternion()).compose(b)), + (Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => settle_matrix(a.compose(b)), + (lhs, Op::Div, Operand::Matrix(b)) => matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse().ok_or(EvalError::SingularMatrix)?)), + (Operand::Matrix(a), Op::Add, Operand::Matrix(b)) => settle_matrix(a + b), + (Operand::Matrix(a), Op::Sub, Operand::Matrix(b)) => settle_matrix(a - b), + (Operand::Matrix(a), Op::Add, Operand::Value(Value::Number(t))) | (Operand::Value(Value::Number(t)), Op::Add, Operand::Matrix(a)) => settle_matrix(a.translated(t.to_quaternion())), + (Operand::Matrix(a), Op::Sub, Operand::Value(Value::Number(t))) => settle_matrix(a.translated(-t.to_quaternion())), + (Operand::Value(Value::Number(t)), Op::Sub, Operand::Matrix(a)) => settle_matrix((-a).translated(t.to_quaternion())), + (Operand::Matrix(a), Op::Pow, Operand::Value(Value::Number(exponent))) => { + // A whole exponent is a composition power, a negative one of the inverse, with an integer read exactly past 2^53 + let whole = match exponent { + Number::Integer(integer) => integer, + real => real + .as_real() + .filter(|real| real.fract() == 0. && real.abs() < i64::MAX as f64) + .ok_or(EvalError::FractionalMatrixPower)? as i64, + }; + settle_matrix(a.power(whole).ok_or(EvalError::SingularMatrix)?) + } + _ => Err(EvalError::OperatorTypeError), + } +} + +impl Node { + #[inline] + pub fn eval(&self, context: &EvalContext) -> Result { + match self { + Node::Value(value) => value.eval(context).map(Object::Value), + Node::Matrix(matrix) => matrix.eval(context).map(Object::from), + } + } +} + +impl ValueNode { pub fn eval(&self, context: &EvalContext) -> Result { match self { - Node::Lit(lit) => match lit { + ValueNode::Lit(lit) => match lit { Literal::Integer(integer) => Ok(Value::from_i64(*integer)), Literal::Float(float) => Ok(Value::from_f64(*float)), }, - Node::BinOp { lhs, op, rhs } => match (lhs.eval(context)?, rhs.eval(context)?) { + ValueNode::BinOp { lhs, op, rhs } => match (lhs.eval(context)?, rhs.eval(context)?) { (Value::Number(lhs), Value::Number(rhs)) => { // Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) { @@ -88,13 +198,13 @@ impl Node { settle(Value::Number(lhs.binary_op(*op, rhs).ok_or(rejected)?)) } }, - Node::UnaryOp { expr, op } => match expr.eval(context)? { + ValueNode::UnaryOp { expr, op } => match expr.eval(context)? { Value::Number(num) => { let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError }; settle(Value::Number(num.unary_op(*op).ok_or(rejected)?)) } }, - Node::Comparison { first, rest } => { + ValueNode::Comparison { first, rest } => { let Value::Number(first) = first.eval(context)?; let rest = rest .iter() @@ -116,11 +226,11 @@ impl Node { }; Ok(Value::from_bool(holds)) } - Node::Var(name) => { + ValueNode::Var(name) => { let value = resolve_value(context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?; canonical_host_value(name, value) } - Node::FnCall { name, expr } => { + ValueNode::FnCall { name, expr } => { // Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call let mut stack_values = [Value::from_i64(0); 5]; let heap_values: Vec; @@ -142,7 +252,7 @@ impl Node { if !prefixed && let Some(value) = context.run_function(bare_name, values) { settle(canonical_host_value(bare_name, value)?) - } else if let Some(Builtin { function, .. }) = builtin_function(bare_name) { + } else if let Some(Builtin::Values { function, .. }) = builtin_function(bare_name) { settle(function(values).ok_or(EvalError::TypeError)?) } else if let Some((function, base)) = suffixed_function(bare_name) { // A base-suffixed call like `log10(x)` runs the two-argument form with the suffix baked in as its second argument @@ -158,39 +268,159 @@ impl Node { Err(EvalError::MissingFunction(name.to_string())) } } - Node::Piecewise { cases, otherwise } => { - // Every condition is evaluated and must be a truth value, and at most one may hold since the cases are unordered - let mut holding = None; - let mut overlapping = false; - for case in cases { - let Value::Number(condition) = case.condition.eval(context)?; - match condition.as_bool() { - Some(false) => {} - Some(true) if holding.is_none() => holding = Some(&case.value), - Some(true) => overlapping = true, - None => return Err(EvalError::NotATruthValue), + // Only the chosen value is evaluated, so an error in any other case's value is never raised + ValueNode::Piecewise { cases, otherwise } => match (holding_case(context, cases)?, otherwise) { + (Some(value), _) => value.eval(context), + (None, Some(otherwise)) => otherwise.eval(context), + (None, None) => Err(EvalError::NoCaseHolds), + }, + ValueNode::Apply { matrix, value } => value_of_matrix(context, MatrixValueCase::Apply(matrix, value)), + ValueNode::OfMatrix { function, matrix } => value_of_matrix(context, MatrixValueCase::OfMatrix(*function, matrix)), + ValueNode::OfValueAndRegions { function, value, regions } => value_of_matrix(context, MatrixValueCase::OfValueAndRegions(*function, value, regions)), + ValueNode::MatrixComparison { matrices, distinct } => value_of_matrix(context, MatrixValueCase::Comparison(matrices, *distinct)), + } + } +} + +/// A value computed from matrices. +enum MatrixValueCase<'a> { + Apply(&'a MatrixNode, &'a ValueNode), + OfMatrix(MatrixToValue, &'a MatrixNode), + OfValueAndRegions(ValueOfRegions, &'a ValueNode, &'a [MatrixNode]), + Comparison(&'a [MatrixNode], bool), +} + +// One function for every value taken from a matrix, called from several sites, since wasm-opt inlines a function with one call site back into the evaluator whatever its attributes say +#[cold] +#[inline(never)] +fn value_of_matrix(context: &EvalContext, case: MatrixValueCase) -> Result { + match case { + MatrixValueCase::Apply(matrix, value) => { + let matrix = matrix.eval(context)?; + let Value::Number(value) = value.eval(context)?; + settle(Value::from(matrix.apply(value.to_quaternion()))) + } + MatrixValueCase::OfMatrix(function, matrix) => settle(function(matrix.eval(context)?)), + MatrixValueCase::OfValueAndRegions(function, value, regions) => { + let value = value.eval(context)?; + + // A range literal is kept by its corners, which may be infinite where no matrix can hold them + let region_of = |region: &MatrixNode| -> Result { + match region { + MatrixNode::Range { from, to } => { + let (Value::Number(from), Value::Number(to)) = (from.eval(context)?, to.eval(context)?); + Ok(Region::Range(from, to)) } + region => region.eval(context).map(Region::Map), } - if overlapping { - return Err(EvalError::OverlappingCases); + }; + + // The range functions take at most two regions as parsed, which land in a stack buffer, while a longer list a host built goes to the heap + let mut stack_regions = [Region::Range(Number::Integer(0), Number::Integer(0)); 2]; + let heap_regions: Vec; + let regions: &[Region] = if regions.len() <= stack_regions.len() { + for (slot, region) in stack_regions.iter_mut().zip(regions) { + *slot = region_of(region)?; + } + &stack_regions[..regions.len()] + } else { + heap_regions = regions.iter().map(region_of).collect::, EvalError>>()?; + &heap_regions + }; + settle(function(value, regions)?) + } + MatrixValueCase::Comparison(matrices, distinct) => { + // A chain lands in a stack buffer when it fits, the usual case + let mut stack_matrices = [Matrix::ZERO; 4]; + let heap_matrices: Vec; + let matrices: &[Matrix] = if matrices.len() <= stack_matrices.len() { + for (slot, matrix) in stack_matrices.iter_mut().zip(matrices) { + *slot = matrix.eval(context)?; + } + &stack_matrices[..matrices.len()] + } else { + heap_matrices = matrices.iter().map(|matrix| matrix.eval(context)).collect::, EvalError>>()?; + &heap_matrices + }; + + let holds = if distinct { + matrices.iter().enumerate().all(|(index, a)| matrices[index + 1..].iter().all(|b| !a.same_entries(*b))) + } else { + matrices.windows(2).all(|pair| pair[0].same_entries(pair[1])) + }; + Ok(Value::from_bool(holds)) + } + } +} + +impl MatrixNode { + pub fn eval(&self, context: &EvalContext) -> Result { + match self { + MatrixNode::Var(name) => { + let matrix = resolve_matrix(context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?; + if matrix.is_nan() { + return Err(EvalError::NotANumber(name.clone())); + } + settle_matrix(matrix) + } + MatrixNode::Literal { entries, by_rows } => { + let mut quaternions = [Quaternion::ZERO; 4]; + if entries.len() > quaternions.len() { + return Err(EvalError::TypeError); + } + for (slot, entry) in quaternions.iter_mut().zip(entries) { + let Value::Number(number) = entry.eval(context)?; + *slot = number.to_quaternion(); } - // Only the chosen value is evaluated, so an error in any other case's value is never raised - match (holding, otherwise) { - (Some(value), _) => value.eval(context), - (None, Some(otherwise)) => otherwise.eval(context), - (None, None) => Err(EvalError::NoCaseHolds), + let entries = &quaternions[..entries.len()]; + let matrix = if *by_rows { Matrix::from_rows(entries) } else { Matrix::from_columns(entries) }; + settle_matrix(matrix.ok_or(EvalError::TypeError)?) + } + MatrixNode::FromValues { function, arguments } => { + // The builders take at most three arguments as parsed, which land in a stack buffer, while a longer list a host built goes to the heap + let mut stack_values = [Value::from_i64(0); 3]; + let heap_values: Vec; + let values: &[Value] = if arguments.len() <= stack_values.len() { + for (slot, argument) in stack_values.iter_mut().zip(arguments) { + *slot = argument.eval(context)?; + } + &stack_values[..arguments.len()] + } else { + heap_values = arguments.iter().map(|argument| argument.eval(context)).collect::, EvalError>>()?; + &heap_values + }; + settle_matrix(function(values).ok_or(EvalError::TypeError)?) + } + MatrixNode::Range { from, to } => { + let (Value::Number(from), Value::Number(to)) = (from.eval(context)?, to.eval(context)?); + settle_matrix(Matrix::range(from.to_quaternion(), to.to_quaternion())) + } + MatrixNode::OfMatrix { function, matrix } => settle_matrix(function(matrix.eval(context)?)), + MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(context)?, *op, rhs.operand(context)?), + MatrixNode::UnaryOp { expr, op } => { + let matrix = expr.eval(context)?; + match op { + UnaryOp::Pos => Ok(matrix), + UnaryOp::Neg => settle_matrix(-matrix), + UnaryOp::Transpose if matrix.is_linear() => settle_matrix(matrix.transposed()), + UnaryOp::Transpose => Err(EvalError::AffineTranspose), + UnaryOp::Not | UnaryOp::Fac | UnaryOp::Magnitude => Err(EvalError::OperatorTypeError), } } + MatrixNode::Piecewise { cases, otherwise } => match (holding_case(context, cases)?, otherwise) { + (Some(matrix), _) => matrix.eval(context), + (None, Some(otherwise)) => otherwise.eval(context), + (None, None) => Err(EvalError::NoCaseHolds), + }, } } } #[cfg(test)] mod tests { - use crate::ast::{BinaryOp, Literal, Node, UnaryOp}; - use crate::context::{EvalContext, NothingMap, ValueProvider}; - use crate::value::Value; + use super::*; + use crate::context::NothingMap; struct SingleValue(f64); @@ -203,9 +433,9 @@ mod tests { #[test] fn known_value_with_one_argument_multiplies() { // `x(2)` juxtaposes like `2(3)` and `i(16)` instead of silently discarding the argument - let call = Node::FnCall { + let call = ValueNode::FnCall { name: "x".to_string(), - expr: vec![Node::Lit(Literal::Float(2.))], + expr: vec![ValueNode::Lit(Literal::Float(2.))], }; let result = call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).unwrap(); assert_eq!(result, Value::from_f64(10.)); @@ -213,9 +443,9 @@ mod tests { #[test] fn known_value_with_multiple_arguments_is_an_error() { - let call = Node::FnCall { + let call = ValueNode::FnCall { name: "x".to_string(), - expr: vec![Node::Lit(Literal::Float(1.)), Node::Lit(Literal::Float(2.))], + expr: vec![ValueNode::Lit(Literal::Float(1.)), ValueNode::Lit(Literal::Float(2.))], }; assert!(call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).is_err()); } @@ -233,38 +463,38 @@ mod tests { } eval_tests! { - test_addition: Value::from_f64(7.) => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Float(3.))), + test_addition: Value::from_f64(7.) => ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Float(3.))), op: BinaryOp::Add, - rhs: Box::new(Node::Lit(Literal::Float(4.))), + rhs: Box::new(ValueNode::Lit(Literal::Float(4.))), }, - test_subtraction: Value::from_f64(1.) => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Float(5.))), + test_subtraction: Value::from_f64(1.) => ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Float(5.))), op: BinaryOp::Sub, - rhs: Box::new(Node::Lit(Literal::Float(4.))), + rhs: Box::new(ValueNode::Lit(Literal::Float(4.))), }, - test_multiplication: Value::from_f64(12.) => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Float(3.))), + test_multiplication: Value::from_f64(12.) => ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Float(3.))), op: BinaryOp::Mul, - rhs: Box::new(Node::Lit(Literal::Float(4.))), + rhs: Box::new(ValueNode::Lit(Literal::Float(4.))), }, - test_division: Value::from_f64(2.5) => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Float(5.))), + test_division: Value::from_f64(2.5) => ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Float(5.))), op: BinaryOp::Div, - rhs: Box::new(Node::Lit(Literal::Float(2.))), + rhs: Box::new(ValueNode::Lit(Literal::Float(2.))), }, - test_negation: Value::from_f64(-3.) => Node::UnaryOp { - expr: Box::new(Node::Lit(Literal::Float(3.))), + test_negation: Value::from_f64(-3.) => ValueNode::UnaryOp { + expr: Box::new(ValueNode::Lit(Literal::Float(3.))), op: UnaryOp::Neg, }, - test_sqrt: Value::from_f64(2.) => Node::FnCall { + test_sqrt: Value::from_f64(2.) => ValueNode::FnCall { name: "sqrt".to_string(), - expr: vec![Node::Lit(Literal::Float(4.))], + expr: vec![ValueNode::Lit(Literal::Float(4.))], + }, + test_power: Value::from_f64(8.) => ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Float(2.))), + op: BinaryOp::Pow, + rhs: Box::new(ValueNode::Lit(Literal::Float(3.))), }, - test_power: Value::from_f64(8.) => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Float(2.))), - op: BinaryOp::Pow, - rhs: Box::new(Node::Lit(Literal::Float(3.))), - }, } } diff --git a/libraries/math-parser/src/lexer.rs b/libraries/math-parser/src/lexer.rs index 8ea573e5ed..7138ea1a76 100644 --- a/libraries/math-parser/src/lexer.rs +++ b/libraries/math-parser/src/lexer.rs @@ -25,7 +25,12 @@ pub enum Token<'src> { RParen, LBrace, RBrace, + LBracket, + RBracket, + Semicolon, Comma, + /// The range `a..b`. + DotDot, Plus, Minus, /// Reserved for percentages, so the parser never matches it and its error points a C-style remainder to `mod(a, b)`. @@ -33,6 +38,8 @@ pub enum Token<'src> { Star, Slash, Caret, + /// The postfix transpose `^T`, one token since no power by a matrix is valid. + Transpose, Lt, Le, @@ -67,13 +74,18 @@ impl<'src> fmt::Display for Token<'src> { Token::RParen => f.write_str(")"), Token::LBrace => f.write_str("{"), Token::RBrace => f.write_str("}"), + Token::LBracket => f.write_str("["), + Token::RBracket => f.write_str("]"), + Token::Semicolon => f.write_str(";"), Token::Comma => f.write_str(","), + Token::DotDot => f.write_str(".."), Token::Plus => f.write_str("+"), Token::Minus => f.write_str("-"), Token::Percent => f.write_str("%"), Token::Star => f.write_str("*"), Token::Slash => f.write_str("/"), Token::Caret => f.write_str("^"), + Token::Transpose => f.write_str("^T"), Token::Lt => f.write_str("<"), Token::Le => f.write_str("<="), @@ -183,9 +195,19 @@ fn keyword(word: &str) -> Option> { } } -/// Whether a character ends an operand: a name, a number, a closing parenthesis or brace, or the `∞` literal. +/// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix. +#[inline] +pub fn names_matrix(name: &str) -> bool { + let name = name.strip_prefix('\\').unwrap_or(name); + match name.as_bytes().first() { + Some(byte) if byte.is_ascii() => byte.is_ascii_uppercase(), + _ => name.starts_with(char::is_uppercase), + } +} + +/// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, or the `∞` literal. fn ends_operand(c: char) -> bool { - c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | '∞') + c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞') } /// Reads every `|` in the source up front, since each depends on what precedes it: a bar opens a magnitude where an operand @@ -226,6 +248,8 @@ fn classify_bars(input: &str) -> Vec<(usize, Bar)> { } // Whitespace changes nothing, and neither does `!`, a postfix factorial after an operand or a prefix not before one c if c.is_whitespace() || c == '!' => {} + // The range `..` is an operator, unlike a number's decimal point + '.' if chars.next_if(|(_, next)| *next == '.').is_some() => after_operand = false, // A name ends an operand, but a keyword like `if` comes before one c if c == '\\' || unicode_ident::is_xid_start(c) => { let mut end = position + c.len_utf8(); @@ -314,6 +338,11 @@ impl<'a> Lexer<'a> { fn follows_operand(&self, literal_start: usize) -> bool { let mut preceding = self.input[..literal_start].trim_end(); + // A range's `..` set apart by whitespace is an operator, while `1...5` stays ambiguous + if preceding.ends_with("..") && preceding.len() < literal_start { + return false; + } + // A `!` run is postfix factorial only when an operand precedes it, otherwise it's a prefix logical not while let Some(rest) = preceding.strip_suffix('!') { preceding = rest.trim_end(); @@ -331,27 +360,28 @@ impl<'a> Lexer<'a> { let mut got_digit = int_digits > 0; let mut plain_integer = true; - if self.peek() == Some('.') { + // A decimal point belongs to the number unless it begins a range's `..` + if self.peek() == Some('.') && !self.input[self.pos..].starts_with("..") { self.bump(); plain_integer = false; got_digit |= self.consume_digits().0 > 0; } - if got_digit && matches!(self.peek(), Some('e' | 'E')) { + // The `e` of scientific notation needs a digit after it or after its sign, and otherwise names Euler's number + let after_exponent_sign = self.input[self.pos..].strip_prefix(['e', 'E']).map(|rest| rest.strip_prefix(['+', '-']).unwrap_or(rest)); + if got_digit && after_exponent_sign.is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) { self.bump(); plain_integer = false; if matches!(self.peek(), Some('+' | '-')) { self.bump(); } - if self.consume_digits().0 == 0 { - self.pos = start_pos; - return None; - } + self.consume_digits(); } - // A numeric literal cannot be glued directly to another by a stray decimal point or digit (e.g. `1..5`, `1.5.5`), so reject rather than letting it parse as implicit multiplication + // A numeric literal cannot be glued directly to another by a stray decimal point or digit (e.g. `1.5.5`, `1.5 5`), so reject rather than letting it parse as implicit multiplication let leading_dot = self.input[start_pos..].starts_with('.'); - if !got_digit || self.peek().is_some_and(|c| c == '.' || c.is_ascii_digit()) || self.follows_number_literal(start_pos) || (leading_dot && self.follows_operand(start_pos)) { + let glued = self.peek().is_some_and(|c| c == '.' || c.is_ascii_digit()) && !self.input[self.pos..].starts_with(".."); + if !got_digit || glued || self.follows_number_literal(start_pos) || (leading_dot && self.follows_operand(start_pos)) { self.pos = start_pos; return None; } @@ -426,14 +456,31 @@ impl<'a> Lexer<'a> { ')' => RParen, '{' => LBrace, '}' => RBrace, + '[' => LBracket, + ']' => RBracket, + ';' => Semicolon, ',' => Comma, '+' => Plus, '-' => Minus, '*' => Star, '%' => Percent, '/' => Slash, - '^' => Caret, + // `^T` is the transpose where the `T` stands alone, spaces between or not + '^' => { + let rest = &self.input[self.pos..]; + let after_spaces = rest.trim_start(); + if after_spaces.starts_with('T') && !after_spaces[1..].starts_with(unicode_ident::is_xid_continue) { + self.pos += rest.len() - after_spaces.len() + 1; + Transpose + } else { + Caret + } + } '≠' => Neq, + '.' if self.peek() == Some('.') => { + self.bump(); + DotDot + } // A symbol can't be a name, so unlike `inf`, no binding can shadow `∞` '∞' => Float(f64::INFINITY), diff --git a/libraries/math-parser/src/lib.rs b/libraries/math-parser/src/lib.rs index 1632fdcc0a..b025a1ad1d 100644 --- a/libraries/math-parser/src/lib.rs +++ b/libraries/math-parser/src/lib.rs @@ -3,17 +3,20 @@ pub mod constants; pub mod context; pub mod executer; pub mod lexer; +pub mod matrix; +pub mod object; pub mod parser; pub mod quaternion; pub mod reducer; +pub mod sort; pub mod value; use context::EvalContext; use executer::EvalError; +use object::Object; use parser::ParseError; -use value::Value; -pub fn evaluate(expression: &str) -> Result, ParseError> { +pub fn evaluate(expression: &str) -> Result, ParseError> { let expr = ast::Node::try_parse_from_str(expression); let context = EvalContext::default(); expr.map(|node| node.eval(&context)) @@ -22,19 +25,35 @@ pub fn evaluate(expression: &str) -> Result, ParseError #[cfg(test)] mod tests { use super::*; + use matrix::{Affine2, Linear2, Matrix}; use quaternion::Quaternion; - use value::{Complex, Number, Rung, Vector1, Vector2, Vector3, Weighted}; + use value::{Complex, Number, Rung, Value, Vector1, Vector2, Vector3, Weighted}; const EPSILON: f64 = 1e-10_f64; #[test] fn malformed_juxtaposed_numbers_fail_to_parse() { // Two numbers cannot be glued together by a stray decimal point (they must not parse as implicit multiplication) - for input in ["1..5", "1.5.5", "1..", ".5.5"] { + for input in ["1.5.5", "1..", ".5.5", "1...5"] { assert!(evaluate(input).is_err(), "expected `{input}` to be a parse error"); } } + #[test] + fn a_number_before_euler_multiplies_unless_an_exponent_follows() { + // The `e` of scientific notation needs a digit after it or after its sign, so `2e` reaches Euler's number like `2pi` reaches pi + let real = |input: &str| evaluate(input).unwrap().unwrap().as_real().unwrap(); + let e = std::f64::consts::E; + assert_eq!(real("2e"), 2. * e); + assert_eq!(real("2e^2"), 2. * e * e); + assert_eq!(real("2e - 1"), 2. * e - 1.); + assert_eq!(real("2e-pi"), 2. * e - std::f64::consts::PI); + assert_eq!(real("2exp(1)"), 2. * e); + assert_eq!(real("2e-1"), 0.2); + assert_eq!(real("2E+1"), 20.); + assert_eq!(real("2.5e3"), 2500.); + } + #[test] fn unrecognized_characters_fail_to_parse() { // Unrecognized trailing input must be rejected rather than silently dropped after a valid prefix @@ -263,6 +282,8 @@ mod tests { fn display_writes_the_nonzero_parts_with_their_bases() { for (input, expected) in [ ("sqrt(-4)", "2i"), + ("sqrt(-1)", "i"), + ("1 - i", "1-i"), ("1 - 2i", "1-2i"), ("(1 + i) / 2", "0.5+0.5i"), ("2i + 3j", "2i+3j"), @@ -292,7 +313,7 @@ mod tests { ("(-1+227i)!", Complex::new(-1.4098280082608946e-157, -2.309687847859193e-156)), ("(-1.5+300i)!", Complex::new(-9.760049091627542e-208, 1.5632983579858933e-207)), ] { - let Value::Number(actual) = evaluate(input).unwrap().unwrap(); + let Value::Number(actual) = evaluate(input).unwrap().unwrap().into_value().unwrap(); let actual = actual.as_complex().unwrap(); assert!((actual - expected).norm() / expected.norm() < 1e-12, "`{input}`: expected {expected}, got {actual}"); } @@ -316,7 +337,7 @@ mod tests { ("choose(-0.5, 5000)", Complex::from(0.007978646139382154), 1e-10), ("choose(1.5 + 2i, 5000)", Complex::new(-2.541871408941716e-8, -8.84744846043224e-9), 1e-10), ] { - let Value::Number(actual) = evaluate(input).unwrap().unwrap(); + let Value::Number(actual) = evaluate(input).unwrap().unwrap().into_value().unwrap(); let actual = actual.as_complex().unwrap(); assert!((actual - expected).norm() / expected.norm() < tolerance, "`{input}`: expected {expected}, got {actual}"); } @@ -331,7 +352,7 @@ mod tests { ("(3 + 4i) / (1 + 2i)", Complex::new(2.2, -0.4)), ("harmmean(i, 1)", Complex::new(1., 1.)), ] { - assert_eq!(evaluate(input).unwrap().unwrap(), Value::from(expected), "`{input}`"); + assert_eq!(evaluate(input).unwrap().unwrap(), Object::from(expected), "`{input}`"); } } @@ -341,7 +362,7 @@ mod tests { for (input, expected) in [("choose(2.5, 2)", 1.875), ("pick(2.5, 2)", 3.75), ("choose(-0.5, 2)", 0.375)] { assert_eq!(evaluate(input).unwrap().unwrap().as_real(), Some(expected), "`{input}`"); } - assert_eq!(evaluate("choose(i, 2)").unwrap().unwrap(), Value::from(Complex::new(-0.5, -0.5))); + assert_eq!(evaluate("choose(i, 2)").unwrap().unwrap(), Object::from(Complex::new(-0.5, -0.5))); } #[test] @@ -360,6 +381,9 @@ mod tests { fn run_function(&self, name: &str, _: &[Value]) -> Option { (name == "f").then(|| Value::from_f64(f64::NAN)) } + fn provides(&self, name: &str) -> bool { + name == "f" + } } let eval = |source: &str| ast::Node::try_parse_from_str(source).unwrap().eval(&EvalContext::new(Host, Host)); @@ -399,8 +423,6 @@ mod tests { ("rms(1e-320)", 1e-320), ("lerp(-1e308, 1e308, 0.5)", 0.), ("lerp(-1e308, 1e308, 1)", 1e308), - ("remap(0, -1e308, 1e308, 0, 1)", 0.5), - ("remap(0.5, 0, 1, -1e308, 1e308)", 0.), ] { assert_eq!(evaluate(input).unwrap().unwrap().as_real(), Some(expected), "`{input}`"); } @@ -410,7 +432,7 @@ mod tests { assert!(!matches!(evaluate(input), Ok(Ok(value)) if value.as_real().is_some_and(f64::is_finite)), "`{input}`"); // Each part averages over its own scale, so a small part beside huge ones keeps its precision - let Value::Number(mean) = evaluate("mean(1e308, 1e308, j)").unwrap().unwrap(); + let Value::Number(mean) = evaluate("mean(1e308, 1e308, j)").unwrap().unwrap().into_value().unwrap(); assert_eq!(mean.to_quaternion().y, 1. / 3.); } @@ -476,6 +498,9 @@ mod tests { fn run_function(&self, name: &str, args: &[Value]) -> Option { (name == "sin").then(|| Value::from_f64(2. * args[0].as_real().unwrap())) } + fn provides(&self, name: &str) -> bool { + name == "sin" + } } let eval = |source: &str| { ast::Node::try_parse_from_str(source) @@ -489,6 +514,31 @@ mod tests { assert_eq!(eval("\\sin(pi / 2)"), Some(1.)); } + #[test] + fn host_functions_shadow_matrix_builtins_when_parsing() { + // A host function gives a value, so a host parsing with its functions reads a call of that name as one, not the builtin + struct Halving; + impl context::FunctionProvider for Halving { + fn run_function(&self, name: &str, args: &[Value]) -> Option { + (name == "clamp").then(|| Value::from_f64(args[0].as_real().unwrap_or_default() / 2.)) + } + fn provides(&self, name: &str) -> bool { + name == "clamp" + } + } + let eval = |source: &str| { + ast::Node::try_parse_with_functions(source, &Halving) + .unwrap() + .eval(&EvalContext::new(context::NothingMap, Halving)) + .unwrap() + .as_real() + }; + + assert_eq!(eval("clamp(8)"), Some(4.)); + assert_eq!(eval("\\clamp(8, 0..5)"), Some(5.)); + assert!(ast::Node::try_parse_from_str("clamp(8)").is_err(), "without the host, `clamp` is the builtin"); + } + #[test] fn rename_identifiers_is_token_exact() { let a_to_x = |name: &str| name.eq_ignore_ascii_case("a").then(|| "x".to_string()); @@ -535,27 +585,33 @@ mod tests { assert_eq!(value.as_real(), Some(1. / 9.)); } - fn run_end_to_end_test(input: &str, expected_value: Value) { + fn run_end_to_end_test(input: &str, expected: Object) { let expr = match ast::Node::try_parse_from_str(input) { Ok(expr) => expr, Err(err) => panic!("failed to parse `{input}`: {err}"), }; let context = EvalContext::default(); - let actual_value = match expr.eval(&context) { + let actual = match expr.eval(&context) { Ok(v) => v, Err(err) => panic!("failed to evaluate `{input}` because of error {err}"), }; - // Storage is never observable, so the comparison reads both values by their four parts, with infinities matched exactly - let (Value::Number(actual), Value::Number(expected)) = (actual_value, expected_value); - let (actual, expected) = (actual.to_quaternion().parts(), expected.to_quaternion().parts()); - for ((actual, expected), basis) in actual.into_iter().zip(expected).zip(["1", "i", "j", "k"]) { + // Storage is never observable, so a value compares by its four parts and a matrix by its twenty entries, with infinities matched exactly + let entries = |object: &Object| match object { + Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(), + Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect::>(), + }; + assert!(actual.as_matrix().is_some() == expected.as_matrix().is_some(), "`{input}`: expected {expected}, got {actual}"); + if let (Some(actual), Some(expected)) = (actual.as_matrix(), expected.as_matrix()) { + assert_eq!(actual.axes, expected.axes, "`{input}`: the axes the matrix acts on"); + } + for (index, (actual, expected)) in entries(&actual).into_iter().zip(entries(&expected)).enumerate() { if actual.is_infinite() || expected.is_infinite() { - assert!(actual == expected, "`{input}` → `{basis}` part: expected {expected:?}, got {actual:?}"); + assert!(actual == expected, "`{input}` → part {index}: expected {expected:?}, got {actual:?}"); } else { let difference = (actual - expected).abs(); - assert!(difference < EPSILON, "`{input}` → `{basis}` part: expected {expected}, got {actual}, Δ={difference}"); + assert!(difference < EPSILON, "`{input}` → part {index}: expected {expected}, got {actual}, Δ={difference}"); } } } @@ -734,6 +790,11 @@ mod tests { logical_not_one: "!1" => 0., logical_not_expression: "!(2 - 2)" => 1., + // NOT binds as tightly as a sign, before a product, a comparison, or `&&` + logical_not_before_product: "!0 * 0" => 0., + logical_not_before_comparison: "!0 < 5" => 1., + logical_not_before_and: "!0 && 0" => 0., + // Log / exp / pow / root log_ln: "ln(e)" => 1., log_log10: "log(100)" => 2., @@ -837,7 +898,7 @@ mod tests { statistics_rms_quaternion: "rms(3j, 4k)" => 12.5_f64.sqrt(), logical_xor_odd_parity: "xor(1, 1, 1)" => 1., logical_xor_even_parity: "xor(1, 0, 1)" => 0., - mapping_remap: "remap(5, 0, 10, 0, 100)" => 50., + mapping_remap: "remap(5, 0..10, 0..100)" => 50., // GCD / LCM gcd_simple: "gcd(24, 18)" => 6., @@ -1158,7 +1219,7 @@ mod tests { quaternion_floor_componentwise: "floor(1.5i + 2.5j)" => Quaternion::new(0., 1., 2., 0.), quaternion_snap_componentwise: "snap(0.4 + 1.6j - 2.8k, 2)" => Quaternion::new(0., 0., 2., -2.), quaternion_min_componentwise: "min(1 + 5j, 3 + 2j)" => Quaternion::new(1., 0., 2., 0.), - quaternion_clamp_componentwise: "clamp(5i - 5j, -i - j, i + j)" => Quaternion::new(0., 1., -1., 0.), + quaternion_clamp_componentwise: "clamp(5i - 5j, (-i - j)..(i + j))" => Quaternion::new(0., 1., -1., 0.), quaternion_lerp: "lerp(2i, 4j, 0.5)" => Quaternion::new(0., 1., 2., 0.), quaternion_mean_pointwise: "mean(2i, 4j)" => Quaternion::new(0., 1., 2., 0.), quaternion_abs_per_part: "abs(-1 - 2i + 3j - 4k)" => Quaternion::new(1., 2., 3., 4.), @@ -1167,7 +1228,7 @@ mod tests { // A real is a quaternion with zero vector parts, so as a bound it holds a vector's parts to zero quaternion_max_with_zero: "max(2i - 3j, 0)" => Complex::new(0., 2.), quaternion_max_with_real: "max(0.5i + 2j, 1)" => Quaternion::new(1., 0.5, 2., 0.), - quaternion_clamp_by_reals: "clamp(3i, 1, 2)" => 1., + quaternion_clamp_moves_other_parts_into_the_range: "clamp(3 + 3i, 1..2)" => 2., // Vector functions: the dot product spans all four parts, the cross product only the vector parts vector_dot: "dot(3i + 4j, i)" => 3., @@ -1220,6 +1281,283 @@ mod tests { vector_project_infinite: "project(inf i, i)" => Complex::new(0., f64::INFINITY), vector_project_onto_infinite: "project(i, inf i)" => Complex::new(0., 1.), vector_reject_infinite: "reject(inf i, j)" => Complex::new(0., f64::INFINITY), + + // Matrix literals build rows or columns, landing on the rung their count names + matrix_identity_literal: "[1;i;j;k]" => Matrix::IDENTITY, + matrix_short_rows_pad: "[i;j]" => Matrix::from_rows(&[Quaternion::I, Quaternion::J]).unwrap(), + matrix_one_row_is_the_weight: "[3i + 4j]" => Matrix::from_rows(&[Quaternion::new(0., 3., 4., 0.)]).unwrap(), + matrix_columns_transpose_rows: "[1,i]" => Matrix::from_columns(&[Quaternion::ONE, Quaternion::I]).unwrap(), + matrix_swizzle: "[k;j;i] (1i + 2j + 3k)" => Quaternion::new(0., 3., 2., 1.), + matrix_real_part: "[1] (3 + 4i)" => 3., + matrix_coefficient: "[j] (1i + 2j + 3k)" => 2., + matrix_argand_shuffle: "[1;i] (3 + 4i)" => Quaternion::new(0., 3., 4., 0.), + matrix_argand_shuffle_inverse: "[i;j;0;0] (3i + 4j)" => Complex::new(3., 4.), + matrix_splat: "[1;1] 5" => Quaternion::new(0., 5., 5., 0.), + matrix_positional_construction: "[3;4] 1" => Quaternion::new(0., 3., 4., 0.), + matrix_scaled_pick: "[1;i;2j;-k] (1 + 2i + 3j + 4k)" => Quaternion::new(1., 2., 6., -4.), + matrix_projection: "[i;j;0] (1i + 2j + 3k)" => Quaternion::new(0., 1., 2., 0.), + matrix_dot_product: "[3i + 4j] (i + j)" => 7., + matrix_columns_apply: "[j, i] (3i + 4j)" => Quaternion::new(0., 4., 3., 0.), + matrix_skew_literal: "[i + 0.5j, j] i" => Quaternion::new(0., 1., 0.5, 0.), + + // Products: a matrix applies to a value and composes with a matrix, and a value on the left acts as `L_q` + matrix_composition: "[i;j] [j;i] (i + 2j)" => Quaternion::new(0., 2., 1., 0.), + matrix_scaled_by_value: "(2 I) (3i)" => Complex::new(0., 6.), + matrix_left_multiplication: "(i I) j" => Quaternion::K, + matrix_implicit_scalar: "2[i;j] (i + j)" => Quaternion::new(0., 2., 2., 0.), + matrix_call_syntax_applies: "I(3i)" => Complex::new(0., 3.), + matrix_zero_entry_beside_infinity: "[1] (inf i)" => 0., + matrix_infinite_part_passes: "[i] (inf i)" => f64::INFINITY, + + // A matrix applies to the whole product after it, unless parentheses give it one factor + matrix_applies_to_rest_of_product: "[1;i] 2 i" => Quaternion::new(0., 0., 2., 0.), + matrix_applies_to_parenthesized_factor: "([1;i] 2) i" => -2., + matrix_scales_rest_of_product: "scale(3) 2 i" => Complex::new(0., 6.), + matrix_applies_through_matrix: "(scale(3) 2 scale(5)) i" => Complex::new(0., 30.), + matrix_dot_of_product: "[1] 3i conj(2i)" => 6., + matrix_over_value_then_factor: "scale(3) / 2 i" => Complex::new(0., 1.5), + matrix_applies_before_division: "(I + 4i) 2i / 2" => Complex::new(0., 5.), + value_before_matrix_in_product: "2 [1;i] 3" => Complex::new(0., 6.), + value_over_matrix_then_factor: "2 / I 3" => 6., + matrix_over_matrix_then_value: "I / [1;i;j;k] (2i)" => Complex::new(0., 2.), + + // A product of values alone folds left whatever its length + product_folds_left: "8 / 2 / 2" => 2., + product_alternates_operators: "2 * 3 / 4 * 5" => 7.5, + product_within_sums: "2 * 3 * 4 - 5 * 6 / 3" => 14., + + // Sums attach a translation, which `A 0` reads back + matrix_translation: "(I + 5i + 4j) 0" => Quaternion::new(0., 5., 4., 0.), + matrix_translation_first: "(5i + I + 4j) 0" => Quaternion::new(0., 5., 4., 0.), + matrix_translation_subtracted: "(I - 2(-2.5i - 2j)) 0" => Quaternion::new(0., 5., 4., 0.), + matrix_linear_part: "(I + 5i) - (I + 5i) 0" => Matrix::IDENTITY, + matrix_translation_function: "translation(I + 5i)" => Complex::new(0., 5.), + matrix_linear_function: "linear(I + 5i)" => Matrix::IDENTITY, + matrix_pointwise_sum: "I + I" => Matrix::linear([Quaternion::new(2., 0., 0., 0.), Quaternion::new(0., 2., 0., 0.), Quaternion::new(0., 0., 2., 0.), Quaternion::new(0., 0., 0., 2.)]), + matrix_pointwise_difference: "I - I" => Matrix::ZERO, + matrix_value_minus_matrix: "(5i - I) 0" => Complex::new(0., 5.), + matrix_affine_composition: "((I + i) (I + j)) 0" => Quaternion::new(0., 1., 1., 0.), + + // Division is times-inverse on every sort, and whole powers compose + matrix_inverse_application: "[1;2i;3j;k]^-1 (2i + 3j)" => Quaternion::new(0., 1., 1., 0.), + matrix_square: "[1;2i;3j;k]^2 (i + j)" => Quaternion::new(0., 4., 9., 0.), + matrix_zeroth_power: "[1;2i;3j;k]^0" => Matrix::IDENTITY, + matrix_over_matrix: "(I + 5i) / (I + 5i)" => Matrix::IDENTITY, + matrix_over_value: "I / 2" => 0.5, + value_over_matrix: "(2 / I) 3" => 6., + matrix_transpose: "[1;i]^T" => Matrix::from_columns(&[Quaternion::ONE, Quaternion::I]).unwrap(), + matrix_transpose_spaced: "[1;i] ^ T" => Matrix::from_columns(&[Quaternion::ONE, Quaternion::I]).unwrap(), + matrix_transpose_then_inverse: "[1;2i;3j;k]^T^-1 (2i + 3j)" => Quaternion::new(0., 1., 1., 0.), + matrix_determinant: "det([1;2i;3j;k])" => 6., + matrix_determinant_of_padded_literal: "det([2i;3j])" => 0., + matrix_determinant_of_left_multiplication: "det(matrix(3 + 4i))" => 625., + + // Builders + matrix_of_value_multiplies: "matrix(1 + i) (2 + j)" => Quaternion::new(2., 2., 1., 1.), + matrix_rotation: "rotation(pi/2) i" => Quaternion::J, + matrix_rotation_about_axis: "rotation(pi/2, i) j" => Quaternion::K, + matrix_rotation_keeps_weight: "rotation(pi) (1 + i)" => Complex::new(1., -1.), + matrix_rotation_matches_rotate: "rotation(1, i + j) (2i + 3k) - rotate(2i + 3k, 1, i + j)" => 0., + matrix_uniform_scale: "scale(2) (1 + i + j)" => Quaternion::new(1., 2., 2., 0.), + matrix_componentwise_product: "scale(3i + 2j) (5i + 7j)" => Quaternion::new(0., 15., 14., 0.), + matrix_componentwise_quotient: "scale(3i + 2j + k)^-1 (6i + 4j)" => Quaternion::new(0., 2., 2., 0.), + matrix_shear: "shear(i, j, 0.5) (2j)" => Quaternion::new(0., 1., 2., 0.), + matrix_shear_infinite: "shear(i, j, inf) (2j)" => Quaternion::new(0., f64::INFINITY, 2., 0.), + matrix_shear_infinite_leaves_other_axes: "shear(i, j, inf) i" => Complex::new(0., 1.), + + // Inverses scale their entries first, so a huge or tiny map inverts, and a whole power reads its exponent exactly + matrix_inverse_of_huge_scale: "scale(1e103)^-1 (1e103 i)" => Complex::new(0., 1.), + matrix_inverse_of_tiny_scale: "scale(1e-110)^-1 (1e-110 i)" => Complex::new(0., 1.), + matrix_power_past_exact_reals: "(-I)^(2^53 + 1) i" => Complex::new(0., -1.), + + // A map keeps the axes it acts on through its linear part and a real scale factor + matrix_linear_keeps_axes: "linear((i + j)..(3i + 3j))" => Matrix::range(Quaternion::ZERO, Quaternion::new(0., 2., 2., 0.)), + linear_part_of_range_keeps_its_axes: "within(0.5 + i, linear(0..(2i + 2j)))" => 0., + within_scaled_range: "within(1.5, 2 (0..1))" => 1., + scaled_range_keeps_its_axes: "within(1.5 + 0.5i, 2 (0..1))" => 0., + outside_left_multiplication: "within(3, matrix(2))" => 0., + + // Comparisons are pointwise, a piecewise may take matrix values, and `\I` reaches the identity past any binding + matrix_equality: "I == [1;i;j;k]" => 1., + matrix_inequality: "I != [i;j]" => 1., + matrix_equality_chain: "I == [1;i;j;k] == I" => 1., + matrix_distinct_chain: "I != [i;j] != [1]" => 1., + matrix_in_piecewise: "{I if 1, [i;j] otherwise} k" => Quaternion::K, + matrix_builtin_identity_prefix: "\\I k" => Quaternion::K, + + // A range sends parameter 0 to its first corner and 1 to its second on the parts the corners have, leaving the others untouched + range_application: "(0..10) 0.5" => 5., + range_reversed: "(10..0) 0.25" => 7.5, + range_reaches_past_products: "(0..2pi) 0.5" => std::f64::consts::PI, + range_unit_is_identity: "0..1 == I" => 1., + range_normalization: "(2..4)^-1 (3)" => 0.5, + range_leaves_other_parts: "(0..10) (0.5 + 3i)" => Complex::new(5., 3.), + box_scales_its_axes: "(0..(3i + 4j)) (0.5i + 0.5j)" => Quaternion::new(0., 1.5, 2., 0.), + box_leaves_the_weight: "(0..(3i + 4j)) (1 + 0.5i)" => Complex::new(1., 1.5), + box_from_a_corner: "((2i + 2j)..(4i + 6j)) (0.5i + 0.5j)" => Quaternion::new(0., 3., 4., 0.), + box_over_every_axis: "(0..(5 + 6i + 7j + 8k)) (1 + i + j + k)" => Quaternion::new(5., 6., 7., 8.), + box_parameter_is_per_axis: "(0..(5 + 6i + 7j + 8k)) 1" => 5., + range_composes_with_a_rotation: "(rotation(pi/2) (0..(2i + 2j))) (i + j)" => Quaternion::new(0., -2., 2., 0.), + range_shifted_by_a_translation: "((0..(i + j)) + 5i) (i + j)" => Quaternion::new(0., 6., 1., 0.), + + // Membership, clamping, and remapping read the range's parameter on the axes it spans, boundary included + within_range: "within(0.5, 0..1)" => 1., + within_range_boundary: "within(1, 0..1)" => 1., + outside_range: "within(1.5, 0..1)" => 0., + outside_range_off_its_axis: "within(0.5 + 7i, 0..1)" => 0., + within_box: "within(2i + 3j, 0..(4i + 4j))" => 1., + outside_box_on_one_axis: "within(2i + 5j, 0..(4i + 4j))" => 0., + outside_box_off_its_axes: "within(9 + 2i + 3j, 0..(4i + 4j))" => 0., + within_rotated_box: "within(0.1i + 0.5j, rotation(pi/4) (0..(i + j)))" => 1., + outside_rotated_box: "within(0.9i + 0.5j, rotation(pi/4) (0..(i + j)))" => 0., + within_parallelogram: "within(2i + j, [2i, i + j] + i)" => 1., + outside_parallelogram: "within(i + j, [2i, i + j] + i)" => 0., + clamp_to_range: "clamp(1.5, 0..1)" => 1., + clamp_within_range: "clamp(0.25, 0..1)" => 0.25, + clamp_moves_other_parts_into_the_range: "clamp(-3 + 7i, 0..1)" => 0., + clamp_to_box: "clamp(2i + 3j, 0..(i + j))" => Quaternion::new(0., 1., 1., 0.), + clamp_within_box: "clamp(0.5i, 0..(i + j))" => Complex::new(0., 0.5), + clamp_to_rotated_box: "clamp(2i, rotation(pi/2) (0..(i + j)))" => 0., + remap_between_ranges: "remap(0.25i + 0.5j, 0..(i + j), 0..(2i + 4j))" => Quaternion::new(0., 0.5, 2., 0.), + remap_reversing: "remap(2, 0..10, 100..0)" => 80., + remap_extrapolates: "remap(3, 0..2, 0..1)" => 1.5, + remap_passes_uncovered_parts: "remap(0.5 + 3i, 0..1, 0..10)" => Complex::new(5., 3.), + remap_to_infinity: "remap(0.5, 0..1, inf..inf)" => f64::INFINITY, + within_huge_box: "within(5e200 i, 0..(1e201 i + 1e201 j + 1e201 k))" => 1., + within_tiny_box: "within(5e-111 i, 0..(1e-110 i + 1e-110 j + 1e-110 k))" => 1., + remap_from_huge_box: "remap(5e200 i, 0..(1e201 i + 1e201 j + 1e201 k), 0..(i + j + k))" => Complex::new(0., 0.5), + } + + #[test] + fn range_syntax() { + // A range's corners are values, a range is a matrix, and a range cannot chain + let message = |input: &str| evaluate(input).unwrap_err().to_string(); + assert_eq!(message("I..1"), "A matrix stands where a value is needed"); + assert_eq!(message("sin(0..1)"), "A matrix stands where a value is needed"); + assert_eq!(message("within(0..1, 0..1)"), "A matrix stands where a value is needed"); + assert_eq!(message("within(1, 2)"), "A value stands where a matrix is needed"); + assert_eq!(message("0..1 < 2"), "The operator has no meaning for a matrix"); + assert!(evaluate("0..1..2").is_err()); + + // A number's decimal point still lexes beside a range, and whitespace around `..` is free + assert_eq!(evaluate("(1.5..2.5) 0.5").unwrap().unwrap().as_real(), Some(2.)); + assert_eq!(evaluate("(1 .. 3) 0.5").unwrap().unwrap().as_real(), Some(2.)); + assert_eq!(evaluate("(0 .. .5) 1").unwrap().unwrap().as_real(), Some(0.5)); + assert_eq!(evaluate("(-1..1) 0.75").unwrap().unwrap().as_real(), Some(0.5)); + + // A flat range holds only its one value on the flat axis, while remapping from it has no parameter to carry + let within = |input: &str| evaluate(input).unwrap().unwrap().as_bool(); + assert_eq!(within("within(5, 5..5)"), Some(true)); + assert_eq!(within("within(4, 5..5)"), Some(false)); + assert_eq!(within("within(0, 0..0)"), Some(true)); + assert_eq!(evaluate("clamp(1, 3..3)").unwrap().unwrap().as_real(), Some(3.)); + assert_eq!(evaluate("(5..5) 0.5").unwrap().unwrap().as_real(), Some(5.)); + assert!(matches!(evaluate("remap(2, 2..2, 0..10)").unwrap(), Err(EvalError::FlatRemapSource))); + assert!(matches!(evaluate("remap(0.5i + 0.5k, 0..(i + k), 0..(2i + 2j + 2k))").unwrap(), Err(EvalError::FlatRemapSource))); + assert!(matches!(evaluate("within(1, [i, 2i])").unwrap(), Err(EvalError::SingularRange))); + + // Matrix builtins check their argument counts as the expression is parsed + for input in [ + "within(1)", + "clamp(1, 0..1, 0..1)", + "remap(1, 0..1)", + "rotation()", + "rotation(1, k, 2)", + "shear(i, j)", + "scale()", + "matrix(1, 2)", + ] { + assert_eq!(evaluate(input).unwrap_err().to_string(), "Invalid arguments for function call", "`{input}`"); + } + + // A range literal's corners bound it directly, so they may be infinite, while other regions with infinite entries have no inverse + assert_eq!(within("within(5i, 0..(inf i))"), Some(true)); + assert_eq!(within("within(-5i, 0..(inf i))"), Some(false)); + assert_eq!(within("within(1e300, 0..inf)"), Some(true)); + assert_eq!(within("within(-1, 0..inf)"), Some(false)); + assert_eq!(within("within(inf, 0..inf)"), Some(true)); + assert_eq!(within("within(-7, -inf..inf)"), Some(true)); + assert_eq!(evaluate("clamp(-3, 0..inf)").unwrap().unwrap().as_real(), Some(0.)); + assert_eq!(evaluate("clamp(5, 0..inf)").unwrap().unwrap().as_real(), Some(5.)); + assert_eq!(evaluate("clamp(5, -inf..0)").unwrap().unwrap().as_real(), Some(0.)); + assert_eq!(evaluate("clamp(0.3, 0.1..0.2)").unwrap().unwrap().as_real(), Some(0.2)); + assert!(matches!(evaluate("within(1, 2 (0..inf))").unwrap(), Err(EvalError::Indeterminate))); + assert!(matches!(evaluate("remap(1, 0..inf, 0..1)").unwrap(), Err(EvalError::Indeterminate))); + + // A box spans its corners' rung, so a part they share is flat and admits only their value there + assert_eq!(within("within(0.5i + 0.5k, 0..(i + k))"), Some(true)); + assert_eq!(within("within(0.5i + 3j + 0.5k, 0..(i + k))"), Some(false)); + assert_eq!(within("within(0.5i + 2j, (2j)..(i + 2j))"), Some(true)); + assert_eq!(within("within(0.5i + 3j, (2j)..(i + 2j))"), Some(false)); + assert_eq!(within("within(0.5 + 0.5k, 0..(1 + i + k))"), Some(true)); + assert_eq!(within("within(0.5 + 0.5j + 0.5k, 0..(1 + i + k))"), Some(false)); + assert_eq!(within("within(0.5i + 0.5k, rotation(pi/2) (0..(i + k)))"), Some(false)); + assert_eq!(within("within(-0.5i + 0.5j + 5k, rotation(pi/2) (0..(i + j)) + 5k)"), Some(true)); + assert_eq!(within("within(-0.5i + 0.5j + 4k, rotation(pi/2) (0..(i + j)) + 5k)"), Some(false)); + assert_eq!(evaluate("clamp(0.5i + 3j + 0.5k, 0..(i + k))").unwrap().unwrap(), Object::from(Quaternion::new(0., 0.5, 0., 0.5))); + assert_eq!(within("within(1.5i + 2j, scale(3i + 2j))"), Some(true)); + assert_eq!(within("within(1.5i + 2j + k, scale(3i + 2j))"), Some(false)); + + // A box holds only the points between its corners on every part, so a part neither corner has must be 0, and a box whose + // height shrinks to nothing holds just the points on its base + assert_eq!(within("within(2i, 0..1)"), Some(false)); + assert_eq!(within("within(2i, I)"), Some(false)); + assert_eq!(within("within(0.5 + 0.5i + 0.5j + 0.5k, I)"), Some(true)); + assert_eq!(within("within(0.5i, 0..1i)"), Some(true)); + assert_eq!(within("within(0.5i + 3j, 0..1i)"), Some(false)); + assert_eq!(within("within(2i, 0..(3i + 0j))"), Some(true)); + assert_eq!(within("within(2i + 5j, 0..(3i + 0j))"), Some(false)); + assert_eq!(within("within(2i + 5j, 0..(3i + 1e-300j))"), Some(false)); + assert_eq!(evaluate("clamp(2i + 5j, 0..3i)").unwrap().unwrap(), Object::from(Complex::new(0., 2.))); + + // A region's parameters are its inner map's, so an outer map or a translation adds no axes to a box + assert_eq!(within("within(0.5, I (0..1))"), Some(true)); + assert_eq!(within("within(2i, I (0..1))"), Some(false)); + assert_eq!(within("within(0.5i + 0.5j, scale(2) (0..(i + j)))"), Some(true)); + assert_eq!(within("within(0.5i + 0.5j + 0.5k, scale(2) (0..(i + j)))"), Some(false)); + assert_eq!(within("within(0.5i + 0.5j + 5k, (0..(i + j)) + 5k)"), Some(true)); + assert_eq!(within("within(0.5i + 0.5j + 5.5k, (0..(i + j)) + 5k)"), Some(false)); + assert_eq!(within("within(0.5i - 0.5j + 0.5k, rotation(pi/2, i) (0..(i + j)))"), Some(false)); + assert_eq!( + evaluate("clamp(0.5i + 0.5j + 5k, scale(2) (0..(i + j)))").unwrap().unwrap(), + Object::from(Quaternion::new(0., 0.5, 0.5, 0.)) + ); + + // A range reads as a Transform when its corners leave the weight and `z` alone + let affine = |input: &str| evaluate(input).unwrap().unwrap().into_matrix().unwrap().as_affine2(); + assert_eq!( + affine("(i + j)..(3i + 4j)"), + Some(Affine2 { + linear: Linear2([[2., 0.], [0., 3.]]), + translation: [1., 1.] + }) + ); + assert_eq!(affine("0..10"), None); + } + + #[test] + fn within_tolerates_a_hair_of_float_error() { + let within = |input: &str| evaluate(input).unwrap().unwrap().as_bool(); + + // A point a billionth of the region's scale off an edge or a flat side is within, and one further off is not + assert_eq!(within("within(1 + 1e-12, 0..1)"), Some(true)); + assert_eq!(within("within(-1e-12, 0..1)"), Some(true)); + assert_eq!(within("within(1 + 1e-7, 0..1)"), Some(false)); + assert_eq!(within("within(1e4 + 1e-6, 0..1e4)"), Some(true)); + assert_eq!(within("within(0.5i + 1e-12 j, 0..(i + k))"), Some(true)); + assert_eq!(within("within(0.5i + 1e-6 j, 0..(i + k))"), Some(false)); + assert_eq!(within("within(1.5i + 2j + 1e-12 k, scale(3i + 2j))"), Some(true)); + assert_eq!(within("within(1.5i + 2j + 1e-6 k, scale(3i + 2j))"), Some(false)); + + // So a point computed onto a rotated region's edge, or a rotated point landing beside a flat side, counts + assert_eq!(within("within(0.5i + 0.5j, rotation(pi/4))"), Some(true)); + assert_eq!(within("within(rotate(i, pi), (-i)..0)"), Some(true)); + + // The scale is the corners' or the map's magnitude, so a region at the origin with no extent is exact + assert_eq!(within("within(1e16 + 1e6, 0..1e16)"), Some(true)); + assert_eq!(within("within(1e16 + 1e8, 0..1e16)"), Some(false)); + assert_eq!(within("within(1e-300, 0..0)"), Some(false)); + assert_eq!(within("within(-1e-20, 0..inf)"), Some(false)); } #[test] @@ -1277,7 +1615,7 @@ mod tests { #[test] fn vector_queries_require_the_other_parts_to_be_zero() { - let value = |source: &str| evaluate(source).unwrap().unwrap(); + let value = |source: &str| evaluate(source).unwrap().unwrap().into_value().unwrap(); // A query succeeds exactly when the parts outside its rung are zero, so a real is a particle but not a vector assert_eq!(value("3i + 4j").as_vector2(), Some(Vector2([3., 4.]))); @@ -1308,7 +1646,14 @@ mod tests { } } } - let eval = |source: &str| ast::Node::try_parse_from_str(source).unwrap().eval(&EvalContext::new(VectorBindings, context::NothingMap)).unwrap(); + let eval = |source: &str| { + ast::Node::try_parse_from_str(source) + .unwrap() + .eval(&EvalContext::new(VectorBindings, context::NothingMap)) + .unwrap() + .into_value() + .unwrap() + }; // A bound vector takes part in the algebra like any literal, and the result queries back at its rung assert_eq!(eval("|v|").as_real(), Some(5.)); @@ -1378,7 +1723,7 @@ mod tests { // Selection and rounding return the integer itself, and a literal spelled as a real is the same whole number assert_eq!(evaluate_i64("max(2^53 + 1, 2^53)"), Some((1_i64 << 53) + 1)); assert_eq!(evaluate_i64("min(2^53 + 1, 2^53 + 2)"), Some((1_i64 << 53) + 1)); - assert_eq!(evaluate_i64("clamp(2^53 + 1, 0, 2^60)"), Some((1_i64 << 53) + 1)); + assert_eq!(evaluate_i64("clamp(2^53 + 1, 0..2^60)"), Some((1_i64 << 53) + 1)); assert_eq!(evaluate_i64("floor(2^53 + 1)"), Some((1_i64 << 53) + 1)); assert_eq!(evaluate_i64("snap(2^53 + 1, 1)"), Some((1_i64 << 53) + 1)); assert_eq!(evaluate_i64("snap(2^60 + 3, 2)"), Some((1_i64 << 60) + 4)); @@ -1393,8 +1738,12 @@ mod tests { assert_eq!(evaluate_i64("gcd(2^126, 6)"), Some(2)); assert!(evaluate("gcd(2^127, 2)").unwrap().is_err()); - // Crossed bounds settle on the upper one - assert_eq!(evaluate_i64("clamp(5, 10, 0)"), Some(0)); + // A reversed range clamps to its own ends, and the ends order exactly past the reals' limit + assert_eq!(evaluate_i64("clamp(15, 10..0)"), Some(10)); + assert_eq!(evaluate_i64("clamp(-5, 10..0)"), Some(0)); + assert_eq!(evaluate_i64("clamp(2^53 + 1, 0..2^53)"), Some(1 << 53)); + assert_eq!(evaluate_i64("clamp(2^53 + 1, 0..(2^53 + 2))"), Some((1 << 53) + 1)); + assert_eq!(evaluate_i64("clamp(-2^53 - 1, (-2^53)..0)"), Some(-(1 << 53))); // A fractional quotient, a power, and a factorial past integer storage continue in the reals assert_eq!(evaluate("7 / 2").unwrap().unwrap().as_real(), Some(3.5)); @@ -1426,9 +1775,124 @@ mod tests { assert_eq!(nan.binary_op(ast::BinaryOp::Geq, Number::Integer(0)), Some(Number::from_bool(false))); } + #[test] + fn matrix_sort_errors() { + // Sorts are fixed by spelling, so a matrix or a value standing where the other belongs fails the parse + let message = |input: &str| evaluate(input).unwrap_err().to_string(); + for input in ["[I]", "sin(I)", "max(I, 1)", "I + [I]", "{1 if I, 0 otherwise}"] { + assert_eq!(message(input), "A matrix stands where a value is needed", "`{input}`"); + } + for input in ["2^T", "det(1)"] { + assert_eq!(message(input), "A value stands where a matrix is needed", "`{input}`"); + } + // Matrices have no order, magnitude, factorial, or logic, and compare only with matrices + for input in ["I < I", "|I|", "I!", "!I", "I && 1", "I == 1", "I^I", "1^I", "I < 1 < 2"] { + assert_eq!(message(input), "The operator has no meaning for a matrix", "`{input}`"); + } + assert_eq!(message("{I if 1, 2 otherwise}"), "A piecewise's cases must all be values or all be matrices"); + assert_eq!(message("I(1, 2)"), "Invalid arguments for function call"); + + // A fractional power, the inverse of a padded literal (whose zero rows make it singular), and the transpose of a translated matrix fail at evaluation + for input in ["I^0.5", "I^inf", "I^i"] { + let error = evaluate(input).unwrap().unwrap_err(); + assert_eq!(error.to_string(), "A matrix power must be a whole number", "`{input}`"); + } + for input in ["[i;j]^-1", "I / [i;j]", "[i;j]^-2"] { + assert!(matches!(evaluate(input).unwrap(), Err(EvalError::SingularMatrix)), "expected `{input}` to be singular"); + } + assert!(matches!(evaluate("(I + 5i)^T").unwrap(), Err(EvalError::AffineTranspose))); + assert!(matches!(evaluate("M").unwrap(), Err(EvalError::MissingValue(name)) if name == "M")); + } + + #[test] + fn matrix_literal_syntax_errors() { + for input in ["[]", "[1; i, j]", "[1 2]", "[1;]", "[;1]", "[1,]"] { + assert!(evaluate(input).is_err(), "expected `{input}` to be a parse error"); + } + + let error = evaluate("[1;i;j;k;1]").unwrap_err().to_string(); + assert!(error.starts_with("A matrix literal has at most four entries"), "{error}"); + } + + #[test] + fn matrices_bind_and_query_by_case() { + struct Bindings; + impl context::ValueProvider for Bindings { + fn get_value(&self, name: &str) -> Option { + (name == "x").then(|| Value::from_f64(2.)) + } + fn get_matrix(&self, name: &str) -> Option { + match name { + // A shear with a translation, as a host's `DAffine2` binds + "X" => Some(Matrix::from(Affine2 { + linear: Linear2([[1., 0.], [0.5, 1.]]), + translation: [5., 4.], + })), + // A binding shadows the identity like any constant + "I" => Some(Matrix::ZERO), + "N" => Some(Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN))), + _ => None, + } + } + } + let eval = |source: &str| ast::Node::try_parse_from_str(source).unwrap().eval(&EvalContext::new(Bindings, context::NothingMap)); + + // A NaN from a host matrix is an error naming its source, like a NaN value + assert!(matches!(eval("N"), Err(EvalError::NotANumber(name)) if name == "N")); + assert!(matches!(eval("N i"), Err(EvalError::NotANumber(name)) if name == "N")); + + // `X` maps the plane, leaving the weight and `z` untouched + assert_eq!(eval("X (2i + 2j)").unwrap(), Object::from(Quaternion::new(0., 8., 6., 0.))); + assert_eq!(eval("X (1 + k)").unwrap(), Object::from(Quaternion::new(1., 5., 4., 1.))); + assert_eq!(eval("x X 0").unwrap(), Object::from(Quaternion::new(0., 10., 8., 0.))); + assert_eq!(eval("I").unwrap(), Object::from(Matrix::ZERO)); + assert_eq!(eval("\\I").unwrap(), Object::from(Matrix::IDENTITY)); + assert!(matches!(eval("Y"), Err(EvalError::MissingValue(name)) if name == "Y")); + + // A query checks its refinement losslessly: the weight untouched for all, `z` untouched for the plane, no translation for a linear map + let x = eval("X").unwrap().into_matrix().unwrap(); + assert_eq!( + x.as_affine2(), + Some(Affine2 { + linear: Linear2([[1., 0.], [0.5, 1.]]), + translation: [5., 4.] + }) + ); + assert_eq!(x.as_linear2(), None); + assert_eq!(x.as_affine3().map(|affine| affine.translation), Some([5., 4., 0.])); + assert_eq!(eval("linear(X)").unwrap().into_matrix().unwrap().as_linear2(), Some(Linear2([[1., 0.], [0.5, 1.]]))); + let rotation = eval("rotation(1, i)").unwrap().into_matrix().unwrap(); + assert_eq!(rotation.as_affine2(), None); + assert!(rotation.as_linear3().is_some()); + assert_eq!(eval("[1;i]").unwrap().into_matrix().unwrap().as_affine3(), None); + + // A matrix is no value to the value readers + assert_eq!(eval("X").unwrap().as_real(), None); + } + + #[test] + fn matrices_display_as_row_literals() { + for (input, expected) in [ + ("I", "[1;i;j;k]"), + ("[i;j]", "[i;j]"), + ("[3i + 4j]", "[3i+4j]"), + ("[1;i]^T", "[i;j;0;0]"), + ("-I", "[-1;-i;-j;-k]"), + ("I - I", "[0]"), + ("I + 5i", "[1;i;j;k] + 5i"), + ("I - 5i", "[1;i;j;k] + (-5i)"), + ("I + 5i + 4j", "[1;i;j;k] + (5i+4j)"), + ("I + i", "[1;i;j;k] + i"), + ("2..4", "[2;i;j;k] + 2"), + ("0..(3i + 4j)", "[1;3i;4j;k]"), + ] { + assert_eq!(evaluate(input).unwrap().unwrap().to_string(), expected, "`{input}`"); + } + } + #[test] fn minimal_rungs_follow_content() { - let rung = |source: &str| evaluate(source).unwrap().unwrap().rung(); + let rung = |source: &str| evaluate(source).unwrap().unwrap().as_value().unwrap().rung(); // The rung is decided by the value rather than by how it was computed or stored assert_eq!(rung("1 < 2"), Rung::Bool); diff --git a/libraries/math-parser/src/matrix.rs b/libraries/math-parser/src/matrix.rs new file mode 100644 index 0000000000..fe2277214b --- /dev/null +++ b/libraries/math-parser/src/matrix.rs @@ -0,0 +1,570 @@ +use crate::constants::mean_of; +use crate::quaternion::Quaternion; +use crate::value::{Number, part_product, power_of_two_scale}; +use std::fmt; +use std::ops::{Add, Neg, Sub}; + +/// An affine map of quaternion space, `p -> M p + c`: four rows over the parts `w, x, y, z` and a translation. Matrices are the +/// language's second sort beside values, holding every map from a swizzle to a Graphite transform, a Linear one with zero translation. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Matrix { + /// Each row weights the input's parts into one output part, so the row `i` in the `x` slot passes the input's `x` through. + pub rows: [Quaternion; 4], + pub translation: Quaternion, + /// The parameter parts the map spans as a region, which `within` and `clamp` bound by `0..1` while holding the rest at 0: a range's + /// rung, a literal's count, a composition's inner map's, or every part a builtin touches. + pub axes: [bool; 4], +} + +const ZERO: Quaternion = Quaternion::ZERO; +const ALL_AXES: [bool; 4] = [true; 4]; + +impl Matrix { + pub const IDENTITY: Self = Self::linear([Quaternion::ONE, Quaternion::I, Quaternion::J, Quaternion::K]); + pub const ZERO: Self = Self::linear([ZERO; 4]); + + pub const fn linear(rows: [Quaternion; 4]) -> Self { + Self { + rows, + translation: ZERO, + axes: ALL_AXES, + } + } + + /// The row literal `[a;b;c]`, whose rows land on the parts of the rung their count names: `w` alone, `x, y`, `x, y, z`, or all four. + pub fn from_rows(rows: &[Quaternion]) -> Option { + let (rows, axes) = match *rows { + [a] => ([a, ZERO, ZERO, ZERO], [true, false, false, false]), + [a, b] => ([ZERO, a, b, ZERO], [false, true, true, false]), + [a, b, c] => ([ZERO, a, b, c], [false, true, true, true]), + [a, b, c, d] => ([a, b, c, d], ALL_AXES), + _ => return None, + }; + Some(Self { axes, ..Self::linear(rows) }) + } + + /// The column literal `[a,b,c]`, whose columns are the images of the basis directions of the rung their count names. + pub fn from_columns(columns: &[Quaternion]) -> Option { + Some(Self::from_rows(columns)?.transposed()) + } + + /// The range `a..b`: on each part of the corners' join rung, the map sending parameter `0` to `a` and `1` to `b`, so vector corners + /// make a box, with the other parts untouched. A part the corners share is flat, so `0..(i + k)` is the square where `j` is 0. + pub fn range(a: Quaternion, b: Quaternion) -> Self { + let axes = Self::range_axes(a, b); + let (a, b) = (a.parts(), b.parts()); + + let mut range = Self { axes, ..Self::IDENTITY }; + let mut translation = [0.; 4]; + for (axis, spanned) in axes.into_iter().enumerate() { + if spanned { + let mut row = [0.; 4]; + // Equal corners are flat even at infinity, where their difference is NaN + row[axis] = if a[axis] == b[axis] { 0. } else { b[axis] - a[axis] }; + range.rows[axis] = Quaternion::from_parts(row); + translation[axis] = a[axis]; + } + } + range.translation = Quaternion::from_parts(translation); + range + } + + /// The axes a range spans, its corners' join rung: the weight if either corner has one, and the vector parts up to the last either + /// has, with `0..0` a range of the weight. + fn range_axes(a: Quaternion, b: Quaternion) -> [bool; 4] { + let (a, b) = (a.parts(), b.parts()); + let has_part = |axis: usize| a[axis] != 0. || b[axis] != 0.; + let last_vector_axis = (1..4).rev().find(|&axis| has_part(axis)); + std::array::from_fn(|axis| match axis { + 0 => has_part(0) || last_vector_axis.is_none(), + _ => last_vector_axis.is_some_and(|last| axis <= last), + }) + } + + /// The image of one parameter axis, a column of the linear part. + fn column(self, axis: usize) -> [f64; 4] { + self.rows.map(|row| row.parts()[axis]) + } + + fn with_column(mut self, axis: usize, column: [f64; 4]) -> Self { + for (row, entry) in self.rows.iter_mut().zip(column) { + let mut parts = row.parts(); + parts[axis] = entry; + *row = Quaternion::from_parts(parts); + } + self + } + + /// The map as a region, where each parameter axis it leaves unspanned and unused passes its own part through, so a padded literal + /// like `[u, v]` leaves the parts off its parallelogram alone. + pub fn region(self) -> Self { + (0..4) + .filter(|&axis| !self.axes[axis] && self.column(axis) == [0.; 4]) + .fold(self, |region, axis| region.with_column(axis, unit(axis))) + } + + /// The region with every parameter axis it leaves unused given a direction off the others, its own where it can, so it inverts + /// unless singular for another reason, and which spanned axes were flat. A point lies on the region only at a parameter of 0 there. + pub fn invertible_region(self) -> (Self, [bool; 4]) { + let used = |axis: usize| self.column(axis) != [0.; 4]; + let flat = std::array::from_fn(|axis| self.axes[axis] && !used(axis)); + + // An orthonormal basis of the region's extent, which each unused axis extends with the basis direction furthest from it + let mut extent = [[0.; 4]; 4]; + let mut extent_count = 0; + for axis in (0..4).filter(|&axis| used(axis)) { + if let Some((direction, _)) = orthogonal_part(self.column(axis), &extent[..extent_count]) { + extent[extent_count] = direction; + extent_count += 1; + } + } + let mut region = self; + for axis in (0..4).filter(|&axis| !used(axis)) { + let candidates = std::iter::once(axis).chain((0..4).filter(|&index| index != axis)); + let furthest = candidates + .filter_map(|index| orthogonal_part(unit(index), &extent[..extent_count])) + .reduce(|furthest, candidate| if candidate.1 > furthest.1 { candidate } else { furthest }); + if let Some((direction, _)) = furthest { + region = region.with_column(axis, direction); + extent[extent_count] = direction; + extent_count += 1; + } + } + + (region, flat) + } + + /// Whether the translation is zero, leaving a linear map. + pub fn is_linear(self) -> bool { + self.translation == ZERO + } + + /// Whether the two maps agree entry for entry, whatever axes each was built to act on. + pub fn same_entries(self, other: Self) -> bool { + self.rows == other.rows && self.translation == other.translation + } + + /// The linear part with its rows and columns swapped, keeping the translation. + pub fn transposed(self) -> Self { + let entries = self.entries(); + Self { + rows: std::array::from_fn(|row| Quaternion::from_parts(std::array::from_fn(|column| entries[column][row]))), + ..self + } + } + + /// The map with the translation `t` added. + pub fn translated(self, t: Quaternion) -> Self { + Self { + translation: self.translation + t, + ..self + } + } + + /// The parts a value has, as the axes a map built from it acts on. + fn axes_of(q: Quaternion) -> [bool; 4] { + q.parts().map(|part| part != 0.) + } + + fn entries(self) -> [[f64; 4]; 4] { + self.rows.map(Quaternion::parts) + } + + /// The image of `p`, `M p + c`. + pub fn apply(self, p: Quaternion) -> Quaternion { + Quaternion::from_parts(self.rows.map(|row| inner(row, p))) + self.translation + } + + /// The composition `self ∘ other`, applying `other` first: `(M₁ M₂, M₁ c₂ + c₁)`. Its parameters are those of `other`, so it spans + /// `other`'s axes, as a rotated box spans the box's. + pub fn compose(self, other: Self) -> Self { + let rows = self.rows.map(|row| { + let weights = row.parts(); + let mut combined = ZERO; + for (weight, other_row) in weights.into_iter().zip(other.rows) { + combined = combined + other_row.map(|entry| part_product(weight, entry, false)); + } + combined + }); + let translation = Quaternion::from_parts(self.rows.map(|row| inner(row, other.translation))) + self.translation; + Self { rows, translation, axes: other.axes } + } + + /// The determinant of the linear part. + pub fn determinant(self) -> f64 { + let entries = self.entries(); + (0..4).map(|column| cofactor(entries, 0, column) * entries[0][column]).sum() + } + + /// The inverse map, or `None` for a singular one: `(M⁻¹, -M⁻¹ c)`. + pub fn inverse(self) -> Option { + // Rows then columns are divided by powers of two near their largest entries, which is exact, so the cofactors of huge or tiny + // entries stay in range, then the scales are divided back out + let mut entries = self.entries(); + let row_scales = entries.map(|row| power_of_two_scale(row.into_iter())); + for (row, scale) in entries.iter_mut().zip(row_scales) { + *row = row.map(|entry| entry / scale); + } + let column_scales: [f64; 4] = std::array::from_fn(|column| power_of_two_scale(entries.iter().map(|row| row[column]))); + for row in entries.iter_mut() { + *row = std::array::from_fn(|column| row[column] / column_scales[column]); + } + + let determinant: f64 = (0..4).map(|column| cofactor(entries, 0, column) * entries[0][column]).sum(); + if determinant == 0. { + return None; + } + + // The adjugate over the determinant, whose entries are the transposed cofactors + let rows = std::array::from_fn(|row| Quaternion::from_parts(std::array::from_fn(|column| cofactor(entries, column, row) / determinant / column_scales[row] / row_scales[column]))); + let linear = Self::linear(rows); + Some(Self { + rows, + translation: -Quaternion::from_parts(linear.rows.map(|row| inner(row, self.translation))), + ..self + }) + } + + /// The composition power `A^n`, with a negative power composing the inverse, or `None` for a negative power of a singular map. + pub fn power(self, exponent: i64) -> Option { + let mut base = if exponent < 0 { self.inverse()? } else { self }; + let mut remaining = exponent.unsigned_abs(); + let mut result = Self { axes: self.axes, ..Self::IDENTITY }; + while remaining > 0 { + if remaining & 1 == 1 { + result = result.compose(base); + } + remaining >>= 1; + if remaining > 0 { + base = base.compose(base); + } + } + Some(result) + } + + /// Left multiplication by `q` as a matrix, `L_q p = q p`, the value's own action in the matrix sort. + pub fn left_multiplication(q: Quaternion) -> Self { + let Quaternion { w, x, y, z } = q; + Self::linear([Quaternion::new(w, -x, -y, -z), Quaternion::new(x, w, -z, y), Quaternion::new(y, z, w, -x), Quaternion::new(z, -y, x, w)]) + } + + /// The rotation a unit rotor performs about `axis`, leaving the weight alone, with the axes it does not turn kept exact. + pub fn rotation(rotor: Quaternion, axis: Quaternion) -> Self { + let Quaternion { w, x, y, z } = rotor; + let [_, along_x, along_y, along_z] = Self::axes_of(axis); + Self { + // The plane of rotation, all of space unless the axis is a basis direction, whose own part stays put + axes: [false, along_y || along_z, along_x || along_z, along_x || along_y], + ..Self::linear([ + Quaternion::ONE, + Quaternion::new(0., 1. - 2. * (y * y + z * z), 2. * (x * y - w * z), 2. * (x * z + w * y)), + Quaternion::new(0., 2. * (x * y + w * z), 1. - 2. * (x * x + z * z), 2. * (y * z - w * x)), + Quaternion::new(0., 2. * (x * z - w * y), 2. * (y * z + w * x), 1. - 2. * (x * x + y * y)), + ]) + } + } + + /// Scales each axis by the weight plus that axis's part of `q`, so a real scales uniformly, leaving the weight alone. + pub fn scale(q: Quaternion) -> Self { + Self { + axes: [false, true, true, true], + ..Self::linear([ + Quaternion::ONE, + Quaternion::new(0., q.w + q.x, 0., 0.), + Quaternion::new(0., 0., q.w + q.y, 0.), + Quaternion::new(0., 0., 0., q.w + q.z), + ]) + } + } + + /// Displaces the `along` coordinate by `factor` times the `by` coordinate: the identity plus `factor` times their outer product. + pub fn shear(along: Quaternion, by: Quaternion, factor: f64) -> Self { + let mut matrix = Self { + axes: joined(Self::axes_of(along), Self::axes_of(by)), + ..Self::IDENTITY + }; + for (row, along) in matrix.rows.iter_mut().zip(along.parts()) { + *row = *row + by.map(|by| part_product(part_product(factor, along, false), by, false)); + } + matrix + } + + /// The pointwise mean, each entry averaged on its own scale as the mean of values is, so huge entries cannot overflow the sum. + pub fn mean(matrices: &[Self]) -> Option { + let count = matrices.len(); + if count == 0 { + return None; + } + + Some(Self { + rows: std::array::from_fn(|row| Quaternion::from_parts(mean_of(matrices.iter().map(|matrix| matrix.rows[row].parts()), count))), + translation: Quaternion::from_parts(mean_of(matrices.iter().map(|matrix| matrix.translation.parts()), count)), + axes: matrices.iter().fold([false; 4], |axes, matrix| joined(axes, matrix.axes)), + }) + } + + /// Applies a function to every entry, the translation included. + pub fn map(self, function: impl Fn(f64) -> f64) -> Self { + Self { + rows: self.rows.map(|row| row.map(&function)), + translation: self.translation.map(&function), + ..self + } + } + + /// Whether any entry is NaN, which no operation may produce. + pub fn is_nan(self) -> bool { + self.rows.iter().chain([&self.translation]).any(|row| row.parts().iter().any(|part| part.is_nan())) + } + + /// Whether every entry is finite, as an inverse needs to be exact rather than dividing by infinity into zeros. + pub fn is_finite(self) -> bool { + self.rows.iter().chain([&self.translation]).all(|row| row.parts().iter().all(|part| part.is_finite())) + } + + /// Whether the weight passes through untouched and never leaks into position, as in every Graphite transform. + fn is_geometric(self) -> bool { + self.rows[0] == Quaternion::ONE && self.rows[1..].iter().all(|row| row.w == 0.) && self.translation.w == 0. + } + + /// Whether `z` passes through untouched, as in a map of the plane. + fn is_planar(self) -> bool { + self.rows[3] == Quaternion::K && self.rows[..3].iter().all(|row| row.z == 0.) && self.translation.z == 0. + } + + /// Reads the matrix as a map of space, or `None` if it touches the weight. + pub fn as_affine3(self) -> Option { + let [_, x, y, z] = self.rows; + self.is_geometric().then_some(Affine3 { + linear: Linear3([[x.x, y.x, z.x], [x.y, y.y, z.y], [x.z, y.z, z.z]]), + translation: [self.translation.x, self.translation.y, self.translation.z], + }) + } + + /// Reads the matrix as a linear map of space, or `None` if it touches the weight or has a translation. + pub fn as_linear3(self) -> Option { + self.is_linear().then(|| self.as_affine3()).flatten().map(|affine| affine.linear) + } + + /// Reads the matrix as a map of the plane, or `None` if it touches the weight or `z`. + pub fn as_affine2(self) -> Option { + let Affine3 { + linear: Linear3([[a, c, _], [b, d, _], _]), + translation: [x, y, _], + } = self.is_planar().then(|| self.as_affine3()).flatten()?; + Some(Affine2 { + linear: Linear2([[a, c], [b, d]]), + translation: [x, y], + }) + } + + /// Reads the matrix as a linear map of the plane, or `None` if it touches the weight or `z` or has a translation. + pub fn as_linear2(self) -> Option { + self.is_linear().then(|| self.as_affine2()).flatten().map(|affine| affine.linear) + } +} + +/// The inner product of a row with a value over all four parts, where a zero entry contributes nothing even beside an infinite part. +fn inner(row: Quaternion, p: Quaternion) -> f64 { + row.parts().into_iter().zip(p.parts()).map(|(weight, part)| part_product(weight, part, false)).sum() +} + +/// The axes either map acts on, as a map built from both does. +fn joined(a: [bool; 4], b: [bool; 4]) -> [bool; 4] { + std::array::from_fn(|axis| a[axis] || b[axis]) +} + +/// The basis direction of one part. +fn unit(axis: usize) -> [f64; 4] { + std::array::from_fn(|part| if part == axis { 1. } else { 0. }) +} + +/// The part of `vector` orthogonal to the orthonormal `basis`, normalized, and its length relative to the vector's scale, or `None` +/// when nothing remains. +fn orthogonal_part(vector: [f64; 4], basis: &[[f64; 4]]) -> Option<([f64; 4], f64)> { + let scale = power_of_two_scale(vector.into_iter()); + let mut remainder = vector.map(|part| part / scale); + for direction in basis { + let projection: f64 = remainder.iter().zip(direction).map(|(part, direction)| part * direction).sum(); + remainder = std::array::from_fn(|part| remainder[part] - projection * direction[part]); + } + + let length = remainder.iter().map(|part| part * part).sum::().sqrt(); + (length > 0.).then(|| (remainder.map(|part| part / length), length)) +} + +/// The signed minor of the entry at `row`, `column`. +fn cofactor(entries: [[f64; 4]; 4], row: usize, column: usize) -> f64 { + let mut minor = [[0.; 3]; 3]; + for (minor_row, source_row) in (0..4).filter(|&index| index != row).enumerate() { + for (minor_column, source_column) in (0..4).filter(|&index| index != column).enumerate() { + minor[minor_row][minor_column] = entries[source_row][source_column]; + } + } + let [[a, b, c], [d, e, f], [g, h, i]] = minor; + let determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g); + if (row + column).is_multiple_of(2) { determinant } else { -determinant } +} + +impl Add for Matrix { + type Output = Self; + fn add(self, other: Self) -> Self { + Self { + rows: std::array::from_fn(|index| self.rows[index] + other.rows[index]), + translation: self.translation + other.translation, + axes: joined(self.axes, other.axes), + } + } +} + +impl Sub for Matrix { + type Output = Self; + fn sub(self, other: Self) -> Self { + self + -other + } +} + +impl Neg for Matrix { + type Output = Self; + fn neg(self) -> Self { + self.map(|entry| -entry) + } +} + +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // The shortest row literal naming the matrix, then its translation, parenthesized unless it is one positive part + let [w, x, y, z] = self.rows; + let rows: &[Quaternion] = if [x, y, z] == [ZERO; 3] { + &[w] + } else if w == ZERO && z == ZERO { + &[x, y] + } else if w == ZERO { + &[x, y, z] + } else { + &self.rows + }; + + f.write_str("[")?; + for (index, row) in rows.iter().enumerate() { + if index > 0 { + f.write_str(";")?; + } + Number::Quaternion(*row).canonical().fmt(f)?; + } + f.write_str("]")?; + + if self.translation != ZERO { + let parts = self.translation.parts(); + let translation = Number::Quaternion(self.translation).canonical(); + if parts.iter().filter(|part| **part != 0.).count() == 1 && parts.iter().any(|part| *part > 0.) { + write!(f, " + {translation}") + } else { + write!(f, " + ({translation})") + } + } else { + Ok(()) + } + } +} + +/// A region for `within`, `clamp`, and `remap`: a range literal kept by its corners as written, which may be integers past a +/// matrix's exactness or infinite where no matrix can hold them, or any other map. +#[derive(Debug, Clone, Copy)] +pub enum Region { + Range(Number, Number), + Map(Matrix), +} + +impl Region { + /// The region as a map, which for a range with an infinite corner holds infinite or indeterminate entries. + pub fn matrix(self) -> Matrix { + match self { + Region::Range(a, b) => Matrix::range(a.to_quaternion(), b.to_quaternion()), + Region::Map(matrix) => matrix, + } + } + + /// The region's scale: the largest finite magnitude among a range's corners' parts, or among a map's spanned columns and translation. + pub fn scale(self) -> f64 { + match self { + Region::Range(a, b) => largest_finite(a.to_quaternion().parts().into_iter().chain(b.to_quaternion().parts())), + Region::Map(matrix) => largest_finite((0..4).filter(|&axis| matrix.axes[axis]).flat_map(|axis| matrix.column(axis)).chain(matrix.translation.parts())), + } + } +} + +fn largest_finite(parts: impl Iterator) -> f64 { + parts.filter(|part| part.is_finite()).fold(0., |largest, part| largest.max(part.abs())) +} + +/// A linear map of the plane as its columns, the images of `i` and `j`, like glam's `from_cols`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Linear2(pub [[f64; 2]; 2]); + +/// A map of the plane: a linear part and a translation, like glam's `DAffine2`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Affine2 { + pub linear: Linear2, + pub translation: [f64; 2], +} + +/// A linear map of space as its columns, the images of `i`, `j`, and `k`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Linear3(pub [[f64; 3]; 3]); + +/// A map of space: a linear part and a translation, like glam's `DAffine3`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Affine3 { + pub linear: Linear3, + pub translation: [f64; 3], +} + +impl From for Matrix { + fn from( + Affine3 { + linear: Linear3([i, j, k]), + translation: [x, y, z], + }: Affine3, + ) -> Self { + Self { + rows: [ + Quaternion::ONE, + Quaternion::new(0., i[0], j[0], k[0]), + Quaternion::new(0., i[1], j[1], k[1]), + Quaternion::new(0., i[2], j[2], k[2]), + ], + translation: Quaternion::new(0., x, y, z), + axes: [false, true, true, true], + } + } +} + +impl From for Matrix { + fn from(linear: Linear3) -> Self { + Self::from(Affine3 { linear, translation: [0.; 3] }) + } +} + +impl From for Matrix { + fn from( + Affine2 { + linear: Linear2([i, j]), + translation: [x, y], + }: Affine2, + ) -> Self { + Self { + axes: [false, true, true, false], + ..Self::from(Affine3 { + linear: Linear3([[i[0], i[1], 0.], [j[0], j[1], 0.], [0., 0., 1.]]), + translation: [x, y, 0.], + }) + } + } +} + +impl From for Matrix { + fn from(linear: Linear2) -> Self { + Self::from(Affine2 { linear, translation: [0.; 2] }) + } +} diff --git a/libraries/math-parser/src/object.rs b/libraries/math-parser/src/object.rs new file mode 100644 index 0000000000..63fa419694 --- /dev/null +++ b/libraries/math-parser/src/object.rs @@ -0,0 +1,94 @@ +use crate::matrix::Matrix; +use crate::value::Value; +use std::fmt; + +/// What an expression evaluates to, one of the language's two sorts: a value or a matrix. The matrix is boxed so that a +/// value, the common case, stays small. +#[derive(Debug, Clone, PartialEq)] +pub enum Object { + Value(Value), + Matrix(Box), +} + +/// Generates readers that see a value's parts and nothing of a matrix. +macro_rules! value_readers { + ($($fn_name:ident: $type:ty),* $(,)?) => { + $( + #[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does, or `None` for a matrix.")] + pub fn $fn_name(&self) -> Option<$type> { + self.as_value()?.$fn_name() + } + )* + }; +} + +impl Object { + #[inline] + pub fn as_value(&self) -> Option<&Value> { + match self { + Self::Value(value) => Some(value), + Self::Matrix(_) => None, + } + } + + #[inline] + pub fn as_matrix(&self) -> Option<&Matrix> { + match self { + Self::Value(_) => None, + Self::Matrix(matrix) => Some(matrix), + } + } + + #[inline] + pub fn into_value(self) -> Option { + match self { + Self::Value(value) => Some(value), + Self::Matrix(_) => None, + } + } + + #[inline] + pub fn into_matrix(self) -> Option { + match self { + Self::Value(_) => None, + Self::Matrix(matrix) => Some(*matrix), + } + } + + value_readers! { + as_real: f64, + as_f32: f32, + as_bool: bool, + as_u8: u8, + as_u16: u16, + as_u32: u32, + as_u64: u64, + as_u128: u128, + as_i8: i8, + as_i16: i16, + as_i32: i32, + as_i64: i64, + as_i128: i128, + } +} + +impl> From for Object { + fn from(value: T) -> Self { + Self::Value(value.into()) + } +} + +impl From for Object { + fn from(matrix: Matrix) -> Self { + Self::Matrix(Box::new(matrix)) + } +} + +impl fmt::Display for Object { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Value(value) => value.fmt(f), + Self::Matrix(matrix) => matrix.fmt(f), + } + } +} diff --git a/libraries/math-parser/src/parser.rs b/libraries/math-parser/src/parser.rs index 82c4435c11..f830ae7b31 100644 --- a/libraries/math-parser/src/parser.rs +++ b/libraries/math-parser/src/parser.rs @@ -1,5 +1,8 @@ -use crate::ast::{BinaryOp, Case, Literal, Node, UnaryOp}; +use crate::ast::{BinaryOp, Case, Literal, Node, Syntax, UnaryOp}; +use crate::context::{FunctionProvider, NothingMap}; use crate::lexer::{Lexer, Span, Token}; +use crate::sort::sorted; +use chumsky::cache::{Cache, Cached}; use chumsky::error::{EmptyErr, LabelError}; use chumsky::input::ValueInput; use chumsky::{Parser, prelude::*}; @@ -42,30 +45,68 @@ impl<'src> CustomError for Rich<'src, Token<'src>, Span> { impl Node { pub fn try_parse_from_str(src: &str) -> Result { - // Parse with zero-cost errors first (several times faster), then re-parse invalid input with rich errors to build the messages - if let Ok(ast) = parser::().parse(Lexer::new(src)).into_result() { - return Ok(ast); - } + Self::try_parse_with_functions(src, &NothingMap) + } - match parser::>>().parse(Lexer::new(src)).into_result() { - Ok(ast) => Ok(ast), - Err(parse_errs) => Err(ParseError( - parse_errs - .into_iter() - .map(|e| match e.found() { - Some(Token::Percent) => format!("`%` is reserved for percentages, so the remainder is written `mod(a, b)`, at {}", e.span()), - Some(Token::If) => format!("`if` joins a case's value to its condition, like `{{a if x > 0, b otherwise}}`, at {}", e.span()), - Some(Token::Otherwise) => format!("`otherwise` ends the one case with no condition, like `{{a if x > 0, b otherwise}}`, at {}", e.span()), - Some(Token::Where) => format!("`where` is a reserved word, so it can't be a name, at {}", e.span()), - _ => format!("{e} at {}", e.span()), - }) - .collect(), - )), - } + /// Parses the source for a host that supplies functions, which shadow any builtin of the same name. + pub fn try_parse_with_functions(src: &str, functions: &impl FunctionProvider) -> Result { + sorted(parse(src)?, functions).map_err(|error| ParseError(vec![error.to_string()])) } } -pub fn parser<'src, I, E>() -> impl Parser<'src, I, Node, E> +/// The parser with zero-cost errors, built once per thread, since building the combinator tree costs as much as parsing a short +/// expression, and cached across input lifetimes by chumsky's cache. +struct FastParser; + +impl Cached for FastParser { + type Parser<'src> = Boxed<'src, 'src, Lexer<'src>, Syntax, extra::Default>; + + fn make_parser<'src>(self) -> ::Parser<'src> { + parser().boxed() + } +} + +/// The parser with rich errors, likewise built once per thread. +struct RichParser; + +impl Cached for RichParser { + type Parser<'src> = Boxed<'src, 'src, Lexer<'src>, Syntax, extra::Err, Span>>>; + + fn make_parser<'src>(self) -> ::Parser<'src> { + parser().boxed() + } +} + +thread_local! { + static FAST_PARSER: Cache = Cache::new(FastParser); + static RICH_PARSER: Cache = Cache::new(RichParser); +} + +/// Parses the source as written, before its sorts are read. +fn parse(src: &str) -> Result { + // Parse with zero-cost errors first (several times faster), then re-parse invalid input with rich errors to build the messages + if let Ok(ast) = FAST_PARSER.with(|cache| cache.get().parse(Lexer::new(src)).into_result()) { + return Ok(ast); + } + + match RICH_PARSER.with(|cache| cache.get().parse(Lexer::new(src)).into_result()) { + Ok(ast) => Ok(ast), + Err(parse_errs) => Err(ParseError( + parse_errs + .into_iter() + .map(|e| match e.found() { + Some(Token::Percent) => format!("`%` is reserved for percentages, so the remainder is written `mod(a, b)`, at {}", e.span()), + Some(Token::If) => format!("`if` joins a case's value to its condition, like `{{a if x > 0, b otherwise}}`, at {}", e.span()), + Some(Token::Otherwise) => format!("`otherwise` ends the one case with no condition, like `{{a if x > 0, b otherwise}}`, at {}", e.span()), + Some(Token::Where) => format!("`where` is a reserved word, so it can't be a name, at {}", e.span()), + _ => format!("{e} at {}", e.span()), + }) + .collect(), + )), + } +} + +pub fn parser<'src, I, E>() -> impl Parser<'src, I, Syntax, E> where I: ValueInput<'src, Token = Token<'src>, Span = Span>, E: extra::ParserExtra<'src, I>, @@ -73,8 +114,8 @@ where { recursive(|expr| { let constant = select! { - Token::Integer(integer) => Node::Lit(Literal::Integer(integer)), - Token::Float(float) => Node::Lit(Literal::Float(float)), + Token::Integer(integer) => Syntax::Lit(Literal::Integer(integer)), + Token::Float(float) => Syntax::Lit(Literal::Float(float)), }; let args = expr.clone().separated_by(just(Token::Comma)).collect::>().delimited_by(just(Token::LParen), just(Token::RParen)); @@ -84,7 +125,7 @@ where let piecewise = case .separated_by(just(Token::Comma)) .at_least(1) - .collect::)>>() + .collect::)>>() .delimited_by(just(Token::LBrace), just(Token::RBrace)) // Emitted rather than failed, since a failure at the atom's start would be relabeled as a missing atom .validate(|written_cases, extra, emitter| { @@ -97,24 +138,42 @@ where None => emitter.emit(CustomError::custom(extra.span(), "A piecewise has at most one `otherwise` case")), } } - Node::Piecewise { cases, otherwise } + Syntax::Piecewise { cases, otherwise } }); + // A matrix literal lists whole values as rows with `;` or as columns with `,`, one separator kind per literal + let entries = |separator: Token<'src>, by_rows: bool| { + expr.clone() + .separated_by(just(separator)) + .at_least(1) + .collect::>() + .delimited_by(just(Token::LBracket), just(Token::RBracket)) + .map(move |entries| Syntax::Matrix { entries, by_rows }) + }; + let matrix = choice((entries(Token::Semicolon, true), entries(Token::Comma, false))).validate(|node, extra, emitter| { + if let Syntax::Matrix { entries, .. } = &node + && entries.len() > 4 + { + emitter.emit(CustomError::custom(extra.span(), "A matrix literal has at most four entries, one per part `1`, `i`, `j`, `k`")); + } + node + }); + let ident = select! {Token::Ident(s) => s}.labelled("ident"); // An ident followed by parenthesized args is a function call, otherwise a variable - let call_or_var = ident.then(args.or_not()).map(|(name, args): (&str, Option>)| match args { - Some(args) => Node::FnCall { name: name.to_string(), expr: args }, - None => Node::Var(name.to_string()), + let call_or_var = ident.then(args.or_not()).map(|(name, args): (&str, Option>)| match args { + Some(args) => Syntax::FnCall { name: name.to_string(), expr: args }, + None => Syntax::Var(name.to_string()), }); let parens = expr.clone().delimited_by(just(Token::LParen), just(Token::RParen)); - let magnitude = expr.clone().delimited_by(just(Token::BarOpen), just(Token::BarClose)).map(|expr| Node::UnaryOp { + let magnitude = expr.clone().delimited_by(just(Token::BarOpen), just(Token::BarClose)).map(|expr| Syntax::UnaryOp { op: UnaryOp::Magnitude, expr: Box::new(expr), }); - let atom = choice((constant, piecewise, call_or_var, parens, magnitude)).labelled("atom"); + let atom = choice((constant, piecewise, matrix, call_or_var, parens, magnitude)).labelled("atom"); let add_op = choice((just(Token::Plus).to(BinaryOp::Add), just(Token::Minus).to(BinaryOp::Sub))); let mul_op = choice((just(Token::Star).to(BinaryOp::Mul), just(Token::Slash).to(BinaryOp::Div))); @@ -136,17 +195,15 @@ where just(Token::EqEq).to(BinaryOp::Eq), )); - // Postfix factorial: expr! → UnaryOp::Fac - let postfix = atom.clone().foldl(just(Token::Bang).repeated(), |expr, _| Node::UnaryOp { - op: UnaryOp::Fac, - expr: Box::new(expr), - }); + // The postfix operators, the factorial `x!` and the transpose `A^T` + let postfix_op = choice((just(Token::Bang).to(UnaryOp::Fac), just(Token::Transpose).to(UnaryOp::Transpose))); + let postfix = atom.clone().foldl(postfix_op.repeated(), |expr, op| Syntax::UnaryOp { op, expr: Box::new(expr) }); // Exponentiation is right-associative (`2^2^3` is `2^(2^3)`) and the exponent may carry unary signs like `2^-3` let pow = recursive(|pow| { - let exponent = unary_op.clone().repeated().foldr(pow, |op, expr| Node::UnaryOp { op, expr: Box::new(expr) }); + let exponent = unary_op.clone().repeated().foldr(pow, |op, expr| Syntax::UnaryOp { op, expr: Box::new(expr) }); postfix.clone().then(pow_op.ignore_then(exponent).or_not()).map(|(base, exponent)| match exponent { - Some(exponent) => Node::BinOp { + Some(exponent) => Syntax::BinOp { lhs: Box::new(base), op: BinaryOp::Pow, rhs: Box::new(exponent), @@ -155,32 +212,54 @@ where }) }); - let unary = unary_op.clone().repeated().foldr(pow.clone(), |op, expr| Node::UnaryOp { op, expr: Box::new(expr) }); + let unary = unary_op.clone().repeated().foldr(pow.clone(), |op, expr| Syntax::UnaryOp { op, expr: Box::new(expr) }); // Juxtaposed factors like `2pi` or `2sqrt(4)` multiply implicitly at the same precedence as `*` and `/`. // The implicit operand is a `pow`, not a full unary, so `2 -3` stays a subtraction; the lexer rejects a number right after another number (`10 000` is not `10*000`). let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs)); - let product = unary.clone().foldl(choice((mul_op.then(unary), implicit_mul)).repeated(), |lhs, (op, rhs)| Node::BinOp { + let product = unary + .clone() + .then(choice((mul_op.then(unary), implicit_mul)).repeated().collect::>()) + .map(|(first, mut rest): (Syntax, Vec<(BinaryOp, Syntax)>)| { + // Two factors group only one way, while a longer chain is grouped by the sort pass, which knows the matrices + if rest.len() <= 1 { + return match rest.pop() { + Some((op, second)) => Syntax::BinOp { + lhs: Box::new(first), + op, + rhs: Box::new(second), + }, + None => first, + }; + } + + Syntax::Product { first: Box::new(first), rest } + }); + + let add = product.clone().foldl(add_op.then(product).repeated(), |lhs, (op, rhs)| Syntax::BinOp { lhs: Box::new(lhs), op, rhs: Box::new(rhs), }); - let add = product.clone().foldl(add_op.then(product).repeated(), |lhs, (op, rhs)| Node::BinOp { - lhs: Box::new(lhs), - op, - rhs: Box::new(rhs), + // A range binds looser than arithmetic, so `0..2pi` reaches `2π`, and tighter than comparison + let range = add.clone().then(just(Token::DotDot).ignore_then(add).or_not()).map(|(from, to)| match to { + Some(to) => Syntax::Range { + from: Box::new(from), + to: Box::new(to), + }, + None => from, }); // A chain like `0 <= x < 1` is one predicate over its adjacent pairs, not an implicit `(0 <= x) < 1` (which is only read that way when its parentheses are written out), and must read in one direction - let cmp = add + let cmp = range .clone() - .then(cmp_op.then(add).repeated().collect::>()) - .try_map(|(first, mut rest): (Node, Vec<(BinaryOp, Node)>), span| { + .then(cmp_op.then(range).repeated().collect::>()) + .try_map(|(first, mut rest): (Syntax, Vec<(BinaryOp, Syntax)>), span| { // A lone comparison is an ordinary binary operation if rest.len() <= 1 { return Ok(match rest.pop() { - Some((op, second)) => Node::BinOp { + Some((op, second)) => Syntax::BinOp { lhs: Box::new(first), op, rhs: Box::new(second), @@ -197,16 +276,16 @@ where )); } - Ok(Node::Comparison { first: Box::new(first), rest }) + Ok(Syntax::Comparison { first: Box::new(first), rest }) }); - let and = cmp.clone().foldl(and_op.then(cmp).repeated(), |lhs, (op, rhs)| Node::BinOp { + let and = cmp.clone().foldl(and_op.then(cmp).repeated(), |lhs, (op, rhs)| Syntax::BinOp { lhs: Box::new(lhs), op, rhs: Box::new(rhs), }); - and.clone().foldl(or_op.then(and).repeated(), |lhs, (op, rhs)| Node::BinOp { + and.clone().foldl(or_op.then(and).repeated(), |lhs, (op, rhs)| Syntax::BinOp { lhs: Box::new(lhs), op, rhs: Box::new(rhs), @@ -224,7 +303,7 @@ mod tests { #[test] fn $name() { - let result = match Node::try_parse_from_str($input) { + let result = match parse($input) { Ok(expr) => expr, Err(err) => panic!("failed to parse `{}`: {err}", $input), }; @@ -235,72 +314,114 @@ mod tests { } test_parser! { - test_parse_int_literal: "42" => Node::Lit(Literal::Integer(42)), - test_parse_float_literal: "3.14" => Node::Lit(Literal::Float(#[allow(clippy::approx_constant)] 3.14)), - test_parse_ident: "x" => Node::Var("x".to_string()), - test_parse_unary_neg: "-42" => Node::UnaryOp { - expr: Box::new(Node::Lit(Literal::Integer(42))), + test_parse_int_literal: "42" => Syntax::Lit(Literal::Integer(42)), + test_parse_float_literal: "3.14" => Syntax::Lit(Literal::Float(#[allow(clippy::approx_constant)] 3.14)), + test_parse_ident: "x" => Syntax::Var("x".to_string()), + test_matrix_rows: "[1;i]" => Syntax::Matrix { + entries: vec![Syntax::Lit(Literal::Integer(1)), Syntax::Var("i".to_string())], + by_rows: true, + }, + test_matrix_columns: "[i,j]" => Syntax::Matrix { + entries: vec![Syntax::Var("i".to_string()), Syntax::Var("j".to_string())], + by_rows: false, + }, + test_range_below_arithmetic: "-1..2pi" => Syntax::Range { + from: Box::new(Syntax::UnaryOp { + op: UnaryOp::Neg, + expr: Box::new(Syntax::Lit(Literal::Integer(1))), + }), + to: Box::new(Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(2))), + op: BinaryOp::Mul, + rhs: Box::new(Syntax::Var("pi".to_string())), + }), + }, + test_product_chain_stays_flat: "2 * 3 / 4" => Syntax::Product { + first: Box::new(Syntax::Lit(Literal::Integer(2))), + rest: vec![(BinaryOp::Mul, Syntax::Lit(Literal::Integer(3))), (BinaryOp::Div, Syntax::Lit(Literal::Integer(4)))], + }, + test_range_above_comparison: "0..1 == I" => Syntax::BinOp { + lhs: Box::new(Syntax::Range { + from: Box::new(Syntax::Lit(Literal::Integer(0))), + to: Box::new(Syntax::Lit(Literal::Integer(1))), + }), + op: BinaryOp::Eq, + rhs: Box::new(Syntax::Var("I".to_string())), + }, + test_transpose_then_inverse: "A^T^-1" => Syntax::BinOp { + lhs: Box::new(Syntax::UnaryOp { + op: UnaryOp::Transpose, + expr: Box::new(Syntax::Var("A".to_string())), + }), + op: BinaryOp::Pow, + rhs: Box::new(Syntax::UnaryOp { + op: UnaryOp::Neg, + expr: Box::new(Syntax::Lit(Literal::Integer(1))), + }), + }, + test_parse_unary_neg: "-42" => Syntax::UnaryOp { + expr: Box::new(Syntax::Lit(Literal::Integer(42))), op: UnaryOp::Neg, }, - test_parse_binary_add: "1 + 2" => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Integer(1))), + test_parse_binary_add: "1 + 2" => Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(1))), op: BinaryOp::Add, - rhs: Box::new(Node::Lit(Literal::Integer(2))), + rhs: Box::new(Syntax::Lit(Literal::Integer(2))), }, - test_parse_binary_mul: "3 * 4" => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Integer(3))), + test_parse_binary_mul: "3 * 4" => Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(3))), op: BinaryOp::Mul, - rhs: Box::new(Node::Lit(Literal::Integer(4))), + rhs: Box::new(Syntax::Lit(Literal::Integer(4))), }, - test_parse_binary_pow: "2 ^ 3" => Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Integer(2))), + test_parse_binary_pow: "2 ^ 3" => Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(2))), op: BinaryOp::Pow, - rhs: Box::new(Node::Lit(Literal::Integer(3))), + rhs: Box::new(Syntax::Lit(Literal::Integer(3))), }, - test_parse_sqrt_call: "sqrt(16)" => Node::FnCall { + test_parse_sqrt_call: "sqrt(16)" => Syntax::FnCall { name: "sqrt".to_string(), - expr: vec![Node::Lit(Literal::Integer(16))], + expr: vec![Syntax::Lit(Literal::Integer(16))], }, - test_parse_ii_call: "ii(16)" => Node::FnCall { + test_parse_ii_call: "ii(16)" => Syntax::FnCall { name: "ii".to_string(), - expr: vec![Node::Lit(Literal::Integer(16))] + expr: vec![Syntax::Lit(Literal::Integer(16))] }, // `i` is a name a binding may shadow, so only the evaluator can read this call as `i` times its argument - test_parse_i_mul: "i(16)" => Node::FnCall { + test_parse_i_mul: "i(16)" => Syntax::FnCall { name: "i".to_string(), - expr: vec![Node::Lit(Literal::Integer(16))], + expr: vec![Syntax::Lit(Literal::Integer(16))], }, - test_parse_complex_expr: "(1 + 2) * 3 - 4 ^ 2" => Node::BinOp { - lhs: Box::new(Node::BinOp { - lhs: Box::new(Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Integer(1))), + test_parse_complex_expr: "(1 + 2) * 3 - 4 ^ 2" => Syntax::BinOp { + lhs: Box::new(Syntax::BinOp { + lhs: Box::new(Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(1))), op: BinaryOp::Add, - rhs: Box::new(Node::Lit(Literal::Integer(2))), + rhs: Box::new(Syntax::Lit(Literal::Integer(2))), }), op: BinaryOp::Mul, - rhs: Box::new(Node::Lit(Literal::Integer(3))), + rhs: Box::new(Syntax::Lit(Literal::Integer(3))), }), op: BinaryOp::Sub, - rhs: Box::new(Node::BinOp { - lhs: Box::new(Node::Lit(Literal::Integer(4))), + rhs: Box::new(Syntax::BinOp { + lhs: Box::new(Syntax::Lit(Literal::Integer(4))), op: BinaryOp::Pow, - rhs: Box::new(Node::Lit(Literal::Integer(2))), + rhs: Box::new(Syntax::Lit(Literal::Integer(2))), }), }, - test_piecewise_expr: "{0 otherwise, x + 3 if x < 0}" => Node::Piecewise { + test_piecewise_expr: "{0 otherwise, x + 3 if x < 0}" => Syntax::Piecewise { cases: vec![Case { - value: Node::BinOp { - lhs: Box::new(Node::Var("x".to_string())), + value: Syntax::BinOp { + lhs: Box::new(Syntax::Var("x".to_string())), op: BinaryOp::Add, - rhs: Box::new(Node::Lit(Literal::Integer(3))), + rhs: Box::new(Syntax::Lit(Literal::Integer(3))), }, - condition: Node::BinOp { - lhs: Box::new(Node::Var("x".to_string())), + condition: Syntax::BinOp { + lhs: Box::new(Syntax::Var("x".to_string())), op: BinaryOp::Lt, - rhs: Box::new(Node::Lit(Literal::Integer(0))), + rhs: Box::new(Syntax::Lit(Literal::Integer(0))), }, }], - otherwise: Some(Box::new(Node::Lit(Literal::Integer(0)))), + otherwise: Some(Box::new(Syntax::Lit(Literal::Integer(0)))), } } } diff --git a/libraries/math-parser/src/quaternion.rs b/libraries/math-parser/src/quaternion.rs index dc40b01b14..157ba67d57 100644 --- a/libraries/math-parser/src/quaternion.rs +++ b/libraries/math-parser/src/quaternion.rs @@ -13,6 +13,7 @@ pub struct Quaternion { } impl Quaternion { + pub const ZERO: Self = Self::new(0., 0., 0., 0.); pub const ONE: Self = Self::new(1., 0., 0., 0.); pub const I: Self = Self::new(0., 1., 0., 0.); pub const J: Self = Self::new(0., 0., 1., 0.); @@ -206,7 +207,7 @@ impl Div for Quaternion { impl fmt::Display for Quaternion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // Only the nonzero parts are written, each with its basis, in the style `1+2i-3j` + // Only the nonzero parts are written, each with its basis, in the style `1+2i-3j`, where a unit part is its basis alone let mut written = false; for (part, basis) in self.parts().into_iter().zip(["", "i", "j", "k"]) { if part == 0. { @@ -215,7 +216,11 @@ impl fmt::Display for Quaternion { if written && part.is_sign_positive() { f.write_str("+")?; } - fmt_real(part, f)?; + if basis.is_empty() || part.abs() != 1. { + fmt_real(part, f)?; + } else if part < 0. { + f.write_str("-")?; + } f.write_str(basis)?; written = true; } diff --git a/libraries/math-parser/src/reducer.rs b/libraries/math-parser/src/reducer.rs index 4248dad9bd..63e20b21ca 100644 --- a/libraries/math-parser/src/reducer.rs +++ b/libraries/math-parser/src/reducer.rs @@ -1,11 +1,18 @@ use crate::ast::BinaryOp; -use crate::constants::{BuiltinFunction, builtin_function}; +use crate::constants::{Builtin, BuiltinFunction, builtin_function}; use crate::context::ValueProvider; +use crate::executer::settle_matrix; use crate::lexer::{Lexer, Token}; +use crate::matrix::Matrix; +use crate::object::Object; use crate::value::{Number, Value}; +use std::cmp::Ordering; use std::collections::HashSet; use std::hash::{Hash, Hasher}; +/// A variadic function's action across a matrix list, which `mean` and `count` alone have. +pub type MatrixFunction = fn(&[Matrix]) -> Option; + /// How a lone reducer token combines the items it is applied across. #[derive(Clone, Copy)] pub enum Reducer { @@ -18,7 +25,17 @@ pub enum Reducer { /// A single n-ary predicate asserting that every pair of items is distinct, like `a != b != c`. ChainDistinct, /// A single call of a variadic function over all items, like `min(a, b, c)`. - Function(BuiltinFunction), + Function { function: BuiltinFunction, over_matrices: Option }, +} + +/// The action of a variadic function across matrices: the mean is pointwise and the count counts, while the others need an +/// order or a product of values. +fn matrix_function(name: &str) -> Option { + match name { + "mean" => Some(|matrices| settle_matrix(Matrix::mean(matrices)?).ok().map(Object::from)), + "count" => Some(|matrices| Some(Object::from(Value::from_i64(matrices.len() as i64)))), + _ => None, + } } /// Classifies an input string as a lone reducer token, or `None` when it should instead be parsed as a full expression. @@ -51,7 +68,13 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option return None, None => name, }; - Reducer::Function(builtin_function(bare_name).filter(|builtin| builtin.variadic)?.function) + match builtin_function(bare_name)? { + Builtin::Values { function, variadic: true } => Reducer::Function { + function, + over_matrices: matrix_function(bare_name), + }, + _ => return None, + } } _ => return None, }) @@ -75,6 +98,11 @@ impl Reducer { Reducer::FoldLeft(op) => { let mut iter = numbers; let Some(first) = iter.next() else { return op.identity_element() }; + + // A lone item meets no operator, so logic checks it is a truth value here + if matches!(op, BinaryOp::And | BinaryOp::Or) { + first.as_bool()?; + } iter.try_fold(first, |accumulated, item| accumulated.binary_op(*op, item)).map(Value::Number) } @@ -84,11 +112,7 @@ impl Reducer { iter.try_fold(first, |accumulated, item| item.binary_op(*op, accumulated)).map(Value::Number) } - // A chain over zero or one items is true, since no pair exists to fail the relation - Reducer::ChainAdjacent(op) => { - let satisfied = numbers.clone().zip(numbers.skip(1)).all(|(lhs, rhs)| lhs.binary_op(*op, rhs).and_then(Number::as_bool) == Some(true)); - Some(Value::from_bool(satisfied)) - } + Reducer::ChainAdjacent(op) => chain_holds(*op, numbers).map(Value::from_bool), // Canonical form stores each value one way (and NaN is already rejected), so equal items share a key and hashing finds a repeat in O(n) Reducer::ChainDistinct => { @@ -98,12 +122,76 @@ impl Reducer { } // Builtins read any complex or quaternion storage as having a vector part, which a host's item may lack - Reducer::Function(function) if items.iter().any(|Value::Number(number)| matches!(number, Number::Complex(_) | Number::Quaternion(_))) => { + Reducer::Function { function, .. } if items.iter().any(|Value::Number(number)| matches!(number, Number::Complex(_) | Number::Quaternion(_))) => { function(&numbers.map(Value::Number).collect::>()) } - Reducer::Function(function) => function(items), + Reducer::Function { function, .. } => function(items), } } + + /// Evaluates this reducer across matrices: `*` and `/` compose in list order, `+`, `-`, and `mean` are pointwise, and `count` + /// counts. Any other reducer is `None`, like a NaN item or a fold of an empty list under `-` or `/`. + pub fn evaluate_matrices(&self, items: &[Matrix]) -> Option { + if items.iter().any(|matrix| matrix.is_nan()) { + return None; + } + + match self { + Reducer::FoldLeft(op) => { + let combine: fn(Matrix, Matrix) -> Option = match op { + BinaryOp::Add => |a, b| Some(a + b), + BinaryOp::Sub => |a, b| Some(a - b), + BinaryOp::Mul => |a, b| Some(a.compose(b)), + BinaryOp::Div => |a, b| Some(a.compose(b.inverse()?)), + _ => return None, + }; + + let mut iter = items.iter().copied(); + let Some(first) = iter.next() else { + return match op { + BinaryOp::Add => Some(Object::from(Matrix::ZERO)), + BinaryOp::Mul => Some(Object::from(Matrix::IDENTITY)), + _ => None, + }; + }; + let combined = iter.try_fold(first, |accumulated, matrix| settle_matrix(combine(accumulated, matrix)?).ok())?; + Some(Object::from(combined)) + } + Reducer::Function { over_matrices, .. } => over_matrices.and_then(|function| function(items)), + Reducer::FoldRight(_) | Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => None, + } + } +} + +/// Whether every adjacent pair of items satisfies the chain's relation: true over zero or one items, since no pair exists to fail +/// it, and `None` when any item has no order, since every pair is checked. Its own function keeps the loop's frame small. +#[inline(never)] +fn chain_holds(op: BinaryOp, numbers: impl Iterator) -> Option { + let mut satisfied = true; + let mut previous = None; + for number in numbers { + if let Some(previous) = previous { + satisfied &= adjacent_holds(op, previous, number)?; + } + previous = Some(number); + } + Some(satisfied) +} + +/// Whether two adjacent items of a comparison chain satisfy its relation, or `None` when one has a vector part and so no order. +fn adjacent_holds(op: BinaryOp, lhs: Number, rhs: Number) -> Option { + if op == BinaryOp::Eq { + return Some(lhs == rhs); + } + + let ordering = lhs.real_ordering(rhs)?; + Some(match op { + BinaryOp::Lt => ordering == Ordering::Less, + BinaryOp::Leq => ordering != Ordering::Greater, + BinaryOp::Gt => ordering == Ordering::Greater, + BinaryOp::Geq => ordering != Ordering::Less, + _ => return None, + }) } /// A canonical number's storage as hashable bits, which equal numbers share. @@ -208,6 +296,14 @@ mod tests { assert_eq!(run("^", &[]), None); } + #[test] + fn logic_checks_a_lone_item_is_a_truth_value() { + assert_eq!(run("&&", &[1.]), Some(1.)); + assert_eq!(run("||", &[0.]), Some(0.)); + assert_eq!(run("&&", &[5.]), None); + assert_eq!(run("||", &[0.5]), None); + } + #[test] fn chains_are_single_predicates() { assert_eq!(run("<", &[1., 2., 3.]), Some(1.)); @@ -276,6 +372,19 @@ mod tests { assert_eq!(reduce(">"), Some(Value::from_bool(true))); } + #[test] + fn orderings_reject_vector_items() { + // A vector has no order, so an ordered chain over one is ill-formed rather than false, while equality compares any items + let reduce = |source: &str, items: &[Value]| classify_reducer(source, NothingMap).unwrap().evaluate(items); + let vectors = [Value::from(Quaternion::J), Value::from(Quaternion::K)]; + for source in ["<", "<=", ">", ">="] { + assert_eq!(reduce(source, &vectors), None, "`{source}`"); + assert_eq!(reduce(source, &[Value::from_f64(1.), Value::from(Quaternion::J), Value::from_f64(3.)]), None, "`{source}`"); + } + assert_eq!(reduce("==", &vectors), Some(Value::from_bool(false))); + assert_eq!(reduce("==", &[Value::from(Quaternion::J), Value::from(Quaternion::J)]), Some(Value::from_bool(true))); + } + #[test] fn nan_items_are_rejected() { // `min` and `count` would otherwise drop or ignore the NaN and return a number @@ -283,4 +392,42 @@ mod tests { assert_eq!(run(source, &[f64::NAN, 1.]), None, "`{source}`"); } } + + #[test] + fn matrix_lists_compose_sum_average_and_count() { + let reduce = |source: &str, items: &[Matrix]| classify_reducer(source, NothingMap).unwrap().evaluate_matrices(items); + let scale = Matrix::scale(Quaternion::new(2., 0., 0., 0.)); + let shift = Matrix::IDENTITY.translated(Quaternion::I); + + // Products compose in list order, so the shift lands before the scale doubles it + assert_eq!(reduce("*", &[scale, shift]).unwrap().into_matrix().unwrap().translation, Quaternion::new(0., 2., 0., 0.)); + assert_eq!(reduce("*", &[shift, scale]).unwrap().into_matrix().unwrap().translation, Quaternion::I); + assert_eq!(reduce("/", &[scale, scale]).unwrap(), Object::from(Matrix { axes: scale.axes, ..Matrix::IDENTITY })); + + // Sums and the mean are pointwise, and the count is a value + assert_eq!(reduce("+", &[scale, scale]).unwrap().into_matrix().unwrap().rows[1], Quaternion::new(0., 4., 0., 0.)); + assert_eq!(reduce("-", &[scale, scale]).unwrap().into_matrix().unwrap().rows[1], Quaternion::ZERO); + assert_eq!(reduce("mean", &[scale, Matrix::IDENTITY]).unwrap().into_matrix().unwrap().rows[1], Quaternion::new(0., 1.5, 0., 0.)); + let huge = Matrix::scale(Quaternion::new(1e308, 0., 0., 0.)); + assert_eq!(reduce("mean", &[huge, huge]).unwrap(), Object::from(huge)); + assert_eq!(reduce("count", &[scale, shift]), Some(Object::from(Value::from_i64(2)))); + + // An empty list yields the identity element where there is one, and a singular divisor has no inverse + assert_eq!(reduce("*", &[]), Some(Object::from(Matrix::IDENTITY))); + assert_eq!(reduce("+", &[]), Some(Object::from(Matrix::ZERO))); + assert_eq!(reduce("count", &[]), Some(Object::from(Value::from_i64(0)))); + for source in ["-", "/", "mean"] { + assert_eq!(reduce(source, &[]), None, "`{source}`"); + } + assert_eq!(reduce("/", &[scale, Matrix::ZERO]), None); + + // Matrices have no order, power, extremum, or truth, even alone, and a NaN item is rejected + for source in ["<", "==", "!=", "^", "&&", "min", "max", "median", "xor"] { + assert_eq!(reduce(source, &[scale, shift]), None, "`{source}`"); + } + for source in ["&&", "||"] { + assert_eq!(reduce(source, &[scale]), None, "`{source}`"); + } + assert_eq!(reduce("+", &[scale, Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN))]), None); + } } diff --git a/libraries/math-parser/src/sort.rs b/libraries/math-parser/src/sort.rs new file mode 100644 index 0000000000..2313d31ab0 --- /dev/null +++ b/libraries/math-parser/src/sort.rs @@ -0,0 +1,243 @@ +use crate::ast::{BinaryOp, Case, Literal, MatrixNode, Node, SortedCase, Syntax, UnaryOp, ValueNode}; +use crate::constants::{Builtin, builtin_function}; +use crate::context::FunctionProvider; +use crate::lexer::names_matrix; +use std::fmt; + +/// A subexpression standing where its sort cannot, which fails the parse, since every sort is fixed by spelling. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SortError(&'static str); + +impl fmt::Display for SortError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } +} + +const MATRIX_AS_VALUE: SortError = SortError("A matrix stands where a value is needed"); +const VALUE_AS_MATRIX: SortError = SortError("A value stands where a matrix is needed"); +const NO_MATRIX_OPERATOR: SortError = SortError("The operator has no meaning for a matrix"); +const MIXED_CASES: SortError = SortError("A piecewise's cases must all be values or all be matrices"); +const INVALID_ARGUMENTS: SortError = SortError("Invalid arguments for function call"); + +/// Reads the sort of every subexpression from its spelling, so each evaluator takes only trees of its own sort. A call of a +/// function the host provides is a value, whatever builtin shares its name. +pub fn sorted(syntax: Syntax, functions: &dyn FunctionProvider) -> Result { + Ok(match syntax { + Syntax::Lit(literal) => Node::Value(ValueNode::Lit(literal)), + Syntax::Var(name) if names_matrix(&name) => Node::Matrix(MatrixNode::Var(name)), + Syntax::Var(name) => Node::Value(ValueNode::Var(name)), + Syntax::FnCall { name, expr } => call(name, expr, functions)?, + Syntax::BinOp { lhs, op, rhs } => binary(sorted(*lhs, functions)?, op, sorted(*rhs, functions)?)?, + Syntax::Product { first, rest } => product(sorted(*first, functions)?, &mut rest.into_iter(), functions)?, + Syntax::UnaryOp { expr, op } => match (sorted(*expr, functions)?, op) { + (Node::Value(_), UnaryOp::Transpose) => return Err(VALUE_AS_MATRIX), + (Node::Value(expr), op) => Node::Value(ValueNode::UnaryOp { expr: Box::new(expr), op }), + (Node::Matrix(expr), UnaryOp::Pos | UnaryOp::Neg | UnaryOp::Transpose) => Node::Matrix(MatrixNode::UnaryOp { expr: Box::new(expr), op }), + (Node::Matrix(_), _) => return Err(NO_MATRIX_OPERATOR), + }, + Syntax::Comparison { first, rest } => { + let first = sorted(*first, functions)?; + let rest = rest + .into_iter() + .map(|(op, operand)| Ok((op, sorted(operand, functions)?))) + .collect::, SortError>>()?; + match first { + Node::Value(first) => { + let rest = rest.into_iter().map(|(op, operand)| Ok((op, value(operand)?))).collect::, SortError>>()?; + Node::Value(ValueNode::Comparison { first: Box::new(first), rest }) + } + // Matrices have no order, so a chain over them is `==` or `!=` throughout + Node::Matrix(first) => { + let distinct = rest.iter().all(|(op, _)| *op == BinaryOp::Neq); + if !distinct && !rest.iter().all(|(op, _)| *op == BinaryOp::Eq) { + return Err(NO_MATRIX_OPERATOR); + } + let rest = rest.into_iter().map(|(_, operand)| matrix(operand).map_err(|_| NO_MATRIX_OPERATOR)); + let matrices = std::iter::once(Ok(first)).chain(rest).collect::, SortError>>()?; + Node::Value(ValueNode::MatrixComparison { matrices, distinct }) + } + } + } + Syntax::Piecewise { cases, otherwise } => piecewise(cases, otherwise, functions)?, + Syntax::Matrix { entries, by_rows } => Node::Matrix(MatrixNode::Literal { + entries: entries.into_iter().map(|entry| value(sorted(entry, functions)?)).collect::, SortError>>()?, + by_rows, + }), + Syntax::Range { from, to } => Node::Matrix(MatrixNode::Range { + from: Box::new(value(sorted(*from, functions)?)?), + to: Box::new(value(sorted(*to, functions)?)?), + }), + }) +} + +fn value(node: Node) -> Result { + match node { + Node::Value(value) => Ok(value), + Node::Matrix(_) => Err(MATRIX_AS_VALUE), + } +} + +fn matrix(node: Node) -> Result { + match node { + Node::Matrix(matrix) => Ok(matrix), + Node::Value(_) => Err(VALUE_AS_MATRIX), + } +} + +fn values(nodes: Vec) -> Result, SortError> { + nodes.into_iter().map(value).collect() +} + +fn one(arguments: Vec) -> Result { + <[Node; 1]>::try_from(arguments).map(|[argument]| argument).map_err(|_| INVALID_ARGUMENTS) +} + +/// A call's sort follows the builtin's, a matrix's name applying it to its one argument, and any other name taking values alone. +/// A range function like `within(p, R)` takes a value and then matrices. +fn call(name: String, arguments: Vec, functions: &dyn FunctionProvider) -> Result { + let arguments = arguments.into_iter().map(|argument| sorted(argument, functions)).collect::, SortError>>()?; + let (prefixed, bare_name) = match name.strip_prefix('\\') { + Some(bare_name) => (true, bare_name), + None => (false, name.as_str()), + }; + + // A matrix applied to one argument is implicit multiplication, so `M(v)` matches `M v` + if names_matrix(bare_name) { + return binary(Node::Matrix(MatrixNode::Var(name)), BinaryOp::Mul, one(arguments)?); + } + + // A host function shadows the builtin of its spelling unless the `\` prefix asks for the language's own + let builtin = if !prefixed && functions.provides(bare_name) { None } else { builtin_function(bare_name) }; + + Ok(match builtin { + Some(Builtin::OfMatrix(function)) => Node::Value(ValueNode::OfMatrix { + function, + matrix: Box::new(matrix(one(arguments)?)?), + }), + Some(Builtin::MatrixOfMatrix(function)) => Node::Matrix(MatrixNode::OfMatrix { + function, + matrix: Box::new(matrix(one(arguments)?)?), + }), + Some(Builtin::MatrixOfValues { function, arity }) => { + if !arity.contains(&arguments.len()) { + return Err(INVALID_ARGUMENTS); + } + Node::Matrix(MatrixNode::FromValues { + function, + arguments: values(arguments)?, + }) + } + Some(Builtin::OfValueAndRegions { function, regions }) => { + if arguments.len() != regions + 1 { + return Err(INVALID_ARGUMENTS); + } + let mut arguments = arguments.into_iter(); + Node::Value(ValueNode::OfValueAndRegions { + function, + value: Box::new(value(arguments.next().ok_or(INVALID_ARGUMENTS)?)?), + regions: arguments.map(matrix).collect::, SortError>>()?, + }) + } + _ => Node::Value(ValueNode::FnCall { name, expr: values(arguments)? }), + }) +} + +/// The sort of an operation: value·value and matrix·value are values, matrix·matrix and value·matrix are matrices, and +/// `+` joins like sorts or attaches a value to a matrix as translation. +fn binary(lhs: Node, op: BinaryOp, rhs: Node) -> Result { + use BinaryOp as Op; + Ok(match (lhs, op, rhs) { + (Node::Value(lhs), op, Node::Value(rhs)) => Node::Value(ValueNode::BinOp { + lhs: Box::new(lhs), + op, + rhs: Box::new(rhs), + }), + (Node::Matrix(matrix), Op::Mul, Node::Value(value)) => Node::Value(ValueNode::Apply { + matrix: Box::new(matrix), + value: Box::new(value), + }), + // Division is times-inverse, so a matrix over a value applies to the value's reciprocal + (Node::Matrix(matrix), Op::Div, Node::Value(value)) => Node::Value(ValueNode::Apply { + matrix: Box::new(matrix), + value: Box::new(reciprocal(value)), + }), + (Node::Matrix(lhs), Op::Eq | Op::Neq, Node::Matrix(rhs)) => Node::Value(ValueNode::MatrixComparison { + matrices: vec![lhs, rhs], + distinct: op == Op::Neq, + }), + (lhs @ Node::Value(_), Op::Mul | Op::Div | Op::Add | Op::Sub, rhs @ Node::Matrix(_)) + | (lhs @ Node::Matrix(_), Op::Mul | Op::Div | Op::Add | Op::Sub, rhs @ Node::Matrix(_)) + | (lhs @ Node::Matrix(_), Op::Add | Op::Sub | Op::Pow, rhs @ Node::Value(_)) => Node::Matrix(MatrixNode::BinOp { + lhs: Box::new(lhs), + op, + rhs: Box::new(rhs), + }), + _ => return Err(NO_MATRIX_OPERATOR), + }) +} + +fn reciprocal(value: ValueNode) -> ValueNode { + ValueNode::BinOp { + lhs: Box::new(ValueNode::Lit(Literal::Integer(1))), + op: BinaryOp::Div, + rhs: Box::new(value), + } +} + +/// A product folds left, except that a matrix meeting a value applies to the whole rest of the product, so `M 2 v` is `M (2 v)` +/// as in linear algebra rather than `(M 2) v`. +fn product(first: Node, rest: &mut std::vec::IntoIter<(BinaryOp, Syntax)>, functions: &dyn FunctionProvider) -> Result { + let mut accumulated = first; + + while let Some((op, factor)) = rest.next() { + accumulated = match (accumulated, sorted(factor, functions)?) { + (Node::Matrix(matrix), Node::Value(factor)) => { + // Dividing by a value applies the matrix to its reciprocal times the rest, so `M / v w` is `M (v⁻¹ w)` + let factor = if op == BinaryOp::Div { reciprocal(factor) } else { factor }; + + let argument = product(Node::Value(factor), rest, functions)?; + return binary(Node::Matrix(matrix), BinaryOp::Mul, argument); + } + (accumulated, factor) => binary(accumulated, op, factor)?, + }; + } + + Ok(accumulated) +} + +/// A piecewise takes the sort of its cases, which must agree, under conditions that are values. +fn piecewise(cases: Vec, otherwise: Option>, functions: &dyn FunctionProvider) -> Result { + let cases = cases + .into_iter() + .map(|Case { value: case, condition }| Ok((sorted(case, functions)?, value(sorted(condition, functions)?)?))) + .collect::, SortError>>()?; + let otherwise = otherwise.map(|otherwise| sorted(*otherwise, functions)).transpose()?; + + let first = cases.first().map(|(case, _)| case).or(otherwise.as_ref()); + if first.is_some_and(|first| matches!(first, Node::Matrix(_))) { + let cases = cases + .into_iter() + .map(|(case, condition)| { + Ok(SortedCase { + value: matrix(case).map_err(|_| MIXED_CASES)?, + condition, + }) + }) + .collect::, SortError>>()?; + let otherwise = otherwise.map(|otherwise| matrix(otherwise).map_err(|_| MIXED_CASES)).transpose()?.map(Box::new); + return Ok(Node::Matrix(MatrixNode::Piecewise { cases, otherwise })); + } + + let cases = cases + .into_iter() + .map(|(case, condition)| { + Ok(SortedCase { + value: value(case).map_err(|_| MIXED_CASES)?, + condition, + }) + }) + .collect::, SortError>>()?; + let otherwise = otherwise.map(|otherwise| value(otherwise).map_err(|_| MIXED_CASES)).transpose()?.map(Box::new); + Ok(Node::Value(ValueNode::Piecewise { cases, otherwise })) +} diff --git a/libraries/math-parser/src/value.rs b/libraries/math-parser/src/value.rs index 34927dc7f6..947bf9ba4e 100644 --- a/libraries/math-parser/src/value.rs +++ b/libraries/math-parser/src/value.rs @@ -479,6 +479,7 @@ impl Number { Number::Quaternion(quaternion) => Number::Quaternion(-quaternion), }), UnaryOp::Not => self.as_bool().map(|boolean| Number::from_bool(!boolean)), + UnaryOp::Transpose => None, UnaryOp::Magnitude => Some(match self { Number::Integer(integer) => i64::try_from(integer.unsigned_abs()).map_or(Number::Real(integer.unsigned_abs() as f64), Number::Integer), _ => Number::Real(self.magnitude()), diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 1753f1cb95..adb69c61e3 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -3,13 +3,15 @@ use core_types::context::{CloneVarArgs, ExtractAll}; use core_types::list::{Bundle, Item, List}; use core_types::transform::Footprint; use core_types::{Color, Ctx, OwnedContextImpl, num_traits}; -use glam::{DAffine2, DVec2}; +use glam::{DAffine2, DMat2, DVec2}; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::{Artboard, Graphic, Vector}; use log::warn; use math_parser::ast; use math_parser::context::{EvalContext, NothingMap, ValueProvider}; use math_parser::lexer::Constant; +use math_parser::matrix::{Affine2, Linear2, Matrix}; +use math_parser::object::Object; use math_parser::reducer::classify_reducer; use math_parser::value::{Value, Vector2, Vector3}; use rand::{Rng, SeedableRng}; @@ -49,9 +51,9 @@ impl ParseCache { } /// Evaluates a parsed expression with the given variable bindings, logging and returning `None` on failure. -fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> Option { +fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> Option { match expression.eval(&EvalContext::new(provider, NothingMap)) { - Ok(value) => Some(value), + Ok(object) => Some(object), Err(error) => { warn!("Expression evaluation error: {error:?}"); None @@ -59,20 +61,55 @@ fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> } } -/// Converts a node item type to and from the values the expression evaluator runs in. +/// Converts a node item type to and from the objects, values or matrices, the expression evaluator runs on. trait ExpressionValue: Copy + Default { + fn into_object(self) -> Object; + /// Reads an evaluated result as this type, seeing only the parts this type has, or `None` when it does not fit, like 0.5 read as a Bool or a matrix read as a Number. + fn from_object(object: &Object) -> Option; + /// Gathers a list of this type as the items of its sort. + fn items(items: impl Iterator) -> Items; +} + +/// The items of the "Math f(…)" node's list, of one sort throughout, bound positionally as `a`, `b`, `c` or as `A`, `B`, `C`. +enum Items { + Values(Vec), + Matrices(Vec), +} + +impl Items { + fn len(&self) -> usize { + match self { + Self::Values(values) => values.len(), + Self::Matrices(matrices) => matrices.len(), + } + } +} + +/// A node item type that is a value in the expression language, so a list of them binds positionally. +trait ExpressionItem: Copy + Default { /// Binds this value into the expression language, exactly for an integer. fn into_value(self) -> Value; - /// Reads an evaluated result as this type, seeing only the parts this type has, or `None` when it does not fit, like 0.5 read as a Bool. fn from_value(value: &Value) -> Option; } +impl ExpressionValue for T { + fn into_object(self) -> Object { + Object::Value(self.into_value()) + } + fn from_object(object: &Object) -> Option { + T::from_value(object.as_value()?) + } + fn items(items: impl Iterator) -> Items { + Items::Values(items.map(T::into_value).collect()) + } +} + /// The value's real part alone, the only part a scalar type has, keeping an integer's exact storage. fn real_part(value: &Value) -> Value { if value.as_real().is_some() { *value } else { Value::from_f64(value.as_particle3().w) } } -impl ExpressionValue for f64 { +impl ExpressionItem for f64 { fn into_value(self) -> Value { Value::from_f64(self) } @@ -82,19 +119,19 @@ impl ExpressionValue for f64 { } /// Reads an expression's result into the node's output type, warning and falling back to the type's default when it does not fit. -fn output(result: Option) -> T { +fn output(result: Option) -> T { result - .and_then(|value| { - let output = T::from_value(&value); + .and_then(|object| { + let output = T::from_object(&object); if output.is_none() { - warn!("The expression's result {value} does not fit the output type"); + warn!("The expression's result {object} does not fit the output type"); } output }) .unwrap_or_default() } -impl ExpressionValue for i64 { +impl ExpressionItem for i64 { fn into_value(self) -> Value { Value::from_i64(self) } @@ -105,7 +142,7 @@ impl ExpressionValue for i64 { } } -impl ExpressionValue for bool { +impl ExpressionItem for bool { fn into_value(self) -> Value { Value::from_bool(self) } @@ -116,7 +153,7 @@ impl ExpressionValue for bool { } } -impl ExpressionValue for DVec2 { +impl ExpressionItem for DVec2 { fn into_value(self) -> Value { Value::from(Vector2(self.to_array())) } @@ -128,33 +165,68 @@ impl ExpressionValue for DVec2 { } } -/// Supplies the value of `x` for the "Math f(x)" node's expression. +/// A transform as the `i, j` block with its translation. +fn transform_matrix(transform: DAffine2) -> Matrix { + Matrix::from(Affine2 { + linear: Linear2(transform.matrix2.to_cols_array_2d()), + translation: transform.translation.to_array(), + }) +} + +impl ExpressionValue for DAffine2 { + fn into_object(self) -> Object { + Object::from(transform_matrix(self)) + } + + // A map of the plane leaving the weight and `z` alone, which no other matrix fits + fn from_object(object: &Object) -> Option { + let Affine2 { + linear: Linear2(columns), + translation, + } = object.as_matrix()?.as_affine2()?; + Some(DAffine2::from_mat2_translation(DMat2::from_cols_array_2d(&columns), DVec2::from_array(translation))) + } + + fn items(items: impl Iterator) -> Items { + Items::Matrices(items.map(transform_matrix).collect()) + } +} + +/// Supplies the value of `x`, or the matrix of `X`, for the "Math f(x)" node's expression. struct SingleVariableMathContext { - x: Value, + x: Object, } impl ValueProvider for SingleVariableMathContext { fn get_value(&self, name: &str) -> Option { // Bound by exact spelling, per the language's rule that a binding shadows the builtin of exactly its spelling - (name == "x").then_some(self.x) + (name == "x").then(|| self.x.as_value().copied()).flatten() + } + + fn get_matrix(&self, name: &str) -> Option { + (name == "X").then(|| self.x.as_matrix().copied()).flatten() } } -/// Evaluates a math expression written in terms of the single variable `x`, which carries the input value. +/// Evaluates a math expression written in terms of the single variable `x`, which carries the input value, or `X` when the input is a Transform. /// -/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, and a Vec2 takes the X and Y of a vector like `3i + 4j`. A boolean input reads as 0 or 1 and a Vec2 input as such a vector. +/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. A boolean input reads as 0 or 1 and a Vec2 input as such a vector. #[node_macro::node(name("Math f(x)"), category("Math: Arithmetic"))] fn math_fx( _: impl Ctx, /// The value passed into the expression as `x`. - #[implementations(f64, f64, f64, f64, i64, i64, i64, i64, bool, bool, bool, bool, DVec2, DVec2, DVec2, DVec2)] + #[implementations( + f64, f64, f64, f64, f64, i64, i64, i64, i64, i64, bool, bool, bool, bool, bool, DVec2, DVec2, DVec2, DVec2, DVec2, DAffine2, DAffine2, DAffine2, DAffine2, DAffine2 + )] value: Item, - /// The expression evaluated for the input value, in terms of `x`, such as `4sin(x/2)`. + /// The expression evaluated for the input value, in terms of `x`, such as `4sin(x/2)`, or of `X` for a Transform. #[name("f(x) =")] #[default("x")] fx: Item, /// The type the result is read as. - #[implementations(f64, i64, bool, DVec2, f64, i64, bool, DVec2, f64, i64, bool, DVec2, f64, i64, bool, DVec2)] + #[implementations( + f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2 + )] #[widget(ParsedWidgetOverride::Custom = "type_choice")] #[name("Output Type")] output_type: Item, @@ -165,55 +237,70 @@ fn math_fx( let (value, attributes) = value.into_parts(); - let x = value.into_value(); - let result = output(parsed.parse(fx.element()).and_then(|expression| evaluate_expression(&expression, SingleVariableMathContext { x }))); + let x = value.into_object(); + + // The default `x` passes any input through, including a Transform, which an expression names `X` + let source = if x.as_matrix().is_some() && fx.element().trim() == "x" { "X" } else { fx.element() }; + let result = output(parsed.parse(source).and_then(|expression| evaluate_expression(&expression, SingleVariableMathContext { x }))); Item::from_parts(result, attributes) } -/// Binds the items of the "Math f(…)" node's list to the positional variables `a`, `b`, `c`, and so on. +/// Binds the items of the "Math f(…)" node's list to the positional variables `a`, `b`, `c`, and so on, or `A`, `B`, `C` for matrices. struct PositionalMathContext { - items: Vec, + items: Items, +} + +/// The position a single-letter name of the given case binds, `a` or `A` being the first. +fn position(name: &str, is_letter_case: fn(&char) -> bool) -> Option { + let mut characters = name.chars(); + let letter = characters.next()?; + (characters.next().is_none() && is_letter_case(&letter)).then(|| (letter.to_ascii_lowercase() as u8 - b'a') as usize) } impl ValueProvider for PositionalMathContext { fn get_value(&self, name: &str) -> Option { - let mut characters = name.chars(); - let letter = characters.next()?; - if characters.next().is_some() || !letter.is_ascii_lowercase() { - return None; - } + let Items::Values(items) = &self.items else { return None }; // A wired item shadows the constant spelled by its letter (`e` as the fifth item, `i` as the ninth), which stay reachable // as `\e` and `\i`; an unwired letter reads as its default of 0, except that a constant's letter stays the constant - let index = (letter as u8 - b'a') as usize; - match self.items.get(index) { + match items.get(position(name, char::is_ascii_lowercase)?) { Some(item) => Some(*item), None if Constant::from_name(name).is_some() => None, None => Some(Value::from_i64(0)), } } + + fn get_matrix(&self, name: &str) -> Option { + let Items::Matrices(items) = &self.items else { return None }; + + // Likewise `I` as the ninth item shadows the identity, and an unwired letter reads as a Transform's default, the identity + Some(items.get(position(name, char::is_ascii_uppercase)?).copied().unwrap_or(Matrix::IDENTITY)) + } } -/// Evaluates a math expression across all of the input items at once. A full expression reads the items as `a`, `b`, `c`, …, while a math operator or N-argument function name (like `*` or `min`) applies across every item. +/// Evaluates a math expression across all of the input items at once. A full expression reads the items as `a`, `b`, `c`, …, or as `A`, `B`, `C`, … for Transforms, while a math operator or N-argument function name (like `*` or `min`) applies across every item. /// -/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, and a Vec2 takes the X and Y of a vector like `3i + 4j`. Boolean items read as 0 or 1 and Vec2 items as such vectors. +/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts. #[node_macro::node(name("Math f(…)"), category("Math: Arithmetic"))] fn math_f( _: impl Ctx, /// The items the expression reads. #[implementations( - List, List, List, List, - List, List, List, List, - List, List, List, List, - List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, + List, List, List, List, List, )] values: List, /// The expression evaluated over the items, such as `a * b + c`, or a lone operator or function applied across all of them. #[name("f(…) =")] f: Item, /// The type the result is read as. - #[implementations(f64, i64, bool, DVec2, f64, i64, bool, DVec2, f64, i64, bool, DVec2, f64, i64, bool, DVec2)] + #[implementations( + f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2 + )] #[widget(ParsedWidgetOverride::Custom = "type_choice")] #[name("Output Type")] output_type: Item, @@ -223,12 +310,17 @@ fn math_f( let _ = output_type; let expression = f.element(); - let items: Vec = values.iter_element_values().map(|&value| value.into_value()).collect(); - let bindings = PositionalMathContext { items }; + let bindings = PositionalMathContext { + items: T::items(values.iter_element_values().copied()), + }; // A lone operator or variadic function name applies across all items rather than parsing as an expression if let Some(reducer) = classify_reducer(expression, &bindings) { - let Some(result) = reducer.evaluate(&bindings.items) else { + let result = match &bindings.items { + Items::Values(values) => reducer.evaluate(values).map(Object::Value), + Items::Matrices(matrices) => reducer.evaluate_matrices(matrices), + }; + let Some(result) = result else { warn!("The `{expression}` reducer cannot be applied to {} items", bindings.items.len()); return Item::new_from_element(U::default()); }; @@ -2093,6 +2185,52 @@ mod test { assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("xor".to_string()), as_bool).into_element()); } + #[test] + fn test_transform_items() { + fn fx(value: T, expression: &str, output_type: U) -> U { + math_fx( + (), + &ParseCache::default(), + Item::new_from_element(value), + Item::new_from_element(expression.to_string()), + Item::new_from_element(output_type), + ) + .into_element() + } + let shear = DAffine2::from_cols(DVec2::new(1., 0.), DVec2::new(0.5, 1.), DVec2::new(5., 4.)); + + // A Transform binds as `X`, and a matrix result reads back as one, so the default `x` passes it through + assert_eq!(fx(shear, "x", shear), shear); + assert_eq!(fx(shear, "X (2i + 2j)", DVec2::ZERO), DVec2::new(8., 6.)); + assert_eq!(fx(shear, "X^-1 X", shear), DAffine2::IDENTITY); + assert_eq!(fx(shear, "linear(X) + 1i", DAffine2::IDENTITY), DAffine2::from_cols(DVec2::new(1., 0.), DVec2::new(0.5, 1.), DVec2::X)); + assert_eq!(fx(2., "rotation(pi/2) + x i", DAffine2::IDENTITY).translation, DVec2::new(2., 0.)); + assert_eq!(fx(shear, "det(X)", 0.), 1.); + + // A value, or a matrix touching the weight, is no Transform, so the output falls back to its default + assert_eq!(fx(shear, "X 0", DAffine2::IDENTITY), DAffine2::IDENTITY); + assert_eq!(fx(shear, "[1;i] + X 0", DAffine2::IDENTITY), DAffine2::IDENTITY); + + // A Transform list binds as `A`, `B`, `C`, and a lone operator composes, averages, or counts across it + let scale = DAffine2::from_scale(DVec2::splat(2.)); + fn f(items: [DAffine2; 2], expression: &str, output_type: U) -> U { + let items: List = items.into_iter().map(Item::new_from_element).collect(); + math_f((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)).into_element() + } + assert_eq!(f([shear, scale], "A B", DAffine2::IDENTITY), shear * scale); + assert_eq!(f([shear, scale], "A C", DAffine2::IDENTITY), shear); + assert_eq!(f([shear, scale], "*", DAffine2::IDENTITY), shear * scale); + assert_eq!(f([shear, scale], "/", DAffine2::IDENTITY), shear * scale.inverse()); + assert_eq!(f([shear, scale], "mean", DAffine2::IDENTITY).translation, DVec2::new(2.5, 2.)); + assert_eq!(f([shear, scale], "count", 0.), 2.); + assert_eq!(f([shear, scale], "det(A)", 0.), 1.); + assert_eq!(f([shear, scale], "min", DAffine2::IDENTITY), DAffine2::IDENTITY); + assert_eq!(f([shear, scale], "a", DAffine2::IDENTITY), DAffine2::IDENTITY); + + // A sum of Transforms doubles the weight row, so it reads as no Transform and the output falls back to its default + assert_eq!(f([shear, scale], "+", DAffine2::IDENTITY), DAffine2::IDENTITY); + } + #[test] fn test_vec2_items() { fn fx(value: T, expression: &str, output_type: U) -> U {