Skip to main content

formula_lang/
lib.rs

1//! Spreadsheet formula language — tokenizer, Pratt parser, AST, evaluator
2//! core. Excel-compatible function semantics.
3//!
4//! `formula-lang` is the estate's **L0 leaf** for spreadsheet work: a pure,
5//! total formula engine with no I/O and no cell storage. Host engines
6//! implement the [`CellResolver`] trait (a sheet, a sparse map, a replay
7//! fixture); the crate turns formula text into typed results.
8//!
9//! ```
10//! use formula_lang::{parse, evaluate, MapResolver, Value};
11//!
12//! // A tiny sheet: A1=2, B1=3, C1 text.
13//! let mut sheet = MapResolver::new();
14//! sheet.set_num(1, 1, 2.0);
15//! sheet.set_num(2, 1, 3.0);
16//! sheet.set_text(3, 1, "unit");
17//!
18//! let e = parse("=SUM(A1:B1) * 10 & \" \" & C1").unwrap();
19//! assert_eq!(
20//!     evaluate(&e, &sheet).unwrap(),
21//!     Value::Text("50 unit".to_string())
22//! );
23//! ```
24//!
25//! # The pipeline
26//!
27//! 1. [`tokenize`] — `&str` in, zero-copy [`Token`]s out (`&[u8]`-backed
28//!    slices of the input; the one allocation is the token vector).
29//! 2. [`parse`] — a Pratt parser over the Excel precedence ladder
30//!    (comparison < concat < add < mul < **right-assoc** power < unary <
31//!    postfix `%`), producing the [`Expr`] AST.
32//! 3. [`evaluate`] — a depth-capped, allocation-light evaluator over a
33//!    [`CellResolver`]; [`evaluate_with_clock`] pins "now" for the
34//!    volatile functions.
35//! 4. [`Display for Expr`](Expr#impl-Display) / [`to_formula`] —
36//!    precedence-correct serialization (round-trip property-tested).
37//!
38//! # Excel compatibility, stated precisely
39//!
40//! - **Precedence & the unary quirk**: `-2^2` is `(-2)^2` = `4` — prefix
41//!   unary binds *tighter* than power, as Excel does (and unlike school
42//!   math). `2^-3` still parses; `^` is right-associative (`2^3^2` =
43//!   `512`).
44//! - **Coercions**: arithmetic coerces bool→1/0, numeric text→number,
45//!   empty→0; comparisons rank Number < Text < Boolean and never
46//!   cross-coerce (`"1" = 1` is FALSE); text compares case-insensitively;
47//!   empty substitutes the other side's zero.
48//! - **Errors**: the seven `#…!` values propagate as data;
49//!   `IFERROR`/`IFNA`/`ISERROR`/`ISNA` catch them. Two documented
50//!   divergences: *unknown function names* are a hard
51//!   [`FormulaError::UnknownFunction`] rather than `#NAME?` (typed over
52//!   forgiving), and a bare range used as a scalar (`=A1:B2`) is
53//!   `#VALUE!` rather than a spill (scalar core).
54//! - **Rounding**: `ROUND` is half-away-from-zero; `INT` floors (−∞);
55//!   `TRUNC`/`ROUNDDOWN` truncate; `MOD` takes the divisor's sign;
56//!   `CEILING`/`FLOOR` carry Excel's significance-sign rules.
57//! - **Text**: UTF-16 code-unit indexing (`LEN("𐍈")` = 2); `TRIM` only
58//!   ever touches U+0020; `SEARCH` honors wildcards, `FIND` does not;
59//!   cell text caps at 32767 units (`REPT` overflows to `#VALUE!`).
60//! - **Dates**: the Lotus leap bug is preserved — serial 60 is the
61//!   phantom 1900-02-29; 1970-01-01 is serial 25569.
62//! - **Volatile functions**: `TODAY`, `NOW`, `OFFSET` — reported by
63//!   [`is_volatile`], clocked by [`evaluate_with_clock`].
64//!
65//! # The omitted-argument marker
66//!
67//! The public AST has no "omitted" variant, so empty argument slots
68//! (`IF(A1,,5)`, `SUM(1,)`) are stored as
69//! [`Expr::Error`]`(`[`ExcelError::Null`]`)` and detected with
70//! [`is_omitted_arg`]. Two documented trade-offs: a literal `#NULL!` in a
71//! direct argument position is treated as omitted, and a call whose
72//! arguments are a *single* omitted slot renders back as `F()` (the
73//! grammar cannot express one empty slot — `F(,)` parses as two). Outside
74//! argument positions the marker is inert.
75//!
76//! # Safety & totality
77//!
78//! `#![no_std]` + `alloc`; `unsafe_code = deny`; `unwrap`/`expect`/
79//! `panic`/indexing deny-linted on the lib target. Parsing and evaluation
80//! are **total**: hostile input (fuzz-verified) yields typed errors —
81//! including [`FormulaError::RecursionLimit`] past [`MAX_DEPTH`] nesting —
82//! never a panic, never a stack overflow.
83//!
84//! # Allocation discipline
85//!
86//! The numeric scalar path (operators, coercions, all arithmetic and
87//! comparison functions) allocates nothing — coercion happens through
88//! `f64` locals, and results are returned unboxed. The allocating edges
89//! are exactly where ownership forces them: text results (owned
90//! `String`s), aggregate operand vectors, range materialization (the
91//! resolver's policy — see [`CellResolver::get_range`]), and the
92//! parse-path's token vector and AST nodes.
93
94#![no_std]
95#![warn(missing_docs)]
96
97extern crate alloc;
98
99#[cfg(feature = "std")]
100extern crate std;
101
102pub mod ast;
103pub mod date;
104pub mod display;
105pub mod error;
106pub mod eval;
107pub mod funcs;
108pub mod lexer;
109pub mod parser;
110pub mod resolver;
111pub mod token;
112pub mod value;
113
114pub use crate::ast::{
115    col_name, col_number, is_omitted_arg, normalize_range, BinaryOp, CellRef, Expr, UnaryOp,
116    MAX_COL, MAX_ROW,
117};
118pub use crate::display::{to_formula, to_formula as to_string};
119pub use crate::error::{ExcelError, FormulaError};
120pub use crate::eval::{evaluate, evaluate_with_clock, is_volatile};
121pub use crate::funcs::builtin_functions;
122pub use crate::lexer::tokenize;
123pub use crate::parser::parse;
124pub use crate::parser::MAX_DEPTH;
125pub use crate::resolver::{CellResolver, EmptyResolver, MapResolver};
126pub use crate::token::{Token, TokenKind};
127pub use crate::value::Value;
128
129/// Crate version, for host diagnostics.
130pub const VERSION: &str = env!("CARGO_PKG_VERSION");
131
132#[cfg(test)]
133mod tests {
134    #![allow(
135        clippy::unwrap_used,
136        clippy::expect_used,
137        clippy::panic,
138        clippy::indexing_slicing
139    )]
140
141    use super::*;
142    use crate::alloc::string::ToString;
143
144    #[test]
145    fn readme_example() {
146        let mut sheet = MapResolver::new();
147        sheet.set_num(1, 1, 2.0);
148        sheet.set_num(2, 1, 3.0);
149        sheet.set_text(3, 1, "unit");
150        let e = parse("=SUM(A1:B1) * 10 & \" \" & C1").unwrap();
151        assert_eq!(
152            evaluate(&e, &sheet).unwrap(),
153            Value::Text("50 unit".to_string())
154        );
155    }
156
157    #[test]
158    fn excel_quirks_hold() {
159        let empty = EmptyResolver;
160        let ev = |s: &str| evaluate(&parse(s).unwrap(), &empty).unwrap();
161        // Unary binds tighter than ^ (Excel quirk).
162        assert_eq!(ev("-2^2"), Value::Number(4.0));
163        // Right-associative power.
164        assert_eq!(ev("2^3^2"), Value::Number(512.0));
165        // Postfix percent binds tightest.
166        assert_eq!(ev("50%*2"), Value::Number(1.0));
167        // Cross-type comparison is ranked, not coerced.
168        assert_eq!(ev("1=\"1\""), Value::Boolean(false));
169        // Text equality is case-insensitive.
170        assert_eq!(ev("\"a\"=\"A\""), Value::Boolean(true));
171        // Half-away-from-zero rounding.
172        assert_eq!(ev("ROUND(2.5,0)"), Value::Number(3.0));
173        assert_eq!(ev("ROUND(-2.5,0)"), Value::Number(-3.0));
174        // MOD takes the divisor's sign.
175        assert_eq!(ev("MOD(-3,2)"), Value::Number(1.0));
176        // The Lotus leap bug: serial 60 is the phantom 1900-02-29.
177        assert_eq!(
178            ev("TEXT(60,\"yyyy-mm-dd\")"),
179            Value::Text("1900-02-29".to_string())
180        );
181    }
182}