visi-core 0.2.1

Embeddable spreadsheet engine: Excel formula compilation and evaluation, dependency-tracked recalculation, and .xlsx import/export
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Excel function dispatch.
//!
//! `evaluate_function` does what has to happen before a function's arguments
//! can be evaluated -- prefix stripping, the lazy/short-circuit functions, and
//! the per-family error-propagation policy -- then offers the evaluated call
//! to each family module in turn. A family returns `None` for a name it does
//! not own, and the chain falls through to "Unknown function".
//!
//! Splitting on family keeps any one file reviewable. The cost is that a call
//! may be tested against several families' matches rather than one; each is a
//! compiler-optimized string match, so this is a small constant, but it is on
//! the hot path and worth a benchmark before adding more families.

mod date_time;
mod engineering;
mod info_lookup;
mod math_trig;
mod stats;
mod text;

use super::{Context, LetScope, Sheet};
use crate::core::engine::cell::{Dependency, EngineError, EvalError};
use crate::core::engine::result_data::ResultData;
use crate::core::parser::Expr;

/// One evaluated function call, as handed to a family module.
///
/// `Copy`, so a family can destructure it and still read `call.upper_name`.
#[derive(Clone, Copy)]
pub(super) struct FnCall<'a> {
    /// Uppercased and stripped of `_xlfn.`/`_xlws.`; what families match on.
    pub upper_name: &'a str,
    /// The unevaluated argument expressions, for the functions that need the
    /// AST rather than the value.
    pub args: &'a [Expr],
    /// The evaluated arguments.
    pub evaluated_args: &'a [ResultData],
    /// Per argument: whether it came from a direct cell reference rather than
    /// a computed expression.
    pub arg_is_direct: &'a [bool],
    /// The other sheets, for cross-sheet references.
    pub context: Option<&'a Context<'a>>,
    /// The row the call is being evaluated for, if any.
    pub row: Option<usize>,
    /// The column the call is being evaluated for, if any.
    pub col: Option<usize>,
    /// Enclosing `LET` bindings.
    pub scope: &'a LetScope<'a>,
}

/// Adapts a numeric function's `Result<f64, String>` to a cell value, where
/// the error string is an Excel error code rather than a Rust failure.
pub(super) fn res_to_rd(res: Result<f64, String>) -> Result<ResultData, EngineError> {
    match res {
        Ok(v) => Ok(ResultData::Float(v)),
        Err(e) => Ok(ResultData::Error(e)),
    }
}

/// A NaN can only come from a math function evaluated outside its domain
/// (ASIN/ACOS of |x|>1, SQRT/LN/LOG10 of a negative, ...), and an infinity
/// only from one that overflowed (POWER(42, 600), EXP(1000)). Excel has
/// neither -- it reports #NUM! for both -- so rather than bolting a
/// domain/overflow guard onto each of those call sites, normalize here at the
/// single point every function result flows through.
fn post_process(r: Result<ResultData, EngineError>) -> Result<ResultData, EngineError> {
    match r {
        Ok(ResultData::Float(f)) if !f.is_finite() => Ok(ResultData::Error("#NUM!".to_string())),
        other => other,
    }
}

impl Sheet {
    /// Evaluates a worksheet function from already-built argument
    /// expressions, outside any cell.
    ///
    /// The entry point `Application.WorksheetFunction.X` reaches, so that the
    /// VBA host bridges onto the *existing* function library rather than
    /// reimplementing it. Deliberately `pub(crate)` and deliberately not a
    /// widening of [`Sheet::evaluate_function`]'s visibility: the caller
    /// supplies arguments and a context and gets a value, with no access to
    /// the dependency plumbing or the `LET` scope a real cell evaluation
    /// carries.
    ///
    /// Dependencies are discarded because there is no cell to record them
    /// against -- a macro's call is a one-off read, not an edge in the
    /// recalculation graph.
    pub(crate) fn call_worksheet_function(
        &self,
        name: &str,
        args: &[Expr],
        context: Option<&Context>,
    ) -> Result<ResultData, EngineError> {
        let mut deps = Vec::new();
        self.evaluate_function(name, args, context, None, None, &mut deps, &LetScope::Empty)
    }

    /// Evaluates a function call by name.
    ///
    /// Handles the lazy/short-circuit functions itself, since their arguments
    /// must not be evaluated up front, then evaluates the remaining arguments
    /// and offers the call to each family module in turn.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn evaluate_function(
        &self,
        name: &str,
        args: &[crate::core::parser::Expr],
        context: Option<&Context>,
        row: Option<usize>,
        col: Option<usize>,
        deps: &mut Vec<Dependency>,
        scope: &LetScope<'_>,
    ) -> Result<ResultData, EngineError> {
        use crate::core::parser::Expr;
        let mut upper_name = name.to_uppercase();
        if upper_name.starts_with("_XLFN.") {
            upper_name = upper_name["_XLFN.".len()..].to_string();
        }
        // Real Excel's OOXML writer additionally nests some dynamic-array
        // worksheet functions (UNIQUE, SORT, FILTER, ...) under a second
        // `_xlws.` prefix inside `_xlfn.` -- e.g. `_xlfn._xlws.SORT`, not
        // just `_xlfn.SORT`. Without stripping it too, the un-stripped
        // name never matches any dispatch arm here -- confirmed as a real
        // mismatch by checking real Excel's own OOXML export for these
        // functions directly.
        if upper_name.starts_with("_XLWS.") {
            upper_name = upper_name["_XLWS.".len()..].to_string();
        }

        if upper_name == "LET" {
            return self.evaluate_let(args, context, row, col, deps, scope);
        }

        if upper_name == "IF" {
            if args.len() < 3 {
                return Err(EngineError::EvalError(EvalError::UnknownFunction(
                    "IF requires 3 arguments".to_string(),
                )));
            }
            let cond_val = self.evaluate_ast(&args[0], context, row, col, deps, scope)?;
            if let ResultData::Error(_) = cond_val {
                return Ok(cond_val);
            }
            let condition = match self.to_bool_opt(&cond_val) {
                Some(b) => b,
                None => return Ok(ResultData::Error("#VALUE!".to_string())),
            };
            if condition {
                return self.evaluate_ast(&args[1], context, row, col, deps, scope);
            } else {
                return self.evaluate_ast(&args[2], context, row, col, deps, scope);
            }
        }

        if upper_name == "IFERROR" {
            if args.len() < 2 {
                return Err(EngineError::EvalError(EvalError::UnknownFunction(
                    "IFERROR requires 2 arguments".to_string(),
                )));
            }
            let first_res = self.evaluate_ast(&args[0], context, row, col, deps, scope);
            match first_res {
                Ok(ResultData::Error(_)) | Err(_) => {
                    return self.evaluate_ast(&args[1], context, row, col, deps, scope);
                }
                Ok(val) => return Ok(val),
            }
        }

        if upper_name == "IFNA" {
            if args.len() < 2 {
                return Err(EngineError::EvalError(EvalError::UnknownFunction(
                    "IFNA requires 2 arguments".to_string(),
                )));
            }
            // Not a bare `?`: a nested call can fail as a hard `Err` rather
            // than an `Ok(ResultData::Error(_))` -- e.g. ATAN2/LOG's own
            // `to_f64_arg(...)?`  on an argument that is itself already an
            // error -- and IFNA still needs to see which error code that
            // was, the same normalization the general arg-gathering loop
            // above does for every ordinary function's arguments.
            let first_val = match self.evaluate_ast(&args[0], context, row, col, deps, scope) {
                Ok(v) => v,
                Err(EngineError::EvalError(EvalError::UnknownFunction(e)))
                    if e.starts_with('#') =>
                {
                    ResultData::Error(e)
                }
                Err(e) => return Err(e),
            };
            if let ResultData::Error(ref e) = first_val
                && e == "#N/A"
            {
                return self.evaluate_ast(&args[1], context, row, col, deps, scope);
            }
            return Ok(first_val);
        }

        if upper_name == "IFS" {
            // Lazily evaluated: only the arms up to and including the
            // first TRUE condition are ever computed, so an error
            // sitting in a later (unselected) value never propagates.
            // Confirmed against real Excel: `IFS(TRUE, 42, TRUE, 1/0)`
            // is 42, while `IFS(FALSE, 42, TRUE, 1/0)` is #DIV/0!.
            let mut i = 0;
            while i + 1 < args.len() {
                let cond = self.evaluate_ast(&args[i], context, row, col, deps, scope)?;
                if let ResultData::Error(_) = cond {
                    return Ok(cond);
                }
                if self.to_bool(&cond) {
                    return self.evaluate_ast(&args[i + 1], context, row, col, deps, scope);
                }
                i += 2;
            }
            return Ok(ResultData::Error("#N/A".to_string()));
        }

        if upper_name == "SWITCH" {
            // Lazily evaluated for the same reason as IFS: an error in
            // a value arm that isn't selected must not propagate
            // (`SWITCH(2, 1, 1/0, 2, 99, -1)` is 99 in real Excel).
            if args.len() < 3 {
                return Ok(ResultData::Error("#VALUE!".to_string()));
            }
            let target = self.evaluate_ast(&args[0], context, row, col, deps, scope)?;
            if let ResultData::Error(_) = target {
                return Ok(target);
            }
            let mut i = 1;
            while i + 1 < args.len() {
                let case = self.evaluate_ast(&args[i], context, row, col, deps, scope)?;
                if let ResultData::Error(_) = case {
                    return Ok(case);
                }
                if target.to_string() == case.to_string() {
                    return self.evaluate_ast(&args[i + 1], context, row, col, deps, scope);
                }
                i += 2;
            }
            // A trailing odd argument is the default.
            if i < args.len() {
                return self.evaluate_ast(&args[i], context, row, col, deps, scope);
            }
            return Ok(ResultData::Error("#N/A".to_string()));
        }

        if upper_name == "CHOOSE" {
            if args.len() < 2 {
                return Err(EngineError::EvalError(EvalError::UnknownFunction(
                    "CHOOSE requires at least 2 arguments".to_string(),
                )));
            }
            let idx_val = self.evaluate_ast(&args[0], context, row, col, deps, scope)?;
            if let ResultData::Error(_) = idx_val {
                return Ok(idx_val);
            }
            let idx = match self.to_f64(&idx_val) {
                Some(f) => f.round() as isize,
                None => return Ok(ResultData::Error("#VALUE!".to_string())),
            };
            let choices = &args[1..];
            if idx >= 1 && (idx as usize) <= choices.len() {
                return self.evaluate_ast(
                    &choices[(idx - 1) as usize],
                    context,
                    row,
                    col,
                    deps,
                    scope,
                );
            } else {
                return Ok(ResultData::Error("#VALUE!".to_string()));
            }
        }

        if upper_name == "LAMBDA" {
            // A bare, uninvoked LAMBDA (not nested as another
            // function's argument, e.g. `=LAMBDA(x, x*2)` alone in a
            // cell) has nothing to apply it to -- the parser doesn't
            // support the `LAMBDA(...)(args)` immediate-invocation
            // syntax (that would need the grammar to allow calling an
            // arbitrary sub-expression, not just a bare identifier),
            // so this mirrors Excel's #CALC! for an unusable lambda.
            return Ok(ResultData::Error("#CALC!".to_string()));
        }

        if matches!(
            upper_name.as_str(),
            "MAP" | "BYROW" | "BYCOL" | "REDUCE" | "SCAN" | "MAKEARRAY"
        ) {
            return self.evaluate_lambda_function(
                upper_name.as_str(),
                args,
                context,
                row,
                col,
                deps,
                scope,
            );
        }

        if upper_name == "ISOMITTED" {
            // Best-effort: every lambda invocation path here
            // (MAP/BYROW/BYCOL/REDUCE/SCAN/MAKEARRAY) always supplies
            // exactly as many argument values as the lambda declares
            // parameters, so a declared parameter is never actually
            // left unbound -- this can only ever observe "not found
            // in scope at all", which is the honest limitation to
            // report rather than silently guessing.
            let is_omitted = match args.first() {
                Some(Expr::Identifier(name)) => scope.get(name).is_none(),
                _ => false,
            };
            return Ok(ResultData::Boolean(is_omitted));
        }

        if matches!(
            upper_name.as_str(),
            "ROW"
                | "ROWS"
                | "COLUMN"
                | "COLUMNS"
                | "AREAS"
                | "ISREF"
                | "FORMULATEXT"
                | "ISFORMULA"
                | "INDIRECT"
                | "OFFSET"
                | "SHEET"
                | "SHEETS"
                | "CELL"
                | "INFO"
        ) {
            return self.evaluate_range_info_function(
                upper_name.as_str(),
                args,
                context,
                row,
                col,
                deps,
                scope,
            );
        }

        if matches!(
            upper_name.as_str(),
            "TRANSPOSE"
                | "HSTACK"
                | "VSTACK"
                | "CHOOSEROWS"
                | "CHOOSECOLS"
                | "DROP"
                | "EXPAND"
                | "TAKE"
                | "TOCOL"
                | "TOROW"
                | "WRAPROWS"
                | "WRAPCOLS"
                | "UNIQUE"
                | "SORT"
                | "SORTBY"
                | "FILTER"
                | "TRIMRANGE"
        ) {
            return self.evaluate_array_reshape_function(
                upper_name.as_str(),
                args,
                context,
                row,
                col,
                deps,
                scope,
            );
        }

        if upper_name == "GETPIVOTDATA" {
            return self.evaluate_getpivotdata(args, context, row, col, deps, scope);
        }

        if upper_name == "ISERROR" {
            if args.is_empty() {
                return Ok(ResultData::Boolean(false));
            }
            let res = self.evaluate_ast(&args[0], context, row, col, deps, scope);
            return match res {
                Ok(ResultData::Error(_)) | Err(_) => Ok(ResultData::Boolean(true)),
                _ => Ok(ResultData::Boolean(false)),
            };
        }

        if upper_name == "ISNA" {
            if args.is_empty() {
                return Ok(ResultData::Boolean(false));
            }
            // A nested call can fail as a hard `Err` rather than an
            // `Ok(ResultData::Error(_))` -- e.g. ATAN2/LOG's own
            // `to_f64_arg(...)?` on an argument that is itself already an
            // error -- so this has to check the error *code* on that path
            // too, not treat every `Err` alike the way `_ => false` did.
            let res = self.evaluate_ast(&args[0], context, row, col, deps, scope);
            return match res {
                Ok(ResultData::Error(e)) => Ok(ResultData::Boolean(e.contains("#N/A"))),
                Err(EngineError::EvalError(EvalError::UnknownFunction(e)))
                    if e.starts_with('#') =>
                {
                    Ok(ResultData::Boolean(e.contains("#N/A")))
                }
                _ => Ok(ResultData::Boolean(false)),
            };
        }

        let mut evaluated_args = Vec::new();
        let mut arg_is_direct = Vec::new();
        for arg in args {
            let is_direct_arg = match arg {
                Expr::CellRef { .. } | Expr::RangeRef { .. } | Expr::StructuredRef { .. } => false,
                Expr::FunctionCall { name, .. } => {
                    let n = name.to_uppercase();
                    n != "IF" && n != "IFERROR" && n != "CHOOSE"
                }
                _ => true,
            };
            arg_is_direct.push(is_direct_arg);
            let eval_res = match self.evaluate_ast(arg, context, row, col, deps, scope) {
                Ok(r) => r,
                Err(EngineError::EvalError(EvalError::UnknownFunction(err_str)))
                    if err_str.starts_with('#') =>
                {
                    ResultData::Error(err_str)
                }
                Err(e) => return Err(e),
            };
            evaluated_args.push(eval_res);
        }

        let uses_ordered_arg_error_check = matches!(
            upper_name.as_str(),
            "SUM" | "AVERAGE" | "MIN" | "MAX" | "PRODUCT"
        );
        // The type-introspection functions must see an error value
        // rather than have it propagate past them: real Excel answers
        // TYPE(1/0) = 16, ISNONTEXT(1/0) = TRUE, and
        // ISTEXT/ISNUMBER/ISLOGICAL/ISBLANK(1/0) = FALSE. (Math
        // functions like ISODD do still propagate -- ISODD(1/0) is
        // #DIV/0! -- so they stay out of this list.)
        let inspects_errors = matches!(
            upper_name.as_str(),
            "IFERROR"
                | "ISERROR"
                | "ISNA"
                | "ISERR"
                | "ERROR.TYPE"
                | "TYPE"
                | "ISTEXT"
                | "ISNONTEXT"
                | "ISNUMBER"
                | "ISLOGICAL"
                | "ISBLANK"
        );
        if !inspects_errors
                // COUNTA counts an error argument as one more non-blank
                // value, and COUNT skips it, rather than either
                // propagating it (both match real Excel).
                && upper_name != "COUNTA"
                && upper_name != "COUNT"
                // COUNTBLANK just asks which cells are empty; an error in
                // the range is a non-blank cell, not a reason to fail.
                && upper_name != "COUNTBLANK"
                // AGGREGATE decides for itself whether to propagate or
                // ignore an error in its data, based on its `options`
                // argument, so it must see the raw arguments.
                && upper_name != "AGGREGATE"
                // The paired statistical functions check their two ranges'
                // shapes before anything else -- a size mismatch is #N/A
                // even when a range also holds an error value -- so they
                // re-raise errors themselves (see paired_args).
                && !matches!(
                    upper_name.as_str(),
                    "CORREL"
                        | "PEARSON"
                        | "COVAR"
                        | "COVARIANCE.P"
                        | "COVARIANCE.S"
                        | "SLOPE"
                        | "INTERCEPT"
                        | "RSQ"
                        | "STEYX"
                        | "FORECAST"
                        | "FORECAST.LINEAR"
                        | "SUMX2MY2"
                        | "SUMX2PY2"
                        | "SUMXMY2"
                        | "CHISQ.TEST"
                        | "CHITEST"
                        // LOG and ATAN2 type-check their *first* argument
                        // before ever looking at whether a later one is
                        // itself an error -- when the first argument is
                        // non-numeric and a later one holds a pre-computed
                        // error, real Excel returns #VALUE! (from the
                        // first-argument check), not the later argument's
                        // error code (measured via win32com against real
                        // Windows Excel: `LOG("C", #N/A)` and
                        // `ATAN2("text", #N/A)` both give #VALUE!). Both
                        // functions' own match arms already check argument
                        // one via `to_f64_arg` before touching argument
                        // two, so exempting them here just lets that
                        // existing order run instead of being preempted.
                        | "LOG"
                        | "ATAN2"
                        // GCD/LCM walk their arguments in order and reject
                        // the first non-numeric one (a boolean, or text
                        // that doesn't coerce) as #VALUE! -- same
                        // first-argument-wins shape as LOG/ATAN2 above.
                        // `GCD(AND(...), CORREL(mismatched ranges))`
                        // should be #VALUE! from the boolean argument, not
                        // CORREL's #N/A (measured via win32com).
                        | "GCD"
                        | "LCM"
                )
                && !uses_ordered_arg_error_check
                && let Some(err) = Self::find_error_in_args(&evaluated_args)
        {
            return Ok(err);
        }

        // A NaN can only come from a math function evaluated outside
        // its domain (ASIN/ACOS of |x|>1, SQRT/LN/LOG10 of a negative,
        // ...), and an infinity only from one that overflowed
        // (POWER(42, 600), EXP(1000)). Excel has neither -- it reports
        // #NUM! for both -- so rather than bolting a domain/overflow
        // guard onto each of those call sites individually, normalize
        // here at the single point every function result flows
        // through.
        let call = FnCall {
            upper_name: upper_name.as_str(),
            args,
            evaluated_args: &evaluated_args,
            arg_is_direct: &arg_is_direct,
            context,
            row,
            col,
            scope,
        };
        if let Some(r) = self.eval_stats_fn(call, deps) {
            return post_process(r);
        }
        if let Some(r) = self.eval_math_trig_fn(call, deps) {
            return post_process(r);
        }
        if let Some(r) = self.eval_text_fn(call, deps) {
            return post_process(r);
        }
        if let Some(r) = self.eval_date_time_fn(call, deps) {
            return post_process(r);
        }
        if let Some(r) = self.eval_engineering_fn(call, deps) {
            return post_process(r);
        }
        if let Some(r) = self.eval_info_lookup_fn(call, deps) {
            return post_process(r);
        }
        post_process(Err(EngineError::EvalError(EvalError::UnknownFunction(
            format!("Unknown function: {}", name),
        ))))
    }
}