formualizer-eval 0.11.0

High-performance Arrow-backed Excel formula engine with dependency graph and incremental recalculation
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
use crate::traits::ArgumentHandle;
// Note: Validator no longer depends on EvaluationContext; keep it engine-agnostic.
use formualizer_common::{ArgKind, ExcelError, ExcelErrorKind, LiteralValue};
use smallvec::{SmallVec, smallvec};
use std::borrow::Cow;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ShapeKind {
    Scalar,
    Range,
    Array,
}

pub use formualizer_common::CoercionPolicy;

#[derive(Clone, Debug)]
pub struct ArgSchema {
    pub kinds: SmallVec<[ArgKind; 2]>,
    pub required: bool,
    pub by_ref: bool,
    pub shape: ShapeKind,
    pub coercion: CoercionPolicy,
    pub max: Option<usize>,
    pub repeating: Option<usize>,
    pub default: Option<LiteralValue>,
}

impl ArgSchema {
    pub fn any() -> Self {
        Self {
            kinds: smallvec![ArgKind::Any],
            required: true,
            by_ref: false,
            shape: ShapeKind::Scalar,
            coercion: CoercionPolicy::None,
            max: None,
            repeating: None,
            default: None,
        }
    }

    pub fn number_lenient_scalar() -> Self {
        Self {
            kinds: smallvec![ArgKind::Number],
            required: true,
            by_ref: false,
            shape: ShapeKind::Scalar,
            coercion: CoercionPolicy::NumberLenientText,
            max: None,
            repeating: None,
            default: None,
        }
    }
}

#[derive(Clone, Debug)]
pub enum CriteriaPredicate {
    Eq(LiteralValue),
    Ne(LiteralValue),
    Gt(f64),
    Ge(f64),
    Lt(f64),
    Le(f64),
    TextLike {
        pattern: String,
        case_insensitive: bool,
    },
    /// `"<>a*"`: the complement of [`CriteriaPredicate::TextLike`]; numbers,
    /// booleans, errors and blank cells match.
    NotTextLike {
        pattern: String,
        case_insensitive: bool,
    },
    /// `">b"` and friends with a non-numeric operand: compares text cells
    /// only (case-insensitive); other cells never match.
    TextGt(String),
    TextGe(String),
    TextLt(String),
    TextLe(String),
    /// `"="`: a truly blank cell (not empty text).
    IsBlank,
    /// `"<>"`: any cell that is not truly blank (empty text matches).
    NotBlank,
    IsNumber,
    IsText,
    IsLogical,
}

#[derive(Debug)]
pub enum PreparedArg<'a> {
    Value(Cow<'a, LiteralValue>),
    Range(crate::engine::range_view::RangeView<'a>),
    Reference(formualizer_parse::parser::ReferenceType),
    Predicate(CriteriaPredicate),
}

pub struct PreparedArgs<'a> {
    pub items: Vec<PreparedArg<'a>>,
}

#[derive(Default)]
pub struct ValidationOptions {
    pub warn_only: bool,
    /// Minimum number of arguments the function requires.  When non-zero,
    /// `validate_and_prepare` rejects calls with fewer arguments before any
    /// per-argument validation runs, preventing out-of-bounds panics in
    /// `eval` implementations.
    pub min_args: usize,
}

// Legacy adapter removed in clean break.

/// Parse a criteria argument (COUNTIF/SUMIF/...IFS, MAXIFS/MINIFS and the
/// database functions) into a predicate, following Excel's rules:
/// - a number, boolean or error criterion matches that value;
/// - a reference to an empty cell is the number 0 (blank cells do not match);
/// - `""` matches blank cells and empty text, `"="` only blank cells, and
///   `"<>"` every cell that is not blank;
/// - `?`, `*` and `~` are wildcards, matched against text cells only, with or
///   without a leading `=` (`"<>a*"` is the complement);
/// - `>`, `>=`, `<`, `<=` compare numbers with a numeric operand and text
///   with a text operand.
pub fn parse_criteria(v: &LiteralValue) -> Result<CriteriaPredicate, ExcelError> {
    match v {
        LiteralValue::Text(s) => {
            // Leading spaces before an operator are tolerated; the text operand
            // itself is matched exactly, so trailing spaces are significant
            // (`"Ltd "` does not match `"Ltd"`).
            let s_trim = s.trim_start();

            let unquote = |t: &str| -> String {
                let q = t.trim();
                if let Some(inner) = q.strip_prefix('"').and_then(|x| x.strip_suffix('"')) {
                    inner.replace("\"\"", "\"")
                } else {
                    t.to_string()
                }
            };
            let is_pattern = |t: &str| t.contains('*') || t.contains('?') || t.contains("~~");

            // Operators: >=, <=, <>, >, <, =
            let ops = [">=", "<=", "<>", ">", "<", "="];
            for op in ops.iter() {
                if let Some(rhs) = s_trim.strip_prefix(op) {
                    // Numbers, then date/time text (`">=2/1/02"`), as Excel
                    // reads the operand the way it reads typed input.
                    if let Some(n) = parse_criteria_number(rhs.trim())
                        .or_else(|| parse_criteria_datetime(rhs.trim()))
                    {
                        return Ok(match *op {
                            ">=" => CriteriaPredicate::Ge(n),
                            "<=" => CriteriaPredicate::Le(n),
                            ">" => CriteriaPredicate::Gt(n),
                            "<" => CriteriaPredicate::Lt(n),
                            "=" => CriteriaPredicate::Eq(LiteralValue::Number(n)),
                            "<>" => CriteriaPredicate::Ne(LiteralValue::Number(n)),
                            _ => unreachable!(),
                        });
                    }
                    // Fallback: non-numeric operand (support Excel-style quoted strings: ="aa")
                    let text = unquote(rhs);
                    let boolean = match text.to_ascii_lowercase().as_str() {
                        "true" => Some(true),
                        "false" => Some(false),
                        _ => None,
                    };
                    return Ok(match *op {
                        "=" if text.is_empty() => CriteriaPredicate::IsBlank,
                        "<>" if text.is_empty() => CriteriaPredicate::NotBlank,
                        "=" if is_pattern(&text) => CriteriaPredicate::TextLike {
                            pattern: text,
                            case_insensitive: true,
                        },
                        "<>" if is_pattern(&text) => CriteriaPredicate::NotTextLike {
                            pattern: text,
                            case_insensitive: true,
                        },
                        "=" => match boolean {
                            Some(b) => CriteriaPredicate::Eq(LiteralValue::Boolean(b)),
                            None => CriteriaPredicate::Eq(LiteralValue::Text(text)),
                        },
                        "<>" => match boolean {
                            Some(b) => CriteriaPredicate::Ne(LiteralValue::Boolean(b)),
                            None => CriteriaPredicate::Ne(LiteralValue::Text(text)),
                        },
                        ">=" => CriteriaPredicate::TextGe(text),
                        "<=" => CriteriaPredicate::TextLe(text),
                        ">" => CriteriaPredicate::TextGt(text),
                        "<" => CriteriaPredicate::TextLt(text),
                        _ => unreachable!(),
                    });
                }
            }

            let plain = unquote(s);

            // Wildcards or escaped tilde => TextLike (including literal ~* and ~?).
            if is_pattern(&plain) {
                return Ok(CriteriaPredicate::TextLike {
                    pattern: plain,
                    case_insensitive: true,
                });
            }
            // Booleans TRUE/FALSE
            let lower = plain.to_ascii_lowercase();
            if lower == "true" {
                return Ok(CriteriaPredicate::Eq(LiteralValue::Boolean(true)));
            } else if lower == "false" {
                return Ok(CriteriaPredicate::Eq(LiteralValue::Boolean(false)));
            }
            // Date or time text (`"2/1/2002"`) matches the date's serial.
            if parse_criteria_number(plain.trim()).is_none()
                && let Some(serial) = parse_criteria_datetime(plain.trim())
            {
                return Ok(CriteriaPredicate::Eq(LiteralValue::Number(serial)));
            }
            // Plain text equality
            Ok(CriteriaPredicate::Eq(LiteralValue::Text(plain)))
        }
        // Excel: a criteria argument that references an empty cell is 0.
        LiteralValue::Empty => Ok(CriteriaPredicate::Eq(LiteralValue::Number(0.0))),
        LiteralValue::Number(n) => Ok(CriteriaPredicate::Eq(LiteralValue::Number(*n))),
        // Normalize integer criteria to Number for Excel-style numeric coercions
        // (numeric text == number, etc.)
        LiteralValue::Int(i) => Ok(CriteriaPredicate::Eq(LiteralValue::Number(*i as f64))),
        LiteralValue::Boolean(b) => Ok(CriteriaPredicate::Eq(LiteralValue::Boolean(*b))),
        LiteralValue::Error(e) => Err(e.clone()),
        LiteralValue::Array(arr) => {
            // Treat 1x1 array literals as scalars for criteria parsing
            if arr.len() == 1 && arr.first().map(|r| r.len()).unwrap_or(0) == 1 {
                parse_criteria(&arr[0][0])
            } else {
                Ok(CriteriaPredicate::Eq(LiteralValue::Array(arr.clone())))
            }
        }
        other => Ok(CriteriaPredicate::Eq(other.clone())),
    }
}

/// A date or time operand (`"2/1/02"`, `"1-Feb-2002"`, `"13:30"`) as a 1900-system
/// serial. Criteria parsing has no workbook context, so 1904-system workbooks
/// would see the 1900 serial.
fn parse_criteria_datetime(text: &str) -> Option<f64> {
    if text.is_empty() || !text.bytes().any(|b| b.is_ascii_digit()) {
        return None;
    }
    formualizer_common::parse_excel_datetime_text_to_serial_for(
        formualizer_common::DateSystem::Excel1900,
        text,
    )
}

/// A finite number operand of a criteria operator (`">=1e3"`, `"<>-2"`).
fn parse_criteria_number(text: &str) -> Option<f64> {
    text.parse::<f64>().ok().filter(|n| n.is_finite())
}

pub fn validate_and_prepare<'a, 'b>(
    args: &'a [ArgumentHandle<'a, 'b>],
    schema: &[ArgSchema],
    options: ValidationOptions,
) -> Result<PreparedArgs<'a>, ExcelError> {
    // Minimum arity — reject too-few arguments before per-arg validation so
    // that individual `eval` implementations cannot panic on indexing.
    if options.min_args > 0 && args.len() < options.min_args {
        if options.warn_only {
            return Ok(PreparedArgs { items: Vec::new() });
        }
        return Err(ExcelError::new(ExcelErrorKind::Value).with_message(format!(
            "Too few arguments: expected at least {}, got {}",
            options.min_args,
            args.len()
        )));
    }

    // Arity: simple rule – if schema.len() == 1, allow variadic repetition; else match up to schema.len()
    if schema.is_empty() {
        return Ok(PreparedArgs { items: Vec::new() });
    }

    let mut items: Vec<PreparedArg<'a>> = Vec::with_capacity(args.len());
    for (idx, arg) in args.iter().enumerate() {
        let spec = if schema.len() == 1 {
            &schema[0]
        } else if idx < schema.len() {
            &schema[idx]
        } else {
            // Attempt to find a repeating spec (e.g., variadic tail like CHOOSE, SUM, etc.)
            if let Some(rep_spec) = schema.iter().find(|s| s.repeating.is_some()) {
                rep_spec
            } else if options.warn_only {
                continue;
            } else {
                return Err(
                    ExcelError::new(ExcelErrorKind::Value).with_message("Too many arguments")
                );
            }
        };

        // By-ref argument: require a reference (AST literal or function-returned)
        if spec.by_ref {
            match arg.as_reference_or_eval() {
                Ok(r) => {
                    items.push(PreparedArg::Reference(r));
                    continue;
                }
                Err(e) => {
                    if options.warn_only {
                        continue;
                    } else {
                        return Err(e);
                    }
                }
            }
        }

        // Criteria policy: parse into predicate
        if matches!(spec.coercion, CoercionPolicy::Criteria) {
            let v = arg.value()?.into_literal();
            match parse_criteria(&v) {
                Ok(pred) => {
                    items.push(PreparedArg::Predicate(pred));
                    continue;
                }
                Err(e) => {
                    if options.warn_only {
                        continue;
                    } else {
                        return Err(e);
                    }
                }
            }
        }

        // Shape handling
        match spec.shape {
            ShapeKind::Scalar => {
                // Collapse to scalar if needed (top-left for arrays)
                match arg.value() {
                    Ok(cv) => {
                        let v: Cow<'_, LiteralValue> = match cv {
                            crate::traits::CalcValue::Scalar(LiteralValue::Array(arr)) => {
                                let tl = arr
                                    .first()
                                    .and_then(|row| row.first())
                                    .cloned()
                                    .unwrap_or(LiteralValue::Empty);
                                Cow::Owned(tl)
                            }
                            crate::traits::CalcValue::Range(rv) => Cow::Owned(rv.get_cell(0, 0)),
                            crate::traits::CalcValue::Scalar(s)
                            | crate::traits::CalcValue::AnnotatedScalar(s, _) => Cow::Owned(s),
                            crate::traits::CalcValue::Callable(_) => {
                                Cow::Owned(LiteralValue::Error(
                                    ExcelError::new(ExcelErrorKind::Calc)
                                        .with_message("LAMBDA value must be invoked"),
                                ))
                            }
                        };
                        // Apply coercion policy to Value shapes when applicable
                        let coerced = match spec.coercion {
                            CoercionPolicy::None => v,
                            CoercionPolicy::NumberStrict => {
                                match crate::coercion::to_number_strict(v.as_ref()) {
                                    Ok(n) => Cow::Owned(LiteralValue::Number(n)),
                                    Err(e) => {
                                        if options.warn_only {
                                            v
                                        } else {
                                            return Err(e);
                                        }
                                    }
                                }
                            }
                            CoercionPolicy::NumberLenientText => {
                                match crate::coercion::to_number_lenient(v.as_ref()) {
                                    Ok(n) => Cow::Owned(LiteralValue::Number(n)),
                                    Err(e) => {
                                        if options.warn_only {
                                            v
                                        } else {
                                            return Err(e);
                                        }
                                    }
                                }
                            }
                            CoercionPolicy::Logical => {
                                match crate::coercion::to_logical(v.as_ref()) {
                                    Ok(b) => Cow::Owned(LiteralValue::Boolean(b)),
                                    Err(e) => {
                                        if options.warn_only {
                                            v
                                        } else {
                                            return Err(e);
                                        }
                                    }
                                }
                            }
                            CoercionPolicy::Criteria => v, // handled per-function currently
                            CoercionPolicy::DateTimeSerial => {
                                match crate::coercion::to_datetime_serial(v.as_ref()) {
                                    Ok(n) => Cow::Owned(LiteralValue::Number(n)),
                                    Err(e) => {
                                        if options.warn_only {
                                            v
                                        } else {
                                            return Err(e);
                                        }
                                    }
                                }
                            }
                        };
                        items.push(PreparedArg::Value(coerced))
                    }
                    Err(e) => items.push(PreparedArg::Value(Cow::Owned(LiteralValue::Error(e)))),
                }
            }
            ShapeKind::Range | ShapeKind::Array => match arg.resolve_once() {
                Ok(crate::traits::ResolvedArgument::Range(range))
                | Ok(crate::traits::ResolvedArgument::Value(crate::traits::CalcValue::Range(
                    range,
                ))) => items.push(PreparedArg::Range(range)),
                Ok(crate::traits::ResolvedArgument::Value(value)) => {
                    // Excel-compatible: range-accepting functions also accept scalars.
                    items.push(PreparedArg::Value(Cow::Owned(value.into_literal())))
                }
                Ok(crate::traits::ResolvedArgument::ReferenceError(error)) => {
                    items.push(PreparedArg::Value(Cow::Owned(LiteralValue::Error(error))))
                }
                Err(error) => {
                    items.push(PreparedArg::Value(Cow::Owned(LiteralValue::Error(error))))
                }
            },
        }
    }

    Ok(PreparedArgs { items })
}