1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
pub mod context;
pub mod coercion;
pub mod functions;
pub mod resolver;
pub use context::Context;
pub use functions::{EvalCtx, FunctionMeta, Registry};
pub use resolver::{extract_refs, Resolver};
use crate::parser::ast::{BinaryOp, Expr, UnaryOp};
use crate::types::{ErrorKind, Value};
use coercion::{to_number, to_string_val};
use functions::FunctionKind;
/// Walk an expression tree and produce a [`Value`].
///
/// Variables are resolved from `ctx.ctx`; functions are dispatched through
/// `ctx.registry`. Eager functions receive pre-evaluated arguments; lazy
/// functions (e.g. `IF`) receive raw [`Expr`] nodes and control their own
/// evaluation order.
pub fn evaluate_expr(expr: &Expr, ctx: &mut EvalCtx<'_>) -> Value {
match expr {
// ── Leaf nodes ──────────────────────────────────────────────────────
Expr::Number(n, _) => {
if n.is_finite() {
Value::Number(*n)
} else {
Value::Error(ErrorKind::Num)
}
}
Expr::Text(s, _) => Value::Text(s.clone()),
Expr::Bool(b, _) => Value::Bool(*b),
// Bare identifiers: a local binding (LAMBDA parameter, caller-supplied
// variable, or canonical-text variable) wins; otherwise the name is
// classified into a `Ref` and read through the resolver (P1.3, #525).
Expr::Variable(name, _) => match ctx.ctx.lookup(name) {
Some(v) => v,
None => ctx.resolve_ref(&crate::parser::refs::Ref::classify(name)),
},
// Sheet-qualified references: a binding under the canonical reference
// text wins (back-compat with variable-supplied refs); otherwise the
// reference is read through the resolver.
Expr::Reference(r, _) => match ctx.ctx.lookup(&r.to_string()) {
Some(v) => v,
None => ctx.resolve_ref(r),
},
// ── Unary ops ───────────────────────────────────────────────────────
Expr::UnaryOp { op, operand, .. } => {
let val = evaluate_expr(operand, ctx);
match to_number(val) {
Err(e) => e,
Ok(n) => match op {
UnaryOp::Neg => Value::Number(-n),
UnaryOp::Percent => Value::Number(n / 100.0),
},
}
}
// ── Binary ops ──────────────────────────────────────────────────────
Expr::BinaryOp { op, left, right, .. } => {
let lv = evaluate_expr(left, ctx);
let rv = evaluate_expr(right, ctx);
eval_binary(op, lv, rv)
}
// ── Array literals ──────────────────────────────────────────────────
Expr::Array(elems, _) => {
let mut values = Vec::with_capacity(elems.len());
for elem in elems {
let v = evaluate_expr(elem, ctx);
values.push(v);
}
Value::Array(values)
}
// ── Immediately-invoked apply: LAMBDA(x, body)(arg) ────────────────
Expr::Apply { func, call_args, .. } => {
eval_apply(func, call_args, ctx)
}
// ── Function calls ──────────────────────────────────────────────────
Expr::FunctionCall { name, args, .. } => {
match ctx.registry.get(name) {
None => Value::Error(ErrorKind::Name),
Some(FunctionKind::Lazy(f)) => {
// Copy the fn pointer out to avoid holding a borrow on ctx.registry
// while also mutably borrowing ctx itself.
let f: functions::LazyFn = *f;
f(args, ctx)
}
Some(FunctionKind::Eager(f)) => {
let f: functions::EagerFn = *f;
// Evaluate all args; return first error encountered.
let mut evaluated = Vec::with_capacity(args.len());
for arg in args {
let v = evaluate_expr(arg, ctx);
if matches!(v, Value::Error(_)) {
return v;
}
evaluated.push(v);
}
f(&evaluated)
}
}
}
}
}
/// Evaluate an immediately-invoked function application `func(call_args)`.
fn eval_apply(func: &Expr, call_args: &[Expr], ctx: &mut EvalCtx<'_>) -> Value {
let (lambda_params, body) = match func {
Expr::FunctionCall { name, args: lambda_args, .. } if name == "LAMBDA" => {
if lambda_args.is_empty() {
return Value::Error(ErrorKind::NA);
}
let param_count = lambda_args.len() - 1;
let mut params: Vec<String> = Vec::with_capacity(param_count);
for param_expr in &lambda_args[..param_count] {
match param_expr {
Expr::Variable(n, _) => params.push(n.to_uppercase()),
_ => return Value::Error(ErrorKind::Name),
}
}
let body = &lambda_args[lambda_args.len() - 1];
(params, body)
}
_ => return Value::Error(ErrorKind::Value),
};
if call_args.len() != lambda_params.len() {
return Value::Error(ErrorKind::NA);
}
let mut evaluated_args: Vec<Value> = Vec::with_capacity(call_args.len());
for arg in call_args {
let v = evaluate_expr(arg, ctx);
if matches!(v, Value::Error(_)) {
return v;
}
evaluated_args.push(v);
}
let mut saved: Vec<(String, Option<Value>)> = Vec::with_capacity(lambda_params.len());
for (param, val) in lambda_params.iter().zip(evaluated_args) {
let old = ctx.ctx.set(param.clone(), val);
saved.push((param.clone(), old));
}
let result = evaluate_expr(body, ctx);
for (name, old_val) in saved.into_iter().rev() {
match old_val {
Some(v) => { ctx.ctx.set(name, v); }
None => { ctx.ctx.remove(&name); }
}
}
result
}
// ── Type ordering for cross-type comparisons (Excel semantics) ───────────────
// Number < Text < Bool (Empty counts as Number)
fn type_rank(v: &Value) -> u8 {
match v {
Value::Number(_) | Value::Date(_) | Value::Empty | Value::Zoned(_) => 0,
Value::Text(_) => 1,
Value::Bool(_) => 2,
// Error and Array cannot reach compare_values through the normal eval path
// (eval_binary guards against errors before calling compare_values).
Value::Error(_) | Value::Array(_) => 3,
}
}
fn eval_binary(op: &BinaryOp, lv: Value, rv: Value) -> Value {
// ── Array broadcasting ───────────────────────────────────────────────────
match (&lv, &rv) {
(Value::Array(lelems), Value::Array(relems)) => {
// Element-wise operation when both operands are arrays of the same length.
if lelems.len() != relems.len() {
return Value::Error(ErrorKind::Value);
}
let result: Vec<Value> = lelems
.iter()
.zip(relems.iter())
.map(|(l, r)| eval_binary(op, l.clone(), r.clone()))
.collect();
return Value::Array(result);
}
(Value::Array(elems), _) => {
let result: Vec<Value> = elems
.iter()
.map(|e| eval_binary(op, e.clone(), rv.clone()))
.collect();
return Value::Array(result);
}
(_, Value::Array(elems)) => {
let result: Vec<Value> = elems
.iter()
.map(|e| eval_binary(op, lv.clone(), e.clone()))
.collect();
return Value::Array(result);
}
_ => {}
}
match op {
// ── Arithmetic ──────────────────────────────────────────────────────
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow => {
// Date-type production (schema spec §6: date-typed iff the fixtures
// pipeline observes Sheets producing a Date). Observed: date ± offset
// via `+` stays date-typed (workbook.tsv `=DATE(2026,6,7)+1` → date);
// date − date is a plain number (`=DATE(2026,6,7)-DATE(2026,6,1)` → 6,
// `=TODAY()-TODAY()` → 0, both typed number). Everything else —
// including date − number, ×, ÷, ^ — stays a plain number until a
// fixture observes otherwise.
let date_typed_add = matches!(op, BinaryOp::Add)
&& matches!(lv, Value::Date(_)) != matches!(rv, Value::Date(_));
let ln = match to_number(lv) { Ok(n) => n, Err(e) => return e };
let rn = match to_number(rv) { Ok(n) => n, Err(e) => return e };
let result = match op {
BinaryOp::Add => ln + rn,
BinaryOp::Sub => ln - rn,
BinaryOp::Mul => ln * rn,
BinaryOp::Div => {
if rn == 0.0 {
return Value::Error(ErrorKind::DivByZero);
}
ln / rn
}
BinaryOp::Pow => libm::pow(ln, rn),
// Safety: outer match arm covers exactly Add|Sub|Mul|Div|Pow; Concat and comparison ops are handled separately.
_ => unreachable!(),
};
if !result.is_finite() {
return Value::Error(ErrorKind::Num);
}
if date_typed_add {
Value::Date(result)
} else {
Value::Number(result)
}
}
// ── Concatenation ───────────────────────────────────────────────────
BinaryOp::Concat => {
let ls = match to_string_val(lv) { Ok(s) => s, Err(e) => return e };
let rs = match to_string_val(rv) { Ok(s) => s, Err(e) => return e };
Value::Text(ls + &rs)
}
// ── Comparisons ─────────────────────────────────────────────────────
BinaryOp::Eq | BinaryOp::Ne
| BinaryOp::Lt | BinaryOp::Gt
| BinaryOp::Le | BinaryOp::Ge => {
// Error propagation: left side first.
if let Value::Error(_) = &lv { return lv; }
if let Value::Error(_) = &rv { return rv; }
// Mixed naive/aware comparison is rejected (a zoned instant cannot be
// ordered against a naive value).
if matches!(&lv, Value::Zoned(_)) ^ matches!(&rv, Value::Zoned(_)) {
return Value::Error(ErrorKind::Value);
}
let result = compare_values(op, &lv, &rv);
Value::Bool(result)
}
}
}
/// Compare two (non-error) values with Excel ordering semantics.
fn compare_values(op: &BinaryOp, lv: &Value, rv: &Value) -> bool {
match (lv, rv) {
(Value::Number(a), Value::Number(b)) => apply_cmp(op, a.partial_cmp(b)),
(Value::Date(a), Value::Date(b)) => apply_cmp(op, a.partial_cmp(b)),
(Value::Date(a), Value::Number(b)) => apply_cmp(op, a.partial_cmp(b)),
(Value::Number(a), Value::Date(b)) => apply_cmp(op, a.partial_cmp(b)),
// Zoned instants compare on the absolute instant only (same moment in a
// different zone compares equal). Cross-type Zoned is rejected in eval_binary.
(Value::Zoned(a), Value::Zoned(b)) => apply_cmp(op, Some(a.utc_nanos.cmp(&b.utc_nanos))),
(Value::Text(a), Value::Text(b)) => apply_cmp(op, Some(a.cmp(b))),
(Value::Bool(a), Value::Bool(b)) => apply_cmp(op, Some(a.cmp(b))),
(Value::Empty, Value::Empty) => apply_cmp(op, Some(std::cmp::Ordering::Equal)),
// Empty acts as Number(0)
(Value::Empty, Value::Number(b)) => apply_cmp(op, 0.0f64.partial_cmp(b)),
(Value::Number(a), Value::Empty) => apply_cmp(op, a.partial_cmp(&0.0f64)),
// Cross-type: use type rank
_ => {
let lr = type_rank(lv);
let rr = type_rank(rv);
match op {
BinaryOp::Eq => false,
BinaryOp::Ne => true,
BinaryOp::Lt => lr < rr,
BinaryOp::Gt => lr > rr,
BinaryOp::Le => lr <= rr,
BinaryOp::Ge => lr >= rr,
// Safety: outer match arm covers exactly Eq|Ne|Lt|Gt|Le|Ge; arithmetic and Concat ops are handled separately.
_ => unreachable!(),
}
}
}
}
fn apply_cmp(op: &BinaryOp, ord: Option<std::cmp::Ordering>) -> bool {
match ord {
// NaN: per Value::Number invariant this should not occur after the is_finite() guard;
// returning false matches Excel semantics if it somehow does.
None => false,
Some(o) => match op {
BinaryOp::Eq => o.is_eq(),
BinaryOp::Ne => o.is_ne(),
BinaryOp::Lt => o.is_lt(),
BinaryOp::Gt => o.is_gt(),
BinaryOp::Le => o.is_le(),
BinaryOp::Ge => o.is_ge(),
// Safety: apply_cmp is only called from compare_values which is only called from eval_binary's comparison arm (Eq|Ne|Lt|Gt|Le|Ge).
_ => unreachable!(),
},
}
}
// ── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests;