Expand description
Spreadsheet formula language — tokenizer, Pratt parser, AST, evaluator core. Excel-compatible function semantics.
formula-lang is the estate’s L0 leaf for spreadsheet work: a pure,
total formula engine with no I/O and no cell storage. Host engines
implement the CellResolver trait (a sheet, a sparse map, a replay
fixture); the crate turns formula text into typed results.
use formula_lang::{parse, evaluate, MapResolver, Value};
// A tiny sheet: A1=2, B1=3, C1 text.
let mut sheet = MapResolver::new();
sheet.set_num(1, 1, 2.0);
sheet.set_num(2, 1, 3.0);
sheet.set_text(3, 1, "unit");
let e = parse("=SUM(A1:B1) * 10 & \" \" & C1").unwrap();
assert_eq!(
evaluate(&e, &sheet).unwrap(),
Value::Text("50 unit".to_string())
);§The pipeline
tokenize—&strin, zero-copyTokens out (&[u8]-backed slices of the input; the one allocation is the token vector).parse— a Pratt parser over the Excel precedence ladder (comparison < concat < add < mul < right-assoc power < unary < postfix%), producing theExprAST.evaluate— a depth-capped, allocation-light evaluator over aCellResolver;evaluate_with_clockpins “now” for the volatile functions.Display for Expr/to_formula— precedence-correct serialization (round-trip property-tested).
§Excel compatibility, stated precisely
- Precedence & the unary quirk:
-2^2is(-2)^2=4— prefix unary binds tighter than power, as Excel does (and unlike school math).2^-3still parses;^is right-associative (2^3^2=512). - Coercions: arithmetic coerces bool→1/0, numeric text→number,
empty→0; comparisons rank Number < Text < Boolean and never
cross-coerce (
"1" = 1is FALSE); text compares case-insensitively; empty substitutes the other side’s zero. - Errors: the seven
#…!values propagate as data;IFERROR/IFNA/ISERROR/ISNAcatch them. Two documented divergences: unknown function names are a hardFormulaError::UnknownFunctionrather than#NAME?(typed over forgiving), and a bare range used as a scalar (=A1:B2) is#VALUE!rather than a spill (scalar core). - Rounding:
ROUNDis half-away-from-zero;INTfloors (−∞);TRUNC/ROUNDDOWNtruncate;MODtakes the divisor’s sign;CEILING/FLOORcarry Excel’s significance-sign rules. - Text: UTF-16 code-unit indexing (
LEN("𐍈")= 2);TRIMonly ever touches U+0020;SEARCHhonors wildcards,FINDdoes not; cell text caps at 32767 units (REPToverflows to#VALUE!). - Dates: the Lotus leap bug is preserved — serial 60 is the phantom 1900-02-29; 1970-01-01 is serial 25569.
- Volatile functions:
TODAY,NOW,OFFSET— reported byis_volatile, clocked byevaluate_with_clock.
§The omitted-argument marker
The public AST has no “omitted” variant, so empty argument slots
(IF(A1,,5), SUM(1,)) are stored as
Expr::Error(ExcelError::Null) and detected with
is_omitted_arg. Two documented trade-offs: a literal #NULL! in a
direct argument position is treated as omitted, and a call whose
arguments are a single omitted slot renders back as F() (the
grammar cannot express one empty slot — F(,) parses as two). Outside
argument positions the marker is inert.
§Safety & totality
#![no_std] + alloc; unsafe_code = deny; unwrap/expect/
panic/indexing deny-linted on the lib target. Parsing and evaluation
are total: hostile input (fuzz-verified) yields typed errors —
including FormulaError::RecursionLimit past MAX_DEPTH nesting —
never a panic, never a stack overflow.
§Allocation discipline
The numeric scalar path (operators, coercions, all arithmetic and
comparison functions) allocates nothing — coercion happens through
f64 locals, and results are returned unboxed. The allocating edges
are exactly where ownership forces them: text results (owned
Strings), aggregate operand vectors, range materialization (the
resolver’s policy — see CellResolver::get_range), and the
parse-path’s token vector and AST nodes.
Re-exports§
pub use crate::ast::col_name;pub use crate::ast::col_number;pub use crate::ast::is_omitted_arg;pub use crate::ast::normalize_range;pub use crate::ast::BinaryOp;pub use crate::ast::CellRef;pub use crate::ast::Expr;pub use crate::ast::UnaryOp;pub use crate::ast::MAX_COL;pub use crate::ast::MAX_ROW;pub use crate::display::to_formula;pub use crate::display::to_formula as to_string;pub use crate::error::ExcelError;pub use crate::error::FormulaError;pub use crate::eval::evaluate;pub use crate::eval::evaluate_with_clock;pub use crate::eval::is_volatile;pub use crate::funcs::builtin_functions;pub use crate::lexer::tokenize;pub use crate::parser::parse;pub use crate::parser::MAX_DEPTH;pub use crate::resolver::CellResolver;pub use crate::resolver::EmptyResolver;pub use crate::resolver::MapResolver;pub use crate::token::Token;pub use crate::token::TokenKind;pub use crate::value::Value;
Modules§
- ast
- The abstract syntax tree.
- date
- Excel serial dates — the calendar math behind
TODAY,NOW, and the date formats ofTEXT. - display
- Serializing an
Exprback to formula text — iteratively. - error
- Typed, exhaustive error taxonomy for the formula language.
- eval
- The evaluator —
Expr+CellResolver→Value. - funcs
- The built-in function library — 63 functions, Excel-compatible semantics, one flat dispatch.
- lexer
- The tokenizer —
&strin, zero-copyTokens out. - parser
- The Pratt parser — tokens in,
Exprout. - resolver
- The cell-value abstraction — the boundary that keeps this crate a pure evaluator.
- token
- Tokens — the zero-copy lexer output.
- value
- Runtime values and Excel’s coercion rules.
Constants§
- VERSION
- Crate version, for host diagnostics.