truecalc_core/eval/functions/mod.rs
1pub mod array;
2pub mod database;
3pub mod date;
4pub mod engineering;
5pub mod filter;
6pub mod financial;
7pub mod logical;
8pub mod lookup;
9pub mod math;
10pub mod operator;
11pub mod parser;
12pub mod statistical;
13pub mod text;
14pub mod timezone;
15pub mod web;
16
17use std::collections::HashMap;
18use crate::eval::context::Context;
19use crate::eval::resolver::Resolver;
20use crate::parser::ast::{BinaryOp, Expr, Span, UnaryOp};
21use crate::types::{ErrorKind, Value};
22
23// ── EvalOp / EvalHook (per-node observation seam, issue #732; span-carrying
24// enhancement per distributions ADR D10) ────────────────────────────────────
25
26/// A lightweight, borrowed description of the operation an evaluated node
27/// performs. Handed to an [`EvalHook`] alongside the node's resulting
28/// [`Value`] so an observer can profile or trace evaluation without touching
29/// the AST directly or any function. Constructing it borrows from the
30/// expression and allocates nothing.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub enum EvalOp<'a> {
33 /// Numeric literal.
34 Number,
35 /// Text literal.
36 Text,
37 /// Boolean literal.
38 Bool,
39 /// Bare-identifier read (local binding or reference), carrying its name.
40 Variable(&'a str),
41 /// Cell / range / name reference read.
42 Reference,
43 /// Unary operator (negation, percent).
44 UnaryOp(&'a UnaryOp),
45 /// Binary operator (arithmetic, comparison, concatenation).
46 BinaryOp(&'a BinaryOp),
47 /// Array literal.
48 Array,
49 /// Immediately-invoked lambda application.
50 Apply,
51 /// Function call, carrying the (uppercased) function name.
52 FunctionCall(&'a str),
53}
54
55impl<'a> EvalOp<'a> {
56 /// Derive the operation descriptor for an expression node. Pure and
57 /// allocation-free — every variant only borrows from `expr`.
58 pub fn of(expr: &'a Expr) -> Self {
59 match expr {
60 Expr::Number(..) => EvalOp::Number,
61 Expr::Text(..) => EvalOp::Text,
62 Expr::Bool(..) => EvalOp::Bool,
63 Expr::Variable(name, _) => EvalOp::Variable(name),
64 Expr::Reference(..) => EvalOp::Reference,
65 Expr::UnaryOp { op, .. } => EvalOp::UnaryOp(op),
66 Expr::BinaryOp { op, .. } => EvalOp::BinaryOp(op),
67 Expr::Array(..) => EvalOp::Array,
68 Expr::Apply { .. } => EvalOp::Apply,
69 Expr::FunctionCall { name, .. } => EvalOp::FunctionCall(name),
70 }
71 }
72}
73
74/// An observer invoked once per evaluated node, in post-order (children before
75/// parents), with the node's [`EvalOp`], its source [`Span`], and resulting
76/// [`Value`]. Purely observational: it is handed shared/by-value data and
77/// cannot alter evaluation.
78///
79/// # Why `Span`
80///
81/// A single post-order stream is ambiguous for variable/dynamic-arity nodes
82/// (`FunctionCall`, `Array`, `Apply`; lazy `IF`/`AND`/`OR` that skip un-taken
83/// branches): a consumer cannot tell, from operation + value alone, which
84/// events belong to which parent, or how many children a node had. Carrying
85/// each node's byte-range `Span` — every `Expr` already has one — lets a
86/// consumer reconstruct the full tree from the flat stream by *span
87/// containment* (a child's span always falls inside its parent's), which is
88/// robust to short-circuiting by construction: an unfired branch simply has
89/// no event, and containment among the events that *do* fire is unaffected.
90/// The span doubles as the byte range a UI highlights to explain a node (see
91/// distributions ADR D10).
92///
93/// # Apply / LAMBDA callee (see [`EvalOp::Variable`] parameter-binding note)
94///
95/// The `LAMBDA(...)` callee of an `Apply` is pattern-destructured, not
96/// evaluated, so it never reduces to a `Value` and its own `FunctionCall`
97/// node never fires — there is no honest `Value` to give a lambda (no such
98/// [`Value`] variant exists). Each parameter *binding* does have an honest
99/// value, though (the argument bound to it), so it fires as an ordinary
100/// [`EvalOp::Variable`] event at bind time, carrying the parameter's own
101/// span and bound value — see `eval_apply`. A consumer can still recover the
102/// callee's source extent (it is a sub-span of the `Apply` node's span) but
103/// gets no discrete event, and no value, for the callee as a whole.
104///
105/// The same parameter-binding event fires for lambda parameters bound by the
106/// six higher-order array functions — MAP, REDUCE, BYROW, BYCOL, SCAN,
107/// MAKEARRAY — which route every lambda call through their own
108/// `crate::eval::functions::array::apply_lambda` helper rather than
109/// `eval_apply` (this was a gap in the initial parameter-event landing,
110/// closed as a follow-up). Each invocation of the lambda (one per array
111/// element for MAP, one per row for BYROW, one per accumulator step for
112/// REDUCE/SCAN, one per (row, col) cell for MAKEARRAY) fires one
113/// [`EvalOp::Variable`] event per parameter, all sharing that parameter's
114/// source span but each carrying the value bound for that specific
115/// invocation — so e.g. `MAP({1,2,3}, LAMBDA(x, 42))` fires three `x` events
116/// (values 1, 2, 3) even though the body never reads `x`. These are
117/// intentionally not deduplicated by span: a consumer sees one event per
118/// invocation, the same way a cell reference read inside a loop fires once
119/// per read rather than once per distinct span.
120///
121/// Blanket-implemented for every `FnMut(EvalOp<'_>, Span, &Value)`, so a
122/// closure can be wired directly. Wiring is opt-in via [`EvalCtx::hook`]:
123/// when it is `None` no descriptor is built and the only per-node cost is a
124/// single branch; when present, each node costs one `EvalOp::of`, one
125/// `Span` copy (two `usize`s), and one dynamic (vtable) call through the
126/// `&mut dyn EvalHook` trait object.
127pub trait EvalHook {
128 fn on_node(&mut self, op: EvalOp<'_>, span: Span, value: &Value);
129}
130
131impl<F: FnMut(EvalOp<'_>, Span, &Value)> EvalHook for F {
132 fn on_node(&mut self, op: EvalOp<'_>, span: Span, value: &Value) {
133 self(op, span, value)
134 }
135}
136
137// ── EvalCtx ───────────────────────────────────────────────────────────────
138
139/// Bundles the variable context, function registry, and reference resolver
140/// for use during evaluation. Passed to lazy functions so they can recursively
141/// evaluate sub-expressions.
142///
143/// References that are not bound as local variables (e.g. a LAMBDA parameter)
144/// are read through `resolver`; see [`crate::Resolver`]. When `resolver` is
145/// `None` (the default, via [`EvalCtx::new`]) every such reference reads as
146/// [`Value::Empty`], preserving the historical contract of
147/// [`crate::Engine::evaluate`].
148pub struct EvalCtx<'r> {
149 pub ctx: Context,
150 pub registry: &'r Registry,
151 /// Resolver for references not bound as local variables. `None` ⇒ such
152 /// references read as [`Value::Empty`] (the historical
153 /// [`crate::Engine::evaluate`] contract).
154 pub resolver: Option<&'r mut dyn Resolver>,
155 /// Opt-in per-node observation hook (issue #732). `None` (the default) ⇒
156 /// zero per-node work beyond a single branch; the callback only observes
157 /// and can never alter evaluation. Set the field directly to wire one.
158 pub hook: Option<&'r mut dyn EvalHook>,
159}
160
161impl<'r> EvalCtx<'r> {
162 /// Build an `EvalCtx` with no resolver: unbound references read as
163 /// [`Value::Empty`]. Use [`EvalCtx::with_resolver`] to supply real
164 /// workbook semantics.
165 pub fn new(ctx: Context, registry: &'r Registry) -> Self {
166 Self { ctx, registry, resolver: None, hook: None }
167 }
168
169 /// Build an `EvalCtx` that resolves references through `resolver`.
170 pub fn with_resolver(
171 ctx: Context,
172 registry: &'r Registry,
173 resolver: &'r mut dyn Resolver,
174 ) -> Self {
175 Self { ctx, registry, resolver: Some(resolver), hook: None }
176 }
177
178 /// Resolve a reference that was not bound as a local variable, delegating
179 /// to [`EvalCtx::resolver`] when present and falling back to
180 /// [`Value::Empty`] otherwise.
181 pub fn resolve_ref(&mut self, r: &crate::parser::refs::Ref) -> Value {
182 match self.resolver {
183 Some(ref mut res) => res.resolve(r),
184 None => Value::Empty,
185 }
186 }
187}
188
189// ── Function kinds ─────────────────────────────────────────────────────────
190
191/// A function that receives pre-evaluated arguments.
192/// Argument errors are caught before dispatch — the slice never contains `Value::Error`.
193pub type EagerFn = fn(&[Value]) -> Value;
194
195/// A function that receives raw AST nodes and controls its own evaluation order.
196/// Used for short-circuit operators like `IF`, `AND`, `OR`.
197pub type LazyFn = fn(&[Expr], &mut EvalCtx<'_>) -> Value;
198
199#[derive(Clone)]
200pub enum FunctionKind {
201 Eager(EagerFn),
202 Lazy(LazyFn),
203}
204
205// ── FunctionMeta ──────────────────────────────────────────────────────────
206
207/// Metadata for a user-facing spreadsheet function.
208/// Co-located with the registration call so it can never drift.
209#[derive(Debug, Clone)]
210pub struct FunctionMeta {
211 pub category: &'static str,
212 pub signature: &'static str,
213 pub description: &'static str,
214}
215
216/// A metadata entry returned by `Registry::get_metadata()`.
217pub struct FunctionMetaEntry<'a> {
218 pub name: &'a str,
219 pub meta: &'a FunctionMeta,
220}
221
222// ── Registry ──────────────────────────────────────────────────────────────
223
224/// The runtime registry of built-in and user-registered spreadsheet functions.
225pub struct Registry {
226 pub functions: HashMap<String, FunctionKind>,
227 pub metadata: HashMap<String, FunctionMeta>,
228}
229
230impl Registry {
231 pub fn new() -> Self {
232 let mut r = Self { functions: HashMap::new(), metadata: HashMap::new() };
233 math::register_math(&mut r);
234 logical::register_logical(&mut r);
235 text::register_text(&mut r);
236 financial::register_financial(&mut r);
237 statistical::register_statistical(&mut r);
238 operator::register_operator(&mut r);
239 date::register_date(&mut r);
240 parser::register_parser(&mut r);
241 engineering::register_engineering(&mut r);
242 filter::register_filter(&mut r);
243 array::register_array(&mut r);
244 database::register_database(&mut r);
245 lookup::register_lookup(&mut r);
246 web::register_web(&mut r);
247 timezone::register_timezone(&mut r);
248 r
249 }
250
251 /// Register a user-facing eager function with metadata.
252 /// Appears in `list_functions()`.
253 /// Panics if `name` is already registered (duplicate registration).
254 pub fn register_eager(&mut self, name: &str, f: EagerFn, meta: FunctionMeta) {
255 let key = name.to_uppercase();
256 assert!(
257 !self.functions.contains_key(&key),
258 "duplicate function registration: '{}'",
259 key
260 );
261 self.functions.insert(key.clone(), FunctionKind::Eager(f));
262 self.metadata.insert(key, meta);
263 }
264
265 /// Register a user-facing lazy function with metadata.
266 /// Appears in `list_functions()`.
267 /// Panics if `name` is already registered (duplicate registration).
268 pub fn register_lazy(&mut self, name: &str, f: LazyFn, meta: FunctionMeta) {
269 let key = name.to_uppercase();
270 assert!(
271 !self.functions.contains_key(&key),
272 "duplicate function registration: '{}'",
273 key
274 );
275 self.functions.insert(key.clone(), FunctionKind::Lazy(f));
276 self.metadata.insert(key, meta);
277 }
278
279 /// Register `alias` as an alternate name for `canonical`.
280 /// The alias shares the same handler but does NOT appear in function metadata
281 /// (it will not show up in `list_functions()` or autocomplete).
282 /// Panics if `alias` is already registered or `canonical` is not yet registered.
283 pub fn register_alias(&mut self, alias: &str, canonical: &str) {
284 let alias_key = alias.to_uppercase();
285 let canonical_key = canonical.to_uppercase();
286 assert!(
287 !self.functions.contains_key(&alias_key),
288 "duplicate function registration: '{}'",
289 alias_key
290 );
291 let kind = self
292 .functions
293 .get(&canonical_key)
294 .unwrap_or_else(|| {
295 panic!(
296 "register_alias: canonical '{}' must be registered before alias '{}'",
297 canonical_key, alias_key
298 )
299 })
300 .clone();
301 self.functions.insert(alias_key, kind);
302 // Intentionally no metadata entry — aliases are not user-facing
303 }
304
305 /// Register an internal/compiler-only eager function without metadata.
306 /// Never appears in `list_functions()`.
307 pub fn register_internal(&mut self, name: &str, f: EagerFn) {
308 self.functions.insert(name.to_uppercase(), FunctionKind::Eager(f));
309 }
310
311 /// Register an internal/compiler-only lazy function without metadata.
312 /// Never appears in `list_functions()`.
313 pub fn register_internal_lazy(&mut self, name: &str, f: LazyFn) {
314 self.functions.insert(name.to_uppercase(), FunctionKind::Lazy(f));
315 }
316
317 pub fn get(&self, name: &str) -> Option<&FunctionKind> {
318 self.functions.get(&name.to_uppercase())
319 }
320
321 /// Iterate all user-facing functions with their metadata.
322 /// The registry is the single source of truth — this can never drift.
323 pub fn list_functions(&self) -> impl Iterator<Item = (&str, &FunctionMeta)> {
324 self.metadata.iter().map(|(k, v)| (k.as_str(), v))
325 }
326
327 /// Return all function metadata entries as a Vec of named structs.
328 /// Used for inspection (e.g. counting functions, verifying aliases are absent).
329 pub fn get_metadata(&self) -> Vec<FunctionMetaEntry<'_>> {
330 self.metadata
331 .iter()
332 .map(|(k, v)| FunctionMetaEntry { name: k.as_str(), meta: v })
333 .collect()
334 }
335
336 /// Return all user-facing function names (from metadata, not aliases).
337 pub fn metadata_names(&self) -> Vec<String> {
338 self.metadata.keys().cloned().collect()
339 }
340}
341
342impl Registry {
343 /// Volatile functions — outputs change on every evaluation.
344 /// Excluded from conformance fixtures; covered by property tests instead.
345 pub const VOLATILE_FUNCTIONS: &'static [&'static str] = &[
346 "RAND", "RANDARRAY", "NOW", "TODAY", "RANDBETWEEN", "TZNOW",
347 ];
348}
349
350impl Default for Registry {
351 fn default() -> Self {
352 Self::new()
353 }
354}
355
356/// Placeholder that stands in for the function name inside an arity diagnostic
357/// message. `check_arity`/`check_arity_len` do not know the calling function's
358/// name, so they emit this token; the evaluator substitutes the real name at
359/// the dispatch site (see [`crate::eval::finalize_call_result`]). Chosen from
360/// control characters so it can never collide with a real function name.
361pub const FN_NAME_PLACEHOLDER: &str = "\u{1}FN\u{1}";
362
363/// Build the Google-Sheets-style "wrong number of arguments" diagnostic. The
364/// function name is left as [`FN_NAME_PLACEHOLDER`] for the dispatch site to
365/// fill in. Example (min == max == 3, got == 0):
366/// `"Wrong number of arguments to DATE. Expected 3 arguments, but got 0 arguments."`
367fn arity_message(min: usize, max: usize, got: usize) -> String {
368 fn plural(n: usize) -> &'static str {
369 if n == 1 { "" } else { "s" }
370 }
371 let expected = if min == max {
372 format!("{min} argument{}", plural(min))
373 } else if max == usize::MAX {
374 format!("at least {min} argument{}", plural(min))
375 } else {
376 format!("between {min} and {max} arguments")
377 };
378 format!(
379 "Wrong number of arguments to {FN_NAME_PLACEHOLDER}. Expected {expected}, but got {got} argument{}.",
380 plural(got)
381 )
382}
383
384/// Validate argument count for eager functions (args already evaluated to `&[Value]`).
385/// Returns `Some(Value::ErrorMsg(ErrorKind::NA, <message>))` if the count is out
386/// of range (matches Google Sheets / Excel behaviour for wrong argument count).
387/// The error *code* is unchanged (`#N/A`); only an additive diagnostic message
388/// is attached.
389pub fn check_arity(args: &[Value], min: usize, max: usize) -> Option<Value> {
390 check_arity_len(args.len(), min, max)
391}
392
393/// Validate argument count for lazy functions (args are `&[Expr]`).
394/// Returns `Some(Value::ErrorMsg(ErrorKind::NA, <message>))` if the count is out
395/// of range.
396pub fn check_arity_len(count: usize, min: usize, max: usize) -> Option<Value> {
397 if count < min || count > max {
398 Some(Value::ErrorMsg(ErrorKind::NA, arity_message(min, max, count)))
399 } else {
400 None
401 }
402}
403
404// ── Tests ─────────────────────────────────────────────────────────────────
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 #[test]
411 fn list_functions_matches_registry() {
412 let registry = Registry::new();
413 let listed: Vec<(&str, &FunctionMeta)> = registry.list_functions().collect();
414 assert!(!listed.is_empty(), "registry should expose at least one function");
415 // Every listed name must be resolvable — catches metadata/functions map skew
416 for (name, _meta) in &listed {
417 assert!(
418 registry.get(name).is_some(),
419 "listed function {name} not found via get()"
420 );
421 }
422 // metadata count == listed count (no orphaned metadata entries)
423 assert_eq!(listed.len(), registry.metadata.len());
424 }
425}