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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use crate::args::{ArgSchema, CoercionPolicy, ShapeKind};
use formualizer_common::{ExcelError, LiteralValue};
use std::sync::LazyLock;

/// Small epsilon used to detect near-zero denominators in trig/hyperbolic functions.
pub const EPSILON_NEAR_ZERO: f64 = 1e-12;

/// Final non-finite guard for numeric aggregate results (SUM/MIN/MAX/...):
/// Excel never surfaces inf/NaN — an overflowed aggregate is `#NUM\!`, the
/// same parity rule operators already apply via `coercion::sanitize_numeric`.
/// One branch per aggregate CALL (apply to the finished reduction, never per
/// element — arrow kernels stay untouched).
pub fn aggregate_result(n: f64) -> LiteralValue {
    if n.is_finite() {
        LiteralValue::Number(n)
    } else {
        LiteralValue::Error(ExcelError::new_num())
    }
}

/// Coerce a `LiteralValue` to `f64` using Excel semantics.
/// - Number/Int map to f64
/// - Boolean maps to 1.0/0.0
/// - Empty maps to 0.0
/// - Others -> `#VALUE!`
pub fn coerce_num(value: &LiteralValue) -> Result<f64, ExcelError> {
    crate::coercion::to_number_lenient(value)
}

/// Get a single numeric argument, with count and error checks.
pub fn unary_numeric_arg<'a, 'b>(
    args: &'a [crate::traits::ArgumentHandle<'a, 'b>],
) -> Result<f64, ExcelError> {
    if args.len() != 1 {
        return Err(ExcelError::new_value()
            .with_message(format!("Expected 1 argument, got {}", args.len())));
    }
    let v = args[0].value()?.into_literal();
    match v {
        LiteralValue::Error(e) => Err(e),
        other => coerce_num(&other),
    }
}

/// Get two numeric arguments, with count and error checks.
pub fn binary_numeric_args<'a, 'b>(
    args: &'a [crate::traits::ArgumentHandle<'a, 'b>],
) -> Result<(f64, f64), ExcelError> {
    if args.len() != 2 {
        return Err(ExcelError::new_value()
            .with_message(format!("Expected 2 arguments, got {}", args.len())));
    }
    let a = args[0].value()?.into_literal();
    let b = args[1].value()?.into_literal();
    let a_num = match a {
        LiteralValue::Error(e) => return Err(e),
        other => coerce_num(&other)?,
    };
    let b_num = match b {
        LiteralValue::Error(e) => return Err(e),
        other => coerce_num(&other)?,
    };
    Ok((a_num, b_num))
}

fn calc_from_literal<'b>(
    v: LiteralValue,
    date_system: crate::engine::DateSystem,
) -> crate::traits::CalcValue<'b> {
    match v {
        LiteralValue::Array(rows) => crate::traits::CalcValue::Range(
            crate::engine::range_view::RangeView::from_owned_rows(rows, date_system),
        ),
        other => crate::traits::CalcValue::Scalar(other),
    }
}

/* ─────────────────── generated-array allocation guard ───────────────────
 *
 * Builtins that materialize a whole array result as `Vec<Vec<LiteralValue>>`
 * before the engine ever sees it (generators such as SEQUENCE/RANDARRAY, and
 * elementwise selections such as IFERROR/IFNA) must bound the output shape
 * BEFORE allocating: `=SEQUENCE(1e6,1e6)` would otherwise attempt a
 * 10^12-cell allocation.
 *
 * Cap rationale:
 * - Per-dimension: Excel sheet limits (1,048,576 rows × 16,384 cols — the
 *   same values as `EvalConfig::default().max_sheet_rows/max_sheet_cols`).
 *   A generated array larger than a sheet can never spill successfully
 *   (`SpillBoundsPolicy::Strict`), so it is `#NUM!` unconditionally.
 * - Total cells: 2^24 (16,777,216). `LiteralValue` is ≥32 bytes, so this
 *   already bounds the transient allocation near ~0.5 GiB — three orders
 *   of magnitude above the engine's default spill cap
 *   (`SpillConfig::max_spill_cells` = 10,000) which would reject the
 *   result downstream anyway. Anything larger risks OOM before that
 *   downstream guard can run.
 *
 * This is a fixed per-array bound, not configured resource accounting: it
 * does not charge the evaluation ledger or observe `EvaluationBudgets`.
 */
pub(crate) const GENERATED_ARRAY_MAX_ROWS: i64 = 1_048_576;
pub(crate) const GENERATED_ARRAY_MAX_COLS: i64 = 16_384;
pub(crate) const GENERATED_ARRAY_MAX_CELLS: i64 = 1 << 24;

/// Returns `Some(#NUM!)` when a `rows x cols` generated array exceeds the
/// allocation guard; uses checked arithmetic so overflowing products fail
/// closed. Callers have already rejected `rows <= 0 || cols <= 0`.
pub(crate) fn generated_array_too_large(rows: i64, cols: i64) -> Option<ExcelError> {
    if rows > GENERATED_ARRAY_MAX_ROWS || cols > GENERATED_ARRAY_MAX_COLS {
        return Some(ExcelError::new(formualizer_common::ExcelErrorKind::Num));
    }
    match rows.checked_mul(cols) {
        Some(total) if total <= GENERATED_ARRAY_MAX_CELLS => None,
        _ => Some(ExcelError::new(formualizer_common::ExcelErrorKind::Num)),
    }
}

/// [`generated_array_too_large`] for an already-computed output shape.
/// Dimensions that do not fit `i64` fail closed.
pub(crate) fn materialized_shape_too_large(shape: (usize, usize)) -> Option<ExcelError> {
    match (i64::try_from(shape.0), i64::try_from(shape.1)) {
        (Ok(rows), Ok(cols)) => generated_array_too_large(rows, cols),
        _ => Some(ExcelError::new(formualizer_common::ExcelErrorKind::Num)),
    }
}

/// Number of visited cells between cancellation polls in eager array walks.
pub(crate) const CANCEL_POLL_CELLS: usize = 4096;

/// Cell-count based cancellation polling for eager walks over arrays that
/// are not driven by a [`RangeView`](crate::engine::range_view::RangeView)
/// segment iterator. The first [`Self::advance`] always polls, so a
/// cancellation raised before a walk starts is observed even for tiny or
/// single-row inputs; later polls happen every [`CANCEL_POLL_CELLS`] cells,
/// so one very wide row is still interrupted mid-row.
pub(crate) struct CancelPoll<'p> {
    is_cancelled: &'p dyn Fn() -> bool,
    since_poll: usize,
}

impl<'p> CancelPoll<'p> {
    pub(crate) fn new(is_cancelled: &'p dyn Fn() -> bool) -> Self {
        Self {
            is_cancelled,
            since_poll: CANCEL_POLL_CELLS,
        }
    }

    /// Records `cells` of work, polling first when the stride is reached.
    #[inline]
    pub(crate) fn advance(&mut self, cells: usize) -> Result<(), ExcelError> {
        if self.since_poll >= CANCEL_POLL_CELLS {
            self.since_poll = 0;
            if (self.is_cancelled)() {
                return Err(ExcelError::new(
                    formualizer_common::ExcelErrorKind::Cancelled,
                ));
            }
        }
        self.since_poll = self.since_poll.saturating_add(cells);
        Ok(())
    }
}

/// A 2D argument for elementwise builtins: a view, an owned array, or a
/// scalar that broadcasts over any shape. Out-of-bounds reads are `Empty`.
pub(crate) enum Grid<'b> {
    Range(crate::engine::range_view::RangeView<'b>),
    Array(Vec<Vec<LiteralValue>>),
    Scalar(LiteralValue),
}

impl<'b> Grid<'b> {
    pub(crate) fn shape(&self) -> (usize, usize) {
        match self {
            Grid::Range(rv) => rv.dims(),
            Grid::Array(arr) => (arr.len(), arr.first().map(|r| r.len()).unwrap_or(0)),
            Grid::Scalar(_) => (1, 1),
        }
    }

    pub(crate) fn get(&self, r: usize, c: usize) -> LiteralValue {
        match self {
            Grid::Range(rv) => rv.get_cell(r, c),
            Grid::Array(arr) => arr
                .get(r)
                .and_then(|row| row.get(c))
                .cloned()
                .unwrap_or(LiteralValue::Empty),
            Grid::Scalar(v) => v.clone(),
        }
    }
}

pub fn unary_numeric_elementwise<'a, 'b, F>(
    args: &'a [crate::traits::ArgumentHandle<'a, 'b>],
    ctx: &dyn crate::traits::FunctionContext<'b>,
    mut f: F,
) -> Result<crate::traits::CalcValue<'b>, ExcelError>
where
    F: FnMut(f64) -> Result<LiteralValue, ExcelError>,
{
    if args.len() != 1 {
        return Err(ExcelError::new_value()
            .with_message(format!("Expected 1 argument, got {}", args.len())));
    }

    let shape = if let Ok(rv) = args[0].range_view() {
        rv.dims()
    } else if let Ok(cv) = args[0].value() {
        match cv.into_literal() {
            LiteralValue::Array(arr) => (arr.len(), arr.first().map(|r| r.len()).unwrap_or(0)),
            _ => (1, 1),
        }
    } else {
        (1, 1)
    };

    if shape != (1, 1) {
        let mut out: Vec<Vec<LiteralValue>> = Vec::with_capacity(shape.0);
        if let Ok(view) = args[0].range_view() {
            view.for_each_row(&mut |row| {
                let mut out_row: Vec<LiteralValue> = Vec::with_capacity(row.len());
                for cell in row.iter() {
                    let num_opt = match cell {
                        LiteralValue::Error(e) => return Err(e.clone()),
                        other => {
                            crate::coercion::to_number_lenient_with_locale(other, &ctx.locale())
                                .ok()
                        }
                    };
                    match num_opt {
                        Some(n) => out_row.push(f(n)?),
                        None => out_row.push(LiteralValue::Error(
                            ExcelError::new_value()
                                .with_message("Element is not coercible to number"),
                        )),
                    }
                }
                out.push(out_row);
                Ok(())
            })?;
        } else {
            let v = args[0].value()?.into_literal();
            let LiteralValue::Array(arr) = v else {
                // Defensive: if shape says array but value isn't, treat as scalar.
                let x = unary_numeric_arg(args)?;
                return Ok(calc_from_literal(f(x)?, ctx.date_system()));
            };

            for row in arr {
                let mut out_row: Vec<LiteralValue> = Vec::with_capacity(row.len());
                for cell in row {
                    let num_opt = match &cell {
                        LiteralValue::Error(e) => return Err(e.clone()),
                        other => {
                            crate::coercion::to_number_lenient_with_locale(other, &ctx.locale())
                                .ok()
                        }
                    };
                    match num_opt {
                        Some(n) => out_row.push(f(n)?),
                        None => out_row.push(LiteralValue::Error(
                            ExcelError::new_value()
                                .with_message("Element is not coercible to number"),
                        )),
                    }
                }
                out.push(out_row);
            }
        }

        return Ok(calc_from_literal(
            LiteralValue::Array(out),
            ctx.date_system(),
        ));
    }

    let x = unary_numeric_arg(args)?;
    Ok(calc_from_literal(f(x)?, ctx.date_system()))
}

pub fn binary_numeric_elementwise<'a, 'b, F>(
    args: &'a [crate::traits::ArgumentHandle<'a, 'b>],
    ctx: &dyn crate::traits::FunctionContext<'b>,
    mut f: F,
) -> Result<crate::traits::CalcValue<'b>, ExcelError>
where
    F: FnMut(f64, f64) -> Result<LiteralValue, ExcelError>,
{
    if args.len() != 2 {
        return Err(ExcelError::new_value()
            .with_message(format!("Expected 2 arguments, got {}", args.len())));
    }

    use crate::broadcast::{broadcast_shape, project_index};

    fn to_grid<'a, 'b>(ah: &crate::traits::ArgumentHandle<'a, 'b>) -> Result<Grid<'b>, ExcelError> {
        if let Ok(rv) = ah.range_view() {
            return Ok(Grid::Range(rv));
        }
        let v = ah.value()?.into_literal();
        Ok(match v {
            LiteralValue::Array(arr) => Grid::Array(arr),
            other => Grid::Scalar(other),
        })
    }

    let g0 = to_grid(&args[0])?;
    let g1 = to_grid(&args[1])?;
    let s0 = g0.shape();
    let s1 = g1.shape();
    let target = broadcast_shape(&[s0, s1])?;

    if target != (1, 1) {
        let mut out: Vec<Vec<LiteralValue>> = Vec::with_capacity(target.0);
        for r in 0..target.0 {
            let mut out_row = Vec::with_capacity(target.1);
            for c in 0..target.1 {
                let (r0, c0) = project_index((r, c), s0);
                let (r1, c1) = project_index((r, c), s1);
                let lv0 = g0.get(r0, c0);
                let lv1 = g1.get(r1, c1);

                let n0 = match &lv0 {
                    LiteralValue::Error(e) => return Err(e.clone()),
                    other => {
                        crate::coercion::to_number_lenient_with_locale(other, &ctx.locale()).ok()
                    }
                };
                let n1 = match &lv1 {
                    LiteralValue::Error(e) => return Err(e.clone()),
                    other => {
                        crate::coercion::to_number_lenient_with_locale(other, &ctx.locale()).ok()
                    }
                };

                let out_cell = match (n0, n1) {
                    (Some(a), Some(b)) => f(a, b)?,
                    _ => LiteralValue::Error(
                        ExcelError::new_value()
                            .with_message("Elements are not coercible to numbers"),
                    ),
                };
                out_row.push(out_cell);
            }
            out.push(out_row);
        }
        return Ok(calc_from_literal(
            LiteralValue::Array(out),
            ctx.date_system(),
        ));
    }

    let (a, b) = binary_numeric_args(args)?;
    Ok(calc_from_literal(f(a, b)?, ctx.date_system()))
}

/// Forward-looking: clamp numeric result to Excel-friendly finite values.
/// Converts NaN to `#NUM!` and +/-Inf to large finite sentinels if desired.
pub fn sanitize_numeric_result(n: f64) -> Result<f64, ExcelError> {
    crate::coercion::sanitize_numeric(n)
}

/// Forward-looking: try converting text that looks like a number (Excel often parses text numbers).
pub fn coerce_text_to_number_maybe(value: &LiteralValue) -> Option<f64> {
    match value {
        LiteralValue::Text(_) => crate::coercion::to_number_lenient(value).ok(),
        _ => None,
    }
}

/// Forward-looking: common rounding strategy for functions requiring specific rounding.
pub fn round_to_precision(n: f64, digits: i32) -> f64 {
    if digits <= 0 {
        return n.round();
    }
    let factor = 10f64.powi(digits);
    (n * factor).round() / factor
}

pub fn collapse_if_scalar(
    rows: Vec<Vec<LiteralValue>>,
    date_system: crate::engine::DateSystem,
) -> crate::traits::CalcValue<'static> {
    if rows.len() == 1 && rows[0].len() == 1 {
        crate::traits::CalcValue::Scalar(rows[0][0].clone())
    } else {
        crate::traits::CalcValue::Range(crate::engine::range_view::RangeView::from_owned_rows(
            rows,
            date_system,
        ))
    }
}

// ─────────────────────────────── Criteria helpers (shared by *IF* aggregators) ───────────────────────────────

/// Match a value against a parsed `CriteriaPredicate` (see `crate::args::CriteriaPredicate`).
/// Implements Excel's criteria semantics: equality is case-insensitive for text and
/// lenient for numeric text (`5` matches the text `"5"`), but a number never matches
/// a blank cell or a boolean; numeric comparisons only match numbers; wildcard and
/// text comparisons only match text.
pub fn criteria_match(pred: &crate::args::CriteriaPredicate, v: &LiteralValue) -> bool {
    use crate::args::CriteriaPredicate as P;
    match pred {
        P::Eq(t) => values_equal_invariant(t, v),
        P::Ne(t) => !values_equal_invariant(t, v),
        P::Gt(n) => criteria_number(v).is_some_and(|x| x > *n),
        P::Ge(n) => criteria_number(v).is_some_and(|x| x >= *n),
        P::Lt(n) => criteria_number(v).is_some_and(|x| x < *n),
        P::Le(n) => criteria_number(v).is_some_and(|x| x <= *n),
        P::TextLike {
            pattern,
            case_insensitive,
        } => text_like_match(pattern, *case_insensitive, v),
        P::NotTextLike {
            pattern,
            case_insensitive,
        } => !text_like_match(pattern, *case_insensitive, v),
        P::TextGt(t) => text_compare(v, t).is_some_and(|o| o.is_gt()),
        P::TextGe(t) => text_compare(v, t).is_some_and(|o| o.is_ge()),
        P::TextLt(t) => text_compare(v, t).is_some_and(|o| o.is_lt()),
        P::TextLe(t) => text_compare(v, t).is_some_and(|o| o.is_le()),
        P::IsBlank => matches!(v, LiteralValue::Empty),
        P::NotBlank => !matches!(v, LiteralValue::Empty),
        P::IsNumber => value_to_number(v).is_ok(),
        P::IsText => matches!(v, LiteralValue::Text(_)),
        P::IsLogical => matches!(v, LiteralValue::Boolean(_)),
    }
}

fn value_to_number(v: &LiteralValue) -> Result<f64, ExcelError> {
    crate::coercion::to_number_lenient(v)
}

/// The number a numeric comparison (`>5`) sees: numbers and dates only.
/// Blank cells, text (even numeric text), booleans and errors never match.
fn criteria_number(v: &LiteralValue) -> Option<f64> {
    match v {
        LiteralValue::Boolean(_) => None,
        other => other.as_serial_number(),
    }
}

/// Case-insensitive ordering of a text cell against a text operand; `None`
/// for any other cell.
fn text_compare(v: &LiteralValue, operand: &str) -> Option<std::cmp::Ordering> {
    match v {
        LiteralValue::Text(t) => Some(t.to_lowercase().cmp(&operand.to_lowercase())),
        _ => None,
    }
}

fn values_equal_invariant(a: &LiteralValue, b: &LiteralValue) -> bool {
    match (a, b) {
        (LiteralValue::Number(x), LiteralValue::Number(y)) => (x - y).abs() < 1e-12,
        (LiteralValue::Int(x), LiteralValue::Int(y)) => x == y,
        (LiteralValue::Boolean(x), LiteralValue::Boolean(y)) => x == y,
        (LiteralValue::Text(x), LiteralValue::Text(y)) => x.to_lowercase() == y.to_lowercase(),
        // Treat blank and empty text as equal (Excel semantics)
        (LiteralValue::Text(x), LiteralValue::Empty) if x.is_empty() => true,
        (LiteralValue::Empty, LiteralValue::Text(y)) if y.is_empty() => true,
        (LiteralValue::Empty, LiteralValue::Empty) => true,
        // Date/time/duration equality: compare by serial value.
        // This matches criteria semantics (COUNTIF(S), SUMIF(S), database criteria, etc.) where
        // date-like values participate in numeric comparisons.
        (x, y) if criteria_number(x).is_some() && criteria_number(y).is_some() => {
            criteria_number(x)
                .zip(criteria_number(y))
                .is_some_and(|(sx, sy)| (sx - sy).abs() < 1e-12)
        }
        // A number equals numeric text (Excel's criteria coerce text), but never a
        // blank cell, a boolean or an error.
        (LiteralValue::Number(_) | LiteralValue::Int(_), LiteralValue::Text(_)) => {
            criteria_number(a)
                .zip(value_to_number(b).ok())
                .is_some_and(|(x, y)| (x - y).abs() < 1e-12)
        }
        (LiteralValue::Text(_), LiteralValue::Number(_) | LiteralValue::Int(_)) => {
            values_equal_invariant(b, a)
        }
        _ => false,
    }
}

/// Wildcard criteria match text cells only: Excel never matches a number,
/// boolean, error or blank cell against `*`, `?` or `~` patterns.
fn text_like_match(pattern: &str, case_insensitive: bool, v: &LiteralValue) -> bool {
    let s = match v {
        LiteralValue::Text(t) => t.as_str(),
        _ => return false,
    };
    let (pat, text) = if case_insensitive {
        (pattern.to_lowercase(), s.to_lowercase())
    } else {
        (pattern.to_string(), s.to_string())
    };

    // Fast-path for anchored patterns without '?' or escape sequences
    if !pat.contains('?') && !pat.contains('~') {
        // Pattern like "text*" - starts with
        if pat.ends_with('*') && !pat[..pat.len() - 1].contains('*') {
            return text.starts_with(&pat[..pat.len() - 1]);
        }
        // Pattern like "*text" - ends with
        if pat.starts_with('*') && !pat[1..].contains('*') {
            return text.ends_with(&pat[1..]);
        }
        // Pattern like "*text*" - contains
        if pat.starts_with('*') && pat.ends_with('*') && !pat[1..pat.len() - 1].contains('*') {
            return text.contains(&pat[1..pat.len() - 1]);
        }
        // Pattern with no wildcards - exact match
        if !pat.contains('*') {
            return text == pat;
        }
    }

    // Fall back to general wildcard matching for complex patterns
    wildcard_match(&pat, &text)
}

fn wildcard_match(pat: &str, text: &str) -> bool {
    wildcard_match_units(pat.as_bytes(), text.as_bytes(), false)
}

/// Match spreadsheet wildcards without recursive branching or token allocation.
/// `~` escapes only `*`, `?`, and `~`; other/trailing tildes remain literal.
/// Criteria retain byte matching; SEARCH supplies characters and accepts a prefix.
/// Only the latest star needs a retry position: it can absorb any intervening text.
/// Space is O(1), with at most O(pattern length * text length) matching work.
pub(crate) fn wildcard_match_units<T: Copy + Eq + From<u8>>(
    pattern: &[T],
    text: &[T],
    prefix: bool,
) -> bool {
    let star = T::from(b'*');
    let question = T::from(b'?');
    let tilde = T::from(b'~');
    let (mut p, mut t) = (0, 0);
    let mut retry = None;
    loop {
        if p == pattern.len() && (prefix || t == text.len()) {
            return true;
        }
        if let Some(&unit) = pattern.get(p) {
            let escaped = unit == tilde
                && pattern
                    .get(p + 1)
                    .is_some_and(|&next| next == star || next == question || next == tilde);
            if !escaped && unit == star {
                p += 1;
                retry = Some((p, t));
                continue;
            }
            let literal = if escaped { pattern[p + 1] } else { unit };
            if t < text.len() && ((!escaped && unit == question) || literal == text[t]) {
                p += if escaped { 2 } else { 1 };
                t += 1;
                continue;
            }
        }
        match retry {
            Some((after_star, consumed)) if consumed < text.len() => {
                t = consumed + 1;
                p = after_star;
                retry = Some((after_star, t));
            }
            _ => return false,
        }
    }
}

// ─────────────────────────────── ArgSchema presets ───────────────────────────────

/// Single scalar argument of any type.
/// Used by many unary or variadic-any functions (e.g., `LEN`, `TYPE`, simple wrappers).
pub static ARG_ANY_ONE: LazyLock<Vec<ArgSchema>> = LazyLock::new(|| vec![ArgSchema::any()]);

/// Two scalar arguments of any type.
/// Used by generic binary functions (e.g., comparisons, concatenation variants).
pub static ARG_ANY_TWO: LazyLock<Vec<ArgSchema>> =
    LazyLock::new(|| vec![ArgSchema::any(), ArgSchema::any()]);

/// Single numeric scalar argument, with lenient text-to-number coercion.
/// Ideal for elementwise numeric functions (e.g., `SIN`, `COS`, `ABS`).
pub static ARG_NUM_LENIENT_ONE: LazyLock<Vec<ArgSchema>> =
    LazyLock::new(|| vec![{ ArgSchema::number_lenient_scalar() }]);

/// Two numeric scalar arguments, with lenient text-to-number coercion.
/// Suited for binary numeric operations (e.g., `ATAN2`, `POWER`, `LOG(base)`).
pub static ARG_NUM_LENIENT_TWO: LazyLock<Vec<ArgSchema>> = LazyLock::new(|| {
    vec![{ ArgSchema::number_lenient_scalar() }, {
        ArgSchema::number_lenient_scalar()
    }]
});

/// Single range argument, numeric semantics with lenient text-to-number coercion.
/// Best for reductions over ranges (e.g., `SUM`, `AVERAGE`, `COUNT`-like families).
pub static ARG_RANGE_NUM_LENIENT_ONE: LazyLock<Vec<ArgSchema>> = LazyLock::new(|| {
    vec![{
        let mut s = ArgSchema::number_lenient_scalar();
        s.shape = ShapeKind::Range;
        s.coercion = CoercionPolicy::NumberLenientText;
        s
    }]
});