Skip to main content

visi_core/core/engine/sheet/
mod.rs

1//! The `Sheet` type: a worksheet's cells, its formula evaluation, and the
2//! dependency-tracked recalculation over them.
3
4mod edit;
5mod functions;
6
7pub use edit::get_word_boundaries_from_str;
8
9use serde::{Deserialize, Serialize};
10use std::collections::{HashMap, HashSet, VecDeque};
11use web_time::Instant;
12
13use super::cell::{CellRef, Dependency, EngineError, EvalError, TextCellRef, generate_unique_id};
14use super::column::DataColumn;
15use super::result_data::ResultData;
16/// Context for evaluating expressions, containing references to other sheets
17#[derive(Default)]
18pub struct Context<'a> {
19    /// Map of sheet names to sheet references for cross-sheet lookups
20    pub sheets: HashMap<String, &'a Sheet>,
21    /// Every pivot table in the workbook, so `GETPIVOTDATA` can resolve a
22    /// rendered pivot's destination cell back to its definition. Pivot
23    /// tables are workbook-level (like `Context.sheets`' cross-sheet
24    /// lookups), not sheet-scoped, so this lives here rather than on
25    /// `Sheet` itself.
26    pub pivot_tables: &'a [crate::core::pivot::PivotTable],
27    /// Sheet names in true workbook order, so `SHEET()` can report a real
28    /// ordinal. `sheets` is an unordered `HashMap`, which is why this is
29    /// tracked separately rather than derived from it -- true order only
30    /// exists one layer up, in `visi`'s `WorkbookManager::sheets` (a
31    /// `Vec`), which populates this when building the context.
32    pub sheet_order: Vec<String>,
33}
34
35impl<'a> Context<'a> {
36    /// Create a new empty context
37    pub fn new() -> Self {
38        Self {
39            sheets: HashMap::new(),
40            pivot_tables: &[],
41            sheet_order: Vec::new(),
42        }
43    }
44
45    /// Add a sheet to the context for lookup during evaluation
46    pub fn add_table(&mut self, name: String, sheet: &'a Sheet) {
47        self.sheets.insert(name, sheet);
48    }
49}
50
51/// A chain of LET name/value bindings in scope while evaluating a single
52/// formula. This is a linked list (not a cloned `HashMap`) because LET
53/// binds names one at a time -- each value expression, and the final
54/// calculation, must see all *earlier* bindings from the same LET (and any
55/// outer LET it's nested inside), and a name can shadow an outer binding of
56/// the same spelling. `evaluate_let` builds this chain by recursing one
57/// pair at a time rather than mutating a shared map.
58enum LetScope<'a> {
59    Empty,
60    Bound {
61        name: &'a str,
62        value: &'a ResultData,
63        parent: &'a LetScope<'a>,
64    },
65}
66
67impl<'a> LetScope<'a> {
68    fn get(&self, name: &str) -> Option<&ResultData> {
69        match self {
70            LetScope::Empty => None,
71            LetScope::Bound {
72                name: n,
73                value,
74                parent,
75            } => {
76                if n.eq_ignore_ascii_case(name) {
77                    Some(value)
78                } else {
79                    parent.get(name)
80                }
81            }
82        }
83    }
84}
85
86/// Which way a fill or selection extends from its anchor cell.
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub enum Direction {
89    /// No direction; the operation is a no-op.
90    None,
91    /// Toward row 0.
92    Up,
93    /// Toward the last row.
94    Down,
95    /// Toward column 0.
96    Left,
97    /// Toward the last column.
98    Right,
99}
100
101/// One worksheet: a grid of cells, the formulas over them, and the dependency
102/// graph that keeps them up to date.
103///
104/// # Coordinates
105///
106/// Everything here is **0-based `(row, col)`**. A1 notation exists only at the
107/// parser and CLI boundaries -- see [`parse_a1_coordinates`] and
108/// [`col_idx_to_letters`] to convert.
109///
110/// # Naming trap
111///
112/// A `Sheet` is informally called a "table" in places (a new one is named
113/// `table_1`, and `Context::add_table` registers one). That is *not* an
114/// [`ExcelTable`], which is a ListObject -- a named rectangular range *on* a
115/// sheet -- and lives in [`Sheet::tables`].
116///
117/// # Storage
118///
119/// Storage is column-oriented: each [`DataColumn`] keeps the raw user text,
120/// the computed values and the compiled formulas in three parallel vectors
121/// that must stay the same length. The row and column insert/delete paths
122/// maintain that invariant by hand, so a new one has to do the same.
123///
124/// # Recalculation
125///
126/// [`Sheet::commit`] recomputes the dirty cells and propagates through
127/// [`Dependency::Local`] and [`Dependency::LocalColumn`] edges only.
128/// Cross-sheet edges are `WorkbookManager::evaluate`'s job, and evaluating a
129/// formula with a remote reference requires a [`Context`] -- without one it
130/// errors.
131///
132/// [`parse_a1_coordinates`]: crate::core::parse_a1_coordinates
133/// [`col_idx_to_letters`]: crate::core::col_idx_to_letters
134/// [`ExcelTable`]: crate::core::table::ExcelTable
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct Sheet {
137    /// Workbook-unique identifier. Formulas compile references against this
138    /// rather than the name, which is what makes a rename non-destructive.
139    #[serde(default = "generate_unique_id")]
140    pub id: u64,
141    /// Display name, as it appears in a cross-sheet reference.
142    pub name: String,
143    /// The cells, one entry per column. Row `r` of column `c` is
144    /// `columns[c]`'s entry `r`.
145    ///
146    /// Every column has the same number of rows -- [`Sheet::row_count`] reads
147    /// only the first and assumes the rest match -- so the `Vec` itself is
148    /// crate-private. Read them through [`Sheet::columns`].
149    pub(crate) columns: Vec<DataColumn>,
150    /// Excel Tables (ListObjects) defined on this sheet.
151    #[serde(default)]
152    pub tables: Vec<crate::core::table::ExcelTable>,
153    /// Forward edges: which cells must be recomputed when a dependency
154    /// changes. Rebuilt from the formulas, so not serialized.
155    #[serde(skip, default)]
156    pub dependencies: HashMap<Dependency, HashSet<CellRef>>,
157    /// Reverse edges: what each cell currently reads, so its old edges can be
158    /// dropped when its formula changes. Rebuilt, so not serialized.
159    #[serde(skip, default)]
160    pub dependencies_rev: HashMap<CellRef, HashSet<Dependency>>,
161    /// Edits made since the last commit, for callers that want to observe or
162    /// replay them.
163    #[serde(skip)]
164    pub uncommitted_actions: Vec<crate::core::SheetAction>,
165}
166
167/// Arguments for [`Sheet::new`]. [`Default`] gives a 10x5 sheet with a
168/// generated id and the name `table_1`.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct SheetInit {
171    /// Identifier to use; `None` generates a fresh one.
172    #[serde(default)]
173    pub id: Option<u64>,
174    /// Name to use; `None` means `table_1`.
175    pub name: Option<String>,
176    /// Rows to allocate.
177    pub rows: usize,
178    /// Columns to allocate.
179    pub cols: usize,
180}
181
182impl Default for SheetInit {
183    fn default() -> Self {
184        Self {
185            id: None,
186            name: None,
187            rows: 10,
188            cols: 5,
189        }
190    }
191}
192
193/// How a blank cell is treated by the strict numeric flatteners.
194#[derive(Clone, Copy, PartialEq, Eq)]
195enum BlankPolicy {
196    /// Counts as 0 (GCD/LCM).
197    Zero,
198    /// Dropped entirely, shifting later elements (SERIESSUM).
199    Skip,
200    /// #VALUE!, like text (LINEST/TREND/GROWTH/LOGEST/MMULT).
201    Reject,
202}
203
204impl Sheet {
205    /// Creates a sheet of `args.rows` x `args.cols` empty cells, every one of
206    /// them queued as a pending edit so the first [`Sheet::commit`] sees them.
207    pub fn new(args: SheetInit) -> Sheet {
208        let SheetInit {
209            id,
210            name,
211            rows,
212            cols,
213        } = args;
214        let sheet_id = id.unwrap_or_else(generate_unique_id);
215        let sheet_name = name.unwrap_or_else(|| "table_1".to_string());
216
217        let mut columns = Vec::with_capacity(cols);
218        for _ in 0..cols {
219            columns.push(DataColumn::new(rows));
220        }
221
222        let mut uncommitted_actions = Vec::new();
223        for c in 0..cols {
224            for r in 0..rows {
225                uncommitted_actions.push(crate::core::SheetAction::SetCellSrc {
226                    sheet_name: sheet_name.clone(),
227                    col: c,
228                    row: r,
229                    src: String::new(),
230                });
231            }
232        }
233
234        Self {
235            id: sheet_id,
236            name: sheet_name,
237            columns,
238            tables: Vec::new(),
239            dependencies: HashMap::new(),
240            dependencies_rev: HashMap::new(),
241            uncommitted_actions,
242        }
243    }
244
245    /// Rebuilds what serialization drops.
246    ///
247    /// Only the raw source text is persisted, so this resizes the value and
248    /// compiled-formula vectors back to match it -- restoring the
249    /// same-length invariant -- and marks everything dirty. Call it after
250    /// deserializing, before [`Sheet::commit`].
251    pub fn setup_after_deserialization(&mut self) {
252        for col in &mut self.columns {
253            col.rebuild_after_load();
254        }
255        self.mark_all_dirty();
256    }
257
258    /// Every sheet a formula on this one could refer to -- this sheet first,
259    /// then the rest of `context` -- as the name-to-id lookup table that
260    /// `compile_formula` resolves references against.
261    ///
262    /// "Tables" here means sheets, not [`ExcelTable`]s.
263    ///
264    /// [`ExcelTable`]: crate::core::table::ExcelTable
265    pub(crate) fn get_all_tables_for_compilation(&self, context: Option<&Context>) -> Vec<Sheet> {
266        let mut list = vec![self.clone()];
267        let mut seen = std::collections::HashSet::new();
268        seen.insert(self.id);
269        if let Some(ctx) = context {
270            for t in ctx.sheets.values() {
271                if !seen.contains(&t.id) {
272                    seen.insert(t.id);
273                    list.push((*t).clone());
274                }
275            }
276        }
277        list
278    }
279
280    /// Queues every cell for recomputation on the next [`Sheet::commit`].
281    ///
282    /// This is how cross-sheet staleness is handled: `WorkbookManager` cannot
283    /// tell which cells a remote edit reached, so it marks whole sheets.
284    pub fn mark_all_dirty(&mut self) {
285        for col in &mut self.columns {
286            col.dirty_indices.clear();
287            col.dirty_indices.extend(0..col.src.len());
288        }
289    }
290
291    /// Commit all changed src items with a context for sheet lookups
292    pub fn commit(&mut self, context: Option<&Context>) -> Result<HashSet<CellRef>, EngineError> {
293        let mut queue: VecDeque<CellRef> = VecDeque::new();
294        let mut queue_set: HashSet<CellRef> = HashSet::new();
295        let mut updated_cells: HashSet<CellRef> = HashSet::new();
296
297        // 1. Collect initial dirty cells
298        for (col_idx, col_data) in self.columns.iter_mut().enumerate() {
299            for row_idx in &col_data.dirty_indices {
300                let cell = CellRef::new(*row_idx, col_idx);
301                queue.push_back(cell);
302                queue_set.insert(cell);
303                updated_cells.insert(cell);
304            }
305            col_data.dirty_indices.clear();
306        }
307
308        let initial_queue_len = queue.len();
309        if initial_queue_len == 0 {
310            return Ok(updated_cells);
311        }
312
313        let start_commit = Instant::now();
314        log::info!(
315            "Sheet '{}' commit starting for {} dirty cells",
316            self.name,
317            initial_queue_len
318        );
319        let max_ops = 10000.max(initial_queue_len * 3);
320        let mut ops = 0;
321
322        let mut tables_for_compilation = self.get_all_tables_for_compilation(context);
323        let mut last_log_time = Instant::now();
324
325        while let Some(cell_ref) = queue.pop_front() {
326            queue_set.remove(&cell_ref);
327            ops += 1;
328            if ops > max_ops {
329                println!("Circular dependency or too many updates detected");
330                break;
331            }
332
333            if ops % 50000 == 0 {
334                log::info!(
335                    "Sheet '{}' commit progress: {}/{} cells processed ({:.2?})",
336                    self.name,
337                    ops,
338                    initial_queue_len,
339                    last_log_time.elapsed()
340                );
341                last_log_time = Instant::now();
342            }
343
344            // `Some(code)` when this cell's literal was recognized as a date;
345            // applied below, since detecting it only has `&self`.
346            let mut detected_num_format: Option<String> = None;
347            let (result, new_deps, compiled_to_cache) = {
348                let src = self.get_src_str_ref(&cell_ref).unwrap_or("");
349                if !src.starts_with('=') {
350                    // Numeric text is trimmed before it is parsed, because
351                    // that is what entering it does: a cell given `"  3  "`
352                    // holds the *number* 3, in Excel and (measured through
353                    // `fuzz/fuzz_vba.py`, where a macro assigned exactly that
354                    // string) through VBA's `Range.Value` as well.
355                    // `xlsx::text_cell_src` trims to match when deciding
356                    // whether an imported *text* cell needs quoting.
357                    let res = if src.is_empty() {
358                        ResultData::None
359                    } else if src.starts_with('"') && src.ends_with('"') && src.len() >= 2 {
360                        ResultData::String(src[1..src.len() - 1].to_string())
361                    } else if let Ok(i) = src.trim().parse::<i64>() {
362                        ResultData::Integer(i)
363                    } else if let Ok(f) = src.trim().parse::<f64>()
364                        // Rust's `f64::from_str` accepts "inf" and "NaN";
365                        // Excel has neither, and reports #NUM! for both. A
366                        // non-finite literal here would otherwise become a
367                        // Float that no formula could have produced -- found
368                        // by `fuzz/fuzz_vba.py`, where a macro assigned
369                        // `-2.5 ^ 1000` to a cell and this stored `-inf`
370                        // where Excel stored `#NUM!`.
371                        && f.is_finite()
372                    {
373                        ResultData::Float(f)
374                    } else if crate::core::engine::result_data::is_excel_error_code(src) {
375                        // Typing an error value into a cell produces the
376                        // error, not the text. See `is_excel_error_code`.
377                        ResultData::Error(src.to_uppercase())
378                    } else if src.eq_ignore_ascii_case("true") {
379                        ResultData::Boolean(true)
380                    } else if src.eq_ignore_ascii_case("false") {
381                        ResultData::Boolean(false)
382                    } else if let Some((date, format)) =
383                        crate::core::date::parse_date(src.trim_matches(' '))
384                    {
385                        // Excel stores a typed date as a serial and remembers
386                        // the notation as the cell's number format, so `6/22/26`
387                        // is a number that happens to display as a date.
388                        detected_num_format = Some(format.to_format_code());
389                        ResultData::Float(crate::core::date::date_to_excel_serial(date))
390                    } else {
391                        ResultData::String(src.to_string())
392                    };
393                    (res, vec![], None)
394                } else {
395                    let compiled =
396                        crate::core::parser::compile_formula(src, &tables_for_compilation);
397                    let eval_src =
398                        crate::core::parser::serialize_formula(&compiled, &tables_for_compilation);
399                    let (res, deps) = match self.eval_with_row(
400                        &eval_src,
401                        context,
402                        Some(cell_ref.row),
403                        Some(cell_ref.col),
404                    ) {
405                        Ok(r) => r,
406                        Err(e) => (ResultData::Error(e.to_string()), vec![]),
407                    };
408                    let final_res = if let ResultData::None = res {
409                        ResultData::Float(0.0)
410                    } else {
411                        res
412                    };
413                    (final_res, deps, Some(compiled))
414                }
415            };
416
417            // Write compiled cache
418            if let Some(col) = self.columns.get_mut(cell_ref.col)
419                && cell_ref.row < col.compiled_src.len()
420            {
421                col.compiled_src[cell_ref.row] = compiled_to_cache.unwrap_or_default();
422            }
423
424            // Update dependencies
425            // 1. Remove old reverse dependencies
426            if let Some(old_deps) = self.dependencies_rev.remove(&cell_ref) {
427                for provider in old_deps {
428                    if let Some(dependents) = self.dependencies.get_mut(&provider) {
429                        dependents.remove(&cell_ref);
430                    }
431                }
432            }
433
434            // 2. Add new dependencies (only if not empty to save map allocations)
435            if !new_deps.is_empty() {
436                let mut new_deps_set = HashSet::new();
437                for provider in new_deps {
438                    new_deps_set.insert(provider.clone());
439                    self.dependencies
440                        .entry(provider)
441                        .or_default()
442                        .insert(cell_ref);
443                }
444                self.dependencies_rev.insert(cell_ref, new_deps_set);
445            }
446
447            // A recognized date literal carries its notation onto the cell,
448            // and a formula that shifts a date by a number inherits that
449            // date's -- `=A1+1` on a date displays as the next day, as in
450            // Excel, rather than as a bare serial.
451            let inherited = if detected_num_format.is_some()
452                || !matches!(result, ResultData::Float(_) | ResultData::Integer(_))
453            {
454                None
455            } else {
456                self.get_src_str_ref(&cell_ref)
457                    .and_then(|src| src.strip_prefix('='))
458                    .and_then(|body| crate::core::parser::parse_excel_formula(body).ok())
459                    .and_then(|ast| self.inherited_date_format(&ast))
460            };
461            // An explicit format the user (or an imported worksheet) already
462            // set wins, so re-entering a date does not clobber it.
463            if let Some(code) = detected_num_format.or(inherited) {
464                let existing = self
465                    .get_cell_style(cell_ref.row, cell_ref.col)
466                    .and_then(|s| s.num_format.clone());
467                if existing.is_none() {
468                    self.update_cell_style(cell_ref.row, cell_ref.col, |style| {
469                        style.num_format = Some(code);
470                    });
471                }
472            }
473
474            // Update data
475            if let Some(col) = self.columns.get_mut(cell_ref.col)
476                && cell_ref.row < col.data.len()
477            {
478                col.data.set(cell_ref.row, result.clone());
479                updated_cells.insert(cell_ref);
480            }
481            if let Some(comp_sheet) = tables_for_compilation
482                .iter_mut()
483                .find(|s| s.name == self.name)
484                && let Some(col) = comp_sheet.columns.get_mut(cell_ref.col)
485                && cell_ref.row < col.data.len()
486            {
487                col.data.set(cell_ref.row, result);
488            }
489
490            // Propagate to dependents (Local only)
491            // If this cell changed, we need to notify anyone who depends on THIS cell (locally).
492            // A local dependency is represented as Dependency::Local(this_cell).
493            let local_dep_key = Dependency::Local(cell_ref);
494            if let Some(dependents) = self.dependencies.get(&local_dep_key) {
495                for dependent in dependents {
496                    if !queue_set.contains(dependent) {
497                        queue.push_back(*dependent);
498                        queue_set.insert(*dependent);
499                    }
500                }
501            }
502
503            // Also notify anyone who depends on the whole COLUMN
504            let local_col_dep_key = Dependency::LocalColumn(cell_ref.col);
505            if let Some(dependents) = self.dependencies.get(&local_col_dep_key) {
506                for dependent in dependents {
507                    if !queue_set.contains(dependent) {
508                        queue.push_back(*dependent);
509                        queue_set.insert(*dependent);
510                    }
511                }
512            }
513        }
514        if initial_queue_len > 0 {
515            log::info!(
516                "Sheet '{}' commit finished. Processed {} cell updates. Total time: {:.2?}",
517                self.name,
518                ops,
519                start_commit.elapsed()
520            );
521        }
522        Ok(updated_cells)
523    }
524
525    /// Evaluates cell source text without storing it, as
526    /// [`Sheet::eval`] does, but from the point of view of `(row, col)`.
527    ///
528    /// The position is what makes relative constructs work -- a structured
529    /// reference like `[@Amount]` means "this row", so it needs to know which
530    /// row is asking. Pass `None` for both when there is no anchor.
531    ///
532    /// # Errors
533    ///
534    /// Returns an [`EngineError`] if the formula cannot be parsed. An *Excel*
535    /// error is not a Rust error: `=1/0` succeeds, returning
536    /// `ResultData::Error("#DIV/0!")`.
537    pub fn eval_with_row(
538        &self,
539        input: &str,
540        context: Option<&Context>,
541        row: Option<usize>,
542        col: Option<usize>,
543    ) -> Result<(ResultData, Vec<Dependency>), EngineError> {
544        if input.is_empty() {
545            return Ok((ResultData::None, vec![]));
546        }
547        if let Some(formula) = input.strip_prefix('=') {
548            self.eval_excel(formula, context, row, col)
549        } else {
550            if let Ok(i) = input.parse::<i64>() {
551                Ok((ResultData::Integer(i), vec![]))
552            } else if let Ok(f) = input.parse::<f64>() {
553                Ok((ResultData::Float(f), vec![]))
554            } else if let Ok(b) = input.parse::<bool>() {
555                Ok((ResultData::Boolean(b), vec![]))
556            } else {
557                Ok((ResultData::String(input.to_string()), vec![]))
558            }
559        }
560    }
561
562    /// Evaluates cell source text against this sheet without storing it,
563    /// returning the value and the references it read.
564    ///
565    /// Text with a leading `=` is a formula; anything else is parsed as a
566    /// literal. `context` supplies the other sheets, and is required for a
567    /// cross-sheet reference to resolve.
568    ///
569    /// # Errors
570    ///
571    /// Returns an [`EngineError`] if the formula cannot be parsed. An *Excel*
572    /// error is not a Rust error: `=1/0` succeeds, returning
573    /// `ResultData::Error("#DIV/0!")`.
574    pub fn eval(
575        &self,
576        input: &str,
577        context: Option<&Context>,
578    ) -> Result<(ResultData, Vec<Dependency>), EngineError> {
579        self.eval_with_row(input, context, None, None)
580    }
581
582    fn eval_excel(
583        &self,
584        code: &str,
585        context: Option<&Context>,
586        row: Option<usize>,
587        col: Option<usize>,
588    ) -> Result<(ResultData, Vec<Dependency>), EngineError> {
589        let ast = crate::core::parser::parse_excel_formula(code)
590            .map_err(|e| EngineError::EvalError(EvalError::UnknownFunction(e)))?;
591
592        let mut deps = Vec::new();
593        let result = match self.evaluate_ast(&ast, context, row, col, &mut deps, &LetScope::Empty) {
594            Ok(r) => r,
595            Err(EngineError::EvalError(EvalError::UnknownFunction(err_str)))
596                if err_str.starts_with('#') =>
597            {
598                ResultData::Error(err_str)
599            }
600            Err(e) => return Err(e),
601        };
602        Ok((result, deps))
603    }
604
605    fn evaluate_ast(
606        &self,
607        ast: &crate::core::parser::Expr,
608        context: Option<&Context>,
609        row: Option<usize>,
610        col: Option<usize>,
611        deps: &mut Vec<Dependency>,
612        scope: &LetScope<'_>,
613    ) -> Result<ResultData, EngineError> {
614        use crate::core::SheetSection;
615        use crate::core::parser::Expr;
616        use crate::core::parser::Op;
617
618        match ast {
619            Expr::Number(n) => Ok(ResultData::Float(*n)),
620            Expr::String(s) => Ok(ResultData::String(s.clone())),
621            Expr::Boolean(b) => Ok(ResultData::Boolean(*b)),
622            Expr::Error(code) => Ok(ResultData::Error(code.to_string())),
623            Expr::Identifier(name) => match scope.get(name) {
624                Some(val) => Ok(val.clone()),
625                None => Ok(ResultData::Error("#NAME?".to_string())),
626            },
627            Expr::StructuredRef {
628                sheet,
629                column,
630                is_this_row,
631                section,
632            } => {
633                let ref_name = match sheet {
634                    Some(name) => name.clone(),
635                    None => self.name.clone(),
636                };
637
638                // The leading name of a structured reference is first looked up as
639                // a real Excel Table (an `ExcelTable` may live on any sheet in
640                // scope, and is scoped to its own row/column range). If no such
641                // table exists, fall back to the legacy behavior of treating the
642                // name as a sheet name and the whole sheet as an implicit table --
643                // this keeps existing formulas working for sheets that don't
644                // define any explicit table.
645                let mut found: Option<(&Sheet, &crate::core::table::ExcelTable)> =
646                    self.find_table(&ref_name).map(|t| (self, t));
647                if found.is_none()
648                    && let Some(ctx) = context
649                {
650                    for s in ctx.sheets.values() {
651                        if let Some(t) = s.find_table(&ref_name) {
652                            found = Some((s, t));
653                            break;
654                        }
655                    }
656                }
657
658                if let Some((table_sheet, excel_table)) = found {
659                    let is_self = table_sheet.name == self.name;
660                    let sheet_name = table_sheet.name.clone();
661
662                    // (local index within the table, absolute sheet column index)
663                    let col_indices: Vec<(usize, usize)> = if let Some(col_name) = column {
664                        let local = excel_table.local_column_index(col_name).ok_or_else(|| {
665                            EngineError::EvalError(EvalError::UnknownFunction(format!(
666                                "Column not found: {}",
667                                col_name
668                            )))
669                        })?;
670                        vec![(local, excel_table.start_col + local)]
671                    } else {
672                        (0..excel_table.columns.len())
673                            .map(|local| (local, excel_table.start_col + local))
674                            .collect()
675                    };
676                    let is_whole_table = column.is_none();
677
678                    match section {
679                        SheetSection::Headers => {
680                            let names: Vec<ResultData> = col_indices
681                                .iter()
682                                .map(|&(local, _)| {
683                                    ResultData::String(
684                                        excel_table.columns.get(local).cloned().unwrap_or_default(),
685                                    )
686                                })
687                                .collect();
688                            if is_whole_table {
689                                Ok(ResultData::List(names))
690                            } else {
691                                Ok(names.into_iter().next().unwrap_or(ResultData::None))
692                            }
693                        }
694                        SheetSection::Totals => {
695                            if let Some(totals_row) = excel_table.totals_row() {
696                                let mut results = Vec::new();
697                                for &(_, col_idx) in &col_indices {
698                                    let cell_ref = CellRef::new(totals_row, col_idx);
699                                    if is_self {
700                                        deps.push(Dependency::Local(cell_ref));
701                                    } else {
702                                        deps.push(Dependency::Remote {
703                                            sheet: sheet_name.clone(),
704                                            cell: cell_ref,
705                                        });
706                                    }
707                                    results.push(table_sheet.get_result_data(&cell_ref));
708                                }
709                                if is_whole_table {
710                                    Ok(ResultData::List(results))
711                                } else {
712                                    Ok(results.into_iter().next().unwrap_or(ResultData::None))
713                                }
714                            } else {
715                                Ok(ResultData::None)
716                            }
717                        }
718                        SheetSection::Data | SheetSection::All => {
719                            if *is_this_row {
720                                let r = row.ok_or_else(|| {
721                                    EngineError::EvalError(EvalError::UnknownFunction(
722                                        "This row reference cannot be evaluated without row context"
723                                            .to_string(),
724                                    ))
725                                })?;
726                                let mut results = Vec::new();
727                                for &(_, col_idx) in &col_indices {
728                                    let cell_ref = CellRef::new(r, col_idx);
729                                    if is_self {
730                                        deps.push(Dependency::Local(cell_ref));
731                                    } else {
732                                        deps.push(Dependency::Remote {
733                                            sheet: sheet_name.clone(),
734                                            cell: cell_ref,
735                                        });
736                                    }
737                                    results.push(table_sheet.get_result_data(&cell_ref));
738                                }
739                                if is_whole_table {
740                                    Ok(ResultData::List(results))
741                                } else {
742                                    Ok(results.into_iter().next().unwrap_or(ResultData::None))
743                                }
744                            } else {
745                                // A table's column reference is bounded to
746                                // its own data rows, not the whole sheet
747                                // column -- so, like any other bounded range
748                                // (e.g. A1:A100), each cell in that range
749                                // gets its own dependency rather than a
750                                // whole-column one. Otherwise a formula
751                                // placed in the same column but *outside*
752                                // the table (a common layout, since summary
753                                // formulas often sit right below or beside
754                                // a table) would register a dependency on
755                                // its own cell and falsely trip circular-
756                                // dependency detection, which real Excel
757                                // does not do.
758                                let mut results = Vec::new();
759                                for &(_, col_idx) in &col_indices {
760                                    for r in
761                                        excel_table.data_start_row()..=excel_table.data_end_row()
762                                    {
763                                        let cell_ref = CellRef::new(r, col_idx);
764                                        if is_self {
765                                            deps.push(Dependency::Local(cell_ref));
766                                        } else {
767                                            deps.push(Dependency::Remote {
768                                                sheet: sheet_name.clone(),
769                                                cell: cell_ref,
770                                            });
771                                        }
772                                        results.push(table_sheet.get_result_data(&cell_ref));
773                                    }
774                                }
775                                Ok(ResultData::List(results))
776                            }
777                        }
778                    }
779                } else {
780                    // Legacy fallback: no explicit ExcelTable found by that name --
781                    // resolve `ref_name` as a sheet name and treat the whole sheet
782                    // as an implicit table.
783                    let sheet_name = ref_name;
784                    let is_self = sheet_name == self.name;
785
786                    let target_table = if is_self {
787                        self
788                    } else if let Some(ctx) = context {
789                        if let Some(t) = ctx.sheets.get(&sheet_name) {
790                            t
791                        } else {
792                            return Err(EngineError::EvalError(EvalError::UnknownFunction(
793                                format!("Sheet not found: {}", sheet_name),
794                            )));
795                        }
796                    } else {
797                        return Err(EngineError::EvalError(EvalError::UnknownFunction(format!(
798                            "No context to resolve sheet reference: {}",
799                            sheet_name
800                        ))));
801                    };
802
803                    // `column: None` means the reference spans every column in the
804                    // table (e.g. `Table1[#Data]` or `[@]`), rather than a single
805                    // named column.
806                    let col_indices: Vec<usize> = if let Some(col_name) = column {
807                        let pos = target_table
808                            .columns
809                            .iter()
810                            .position(|c| c.name == *col_name)
811                            .ok_or_else(|| {
812                                EngineError::EvalError(EvalError::UnknownFunction(format!(
813                                    "Column not found: {}",
814                                    col_name
815                                )))
816                            })?;
817                        vec![pos]
818                    } else {
819                        (0..target_table.columns.len()).collect()
820                    };
821                    let is_whole_table = column.is_none();
822
823                    match section {
824                        SheetSection::Headers => {
825                            let names: Vec<ResultData> = col_indices
826                                .iter()
827                                .map(|&idx| {
828                                    ResultData::String(
829                                        target_table
830                                            .columns
831                                            .get(idx)
832                                            .map(|c| c.name.clone())
833                                            .unwrap_or_default(),
834                                    )
835                                })
836                                .collect();
837                            if is_whole_table {
838                                Ok(ResultData::List(names))
839                            } else {
840                                Ok(names.into_iter().next().unwrap_or(ResultData::None))
841                            }
842                        }
843                        SheetSection::Totals => Ok(ResultData::None),
844                        SheetSection::Data | SheetSection::All => {
845                            if *is_this_row {
846                                let r = row.ok_or_else(|| {
847                                    EngineError::EvalError(EvalError::UnknownFunction(
848                                        "This row reference cannot be evaluated without row context"
849                                            .to_string(),
850                                    ))
851                                })?;
852                                let mut results = Vec::new();
853                                for &col_idx in &col_indices {
854                                    let cell_ref = CellRef::new(r, col_idx);
855                                    if is_self {
856                                        deps.push(Dependency::Local(cell_ref));
857                                    } else {
858                                        deps.push(Dependency::Remote {
859                                            sheet: sheet_name.clone(),
860                                            cell: cell_ref,
861                                        });
862                                    }
863                                    results.push(target_table.get_result_data(&cell_ref));
864                                }
865                                if is_whole_table {
866                                    Ok(ResultData::List(results))
867                                } else {
868                                    Ok(results.into_iter().next().unwrap_or(ResultData::None))
869                                }
870                            } else {
871                                let mut results = Vec::new();
872                                for &col_idx in &col_indices {
873                                    if is_self {
874                                        deps.push(Dependency::LocalColumn(col_idx));
875                                    } else {
876                                        deps.push(Dependency::RemoteColumn {
877                                            sheet: sheet_name.clone(),
878                                            col: col_idx,
879                                        });
880                                    }
881                                    for r in 0..target_table.row_count() {
882                                        let cell_ref = CellRef::new(r, col_idx);
883                                        results.push(target_table.get_result_data(&cell_ref));
884                                    }
885                                }
886                                Ok(ResultData::List(results))
887                            }
888                        }
889                    }
890                }
891            }
892            Expr::CellRef {
893                sheet,
894                row: r_val,
895                col,
896                ..
897            } => {
898                let cell_ref = CellRef::new(*r_val, *col);
899                let is_self = match sheet {
900                    Some(name) => name == &self.name,
901                    None => true,
902                };
903
904                if is_self {
905                    deps.push(Dependency::Local(cell_ref));
906                    Ok(self.get_result_data(&cell_ref))
907                } else {
908                    let name = sheet.as_ref().unwrap().clone();
909                    deps.push(Dependency::Remote {
910                        sheet: name.clone(),
911                        cell: cell_ref,
912                    });
913
914                    if let Some(ctx) = context {
915                        if let Some(t) = ctx.sheets.get(&name) {
916                            Ok(t.get_result_data(&cell_ref))
917                        } else {
918                            Err(EngineError::EvalError(EvalError::UnknownFunction(format!(
919                                "Sheet not found: {}",
920                                name
921                            ))))
922                        }
923                    } else {
924                        Err(EngineError::EvalError(EvalError::UnknownFunction(
925                            "No context to resolve sheet reference".to_string(),
926                        )))
927                    }
928                }
929            }
930            Expr::RangeRef {
931                sheet,
932                start_row,
933                start_col,
934                end_row,
935                end_col,
936                ..
937            } => {
938                let is_self = match sheet {
939                    Some(name) => name == &self.name,
940                    None => true,
941                };
942
943                let actual_end_row = if *end_row == usize::MAX {
944                    if is_self {
945                        self.row_count().saturating_sub(1)
946                    } else if let Some(ctx) = context {
947                        ctx.sheets
948                            .get(sheet.as_ref().unwrap())
949                            .map(|t| t.row_count().saturating_sub(1))
950                            .unwrap_or(0)
951                    } else {
952                        0
953                    }
954                } else {
955                    *end_row
956                };
957
958                let is_col_range = *end_row == usize::MAX;
959
960                // A whole-column range's dependency is scoped to the
961                // *column*, not each individual cell, but the loop below
962                // still visits every (row, col) pair -- without tracking
963                // which columns this range has already registered, the
964                // `deps.contains` scan below (needed for correctness
965                // against whatever `deps` already held coming in) would
966                // run once per *cell* instead of once per *column*, i.e.
967                // O(width * height * deps.len()) instead of O(width *
968                // deps.len()). For a wide range (e.g. `=C:LL`, 322
969                // columns) evaluated repeatedly (e.g. inside a self-
970                // referential formula bounded by commit()'s max_ops, see
971                // the fix just above), that quadratic-in-width blowup was
972                // the difference between finishing in under a second and
973                // taking tens of seconds to minutes -- found via the same
974                // visi-core/fuzz formula_eval run (#26).
975                let mut seen_col_deps: HashSet<usize> = HashSet::new();
976
977                let mut results = Vec::new();
978                for r in *start_row..=actual_end_row {
979                    for c in *start_col..=*end_col {
980                        let cell_ref = CellRef::new(r, c);
981                        if is_self {
982                            if is_col_range {
983                                if seen_col_deps.insert(c) {
984                                    let col_dep = Dependency::LocalColumn(c);
985                                    if !deps.contains(&col_dep) {
986                                        deps.push(col_dep);
987                                    }
988                                }
989                            } else {
990                                deps.push(Dependency::Local(cell_ref));
991                            }
992                            // A range that includes the very cell this
993                            // formula lives in (most commonly a bare,
994                            // unaggregated whole-column/whole-row range
995                            // like `=C:P` sitting inside columns C..P)
996                            // must not read that cell's own currently
997                            // stored value back into itself: on every
998                            // recompute the stored value *is* this List,
999                            // so reading it back would nest a List inside
1000                            // itself one level deeper each pass --
1001                            // unbounded growth that only stops at a stack
1002                            // overflow in recursive Clone/Drop, found via
1003                            // visi-core/fuzz's formula_eval target (#26).
1004                            // Blank matches this engine's existing
1005                            // convention for an unresolvable self-read
1006                            // elsewhere (e.g. ISBLANK(GET(...)) on an
1007                            // empty cell).
1008                            if row == Some(r) && col == Some(c) {
1009                                results.push(ResultData::None);
1010                            } else {
1011                                results.push(self.get_result_data(&cell_ref));
1012                            }
1013                        } else {
1014                            let name = sheet.as_ref().unwrap().clone();
1015                            if is_col_range {
1016                                if seen_col_deps.insert(c) {
1017                                    let col_dep = Dependency::RemoteColumn {
1018                                        sheet: name.clone(),
1019                                        col: c,
1020                                    };
1021                                    if !deps.contains(&col_dep) {
1022                                        deps.push(col_dep);
1023                                    }
1024                                }
1025                            } else {
1026                                deps.push(Dependency::Remote {
1027                                    sheet: name.clone(),
1028                                    cell: cell_ref,
1029                                });
1030                            }
1031                            if let Some(ctx) = context {
1032                                if let Some(t) = ctx.sheets.get(&name) {
1033                                    results.push(t.get_result_data(&cell_ref));
1034                                } else {
1035                                    return Err(EngineError::EvalError(
1036                                        EvalError::UnknownFunction(format!(
1037                                            "Sheet not found: {}",
1038                                            name
1039                                        )),
1040                                    ));
1041                                }
1042                            } else {
1043                                return Err(EngineError::EvalError(EvalError::UnknownFunction(
1044                                    "No context to resolve sheet reference".to_string(),
1045                                )));
1046                            }
1047                        }
1048                    }
1049                }
1050                Ok(ResultData::List(results))
1051            }
1052            Expr::List(list) => {
1053                let mut results = Vec::new();
1054                for item in list {
1055                    results.push(self.evaluate_ast(item, context, row, col, deps, scope)?);
1056                }
1057                Ok(ResultData::List(results))
1058            }
1059            Expr::UnaryOp { op, expr } => {
1060                let val = self.evaluate_ast(expr, context, row, col, deps, scope)?;
1061                match op {
1062                    Op::Sub => match val {
1063                        ResultData::Float(f) => Ok(ResultData::Float(-f)),
1064                        ResultData::Integer(i) => Ok(ResultData::Integer(-i)),
1065                        _ => Err(EngineError::EvalError(EvalError::UnknownFunction(
1066                            "Unary minus expects number".to_string(),
1067                        ))),
1068                    },
1069                    _ => Ok(val),
1070                }
1071            }
1072            Expr::BinaryOp { op, left, right } => {
1073                let l_val = self.evaluate_ast(left, context, row, col, deps, scope)?;
1074                let r_val = self.evaluate_ast(right, context, row, col, deps, scope)?;
1075
1076                match op {
1077                    Op::Eq | Op::Ne | Op::Lt | Op::Gt | Op::Le | Op::Ge => {
1078                        if let ResultData::Error(_) = &l_val {
1079                            return Ok(l_val);
1080                        }
1081                        if let ResultData::Error(_) = &r_val {
1082                            return Ok(r_val);
1083                        }
1084                        let ord = Self::compare_excel_values(&l_val, &r_val);
1085                        let b = match op {
1086                            Op::Eq => ord.is_eq(),
1087                            Op::Ne => !ord.is_eq(),
1088                            Op::Lt => ord.is_lt(),
1089                            Op::Gt => ord.is_gt(),
1090                            Op::Le => ord.is_le(),
1091                            Op::Ge => ord.is_ge(),
1092                            _ => unreachable!(),
1093                        };
1094                        Ok(ResultData::Boolean(b))
1095                    }
1096                    _ => {
1097                        if let ResultData::Error(_) = &l_val {
1098                            return Ok(l_val);
1099                        }
1100                        let lf = match self.to_f64(&l_val) {
1101                            Some(f) => f,
1102                            None => return Ok(ResultData::Error("#VALUE!".to_string())),
1103                        };
1104                        if let ResultData::Error(_) = &r_val {
1105                            return Ok(r_val);
1106                        }
1107                        let rf = match self.to_f64(&r_val) {
1108                            Some(f) => f,
1109                            None => return Ok(ResultData::Error("#VALUE!".to_string())),
1110                        };
1111                        match op {
1112                            Op::Add => Ok(ResultData::Float(lf + rf)),
1113                            Op::Sub => Ok(ResultData::Float(lf - rf)),
1114                            Op::Mul => Ok(ResultData::Float(lf * rf)),
1115                            Op::Div => {
1116                                if rf == 0.0 {
1117                                    return Ok(ResultData::Error("#DIV/0!".to_string()));
1118                                }
1119                                Ok(ResultData::Float(lf / rf))
1120                            }
1121                            Op::Exp => {
1122                                if lf == 0.0 && rf == 0.0 {
1123                                    return Ok(ResultData::Error("#NUM!".to_string()));
1124                                }
1125                                if lf == 0.0 && rf < 0.0 {
1126                                    return Ok(ResultData::Error("#DIV/0!".to_string()));
1127                                }
1128                                if lf < 0.0 {
1129                                    if rf.fract() != 0.0 || rf.abs() > 1e6 {
1130                                        return Ok(ResultData::Error("#NUM!".to_string()));
1131                                    }
1132                                    let res = lf.powi(rf as i32);
1133                                    if res.is_nan() || res.is_infinite() {
1134                                        return Ok(ResultData::Error("#NUM!".to_string()));
1135                                    }
1136                                    return Ok(ResultData::Float(res));
1137                                }
1138                                let res = lf.powf(rf);
1139                                if res.is_nan() || res.is_infinite() {
1140                                    return Ok(ResultData::Error("#NUM!".to_string()));
1141                                }
1142                                Ok(ResultData::Float(res))
1143                            }
1144                            _ => unreachable!(),
1145                        }
1146                    }
1147                }
1148            }
1149            Expr::FunctionCall { name, args } => {
1150                self.evaluate_function(name, args, context, row, col, deps, scope)
1151            }
1152        }
1153    }
1154
1155    fn excel_type_rank(val: &ResultData) -> u8 {
1156        match val {
1157            ResultData::None => 0,
1158            ResultData::Integer(_) | ResultData::Float(_) => 1,
1159            ResultData::String(_) => 2,
1160            ResultData::Boolean(_) => 3,
1161            _ => 4,
1162        }
1163    }
1164
1165    fn compare_excel_values(l: &ResultData, r: &ResultData) -> std::cmp::Ordering {
1166        // Coerce ResultData::None against the type of the opposing operand
1167        match (l, r) {
1168            (ResultData::None, ResultData::None) => return std::cmp::Ordering::Equal,
1169            (ResultData::None, ResultData::Integer(b)) => {
1170                return 0.0
1171                    .partial_cmp(&(*b as f64))
1172                    .unwrap_or(std::cmp::Ordering::Equal);
1173            }
1174            (ResultData::None, ResultData::Float(b)) => {
1175                return 0.0.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
1176            }
1177            (ResultData::Integer(a), ResultData::None) => {
1178                return (*a as f64)
1179                    .partial_cmp(&0.0)
1180                    .unwrap_or(std::cmp::Ordering::Equal);
1181            }
1182            (ResultData::Float(a), ResultData::None) => {
1183                return a.partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal);
1184            }
1185            (ResultData::None, ResultData::String(b)) => {
1186                return "".cmp(b.to_lowercase().as_str());
1187            }
1188            (ResultData::String(a), ResultData::None) => {
1189                return a.to_lowercase().as_str().cmp("");
1190            }
1191            (ResultData::None, ResultData::Boolean(b)) => {
1192                return false.cmp(b);
1193            }
1194            (ResultData::Boolean(a), ResultData::None) => {
1195                return a.cmp(&false);
1196            }
1197            _ => {}
1198        }
1199
1200        let rank_l = Self::excel_type_rank(l);
1201        let rank_r = Self::excel_type_rank(r);
1202        if rank_l != rank_r {
1203            return rank_l.cmp(&rank_r);
1204        }
1205        match (l, r) {
1206            (ResultData::Integer(a), ResultData::Integer(b)) => a.cmp(b),
1207            (ResultData::Float(a), ResultData::Float(b)) => {
1208                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
1209            }
1210            (ResultData::Integer(a), ResultData::Float(b)) => (*a as f64)
1211                .partial_cmp(b)
1212                .unwrap_or(std::cmp::Ordering::Equal),
1213            (ResultData::Float(a), ResultData::Integer(b)) => a
1214                .partial_cmp(&(*b as f64))
1215                .unwrap_or(std::cmp::Ordering::Equal),
1216            (ResultData::Boolean(a), ResultData::Boolean(b)) => a.cmp(b),
1217            (ResultData::String(a), ResultData::String(b)) => Self::compare_excel_strings(a, b),
1218            _ => std::cmp::Ordering::Equal,
1219        }
1220    }
1221
1222    /// `SORT`/`SORTBY`-specific comparator: Microsoft documents that both
1223    /// functions always place blank cells last, regardless of ascending
1224    /// vs. descending order -- unlike `compare_excel_values`'s general
1225    /// blank-coerces-to-0/""/false rule (correct for comparison operators,
1226    /// MATCH, etc.), which would otherwise rank a blank ahead of every
1227    /// negative number once descending order reverses the comparison.
1228    /// Found via the differential fuzzer: `SORT({-215.8,,-100,-240.97,-88},1,-1)`
1229    /// put the blank first (coerced to 0, the largest value once reversed)
1230    /// instead of last, so `INDEX(...,1)` returned 0 instead of -88.
1231    fn sort_compare_blanks_last(
1232        l: &ResultData,
1233        r: &ResultData,
1234        sort_order: f64,
1235    ) -> std::cmp::Ordering {
1236        match (matches!(l, ResultData::None), matches!(r, ResultData::None)) {
1237            (true, true) => std::cmp::Ordering::Equal,
1238            (true, false) => std::cmp::Ordering::Greater,
1239            (false, true) => std::cmp::Ordering::Less,
1240            (false, false) => {
1241                let ord = Self::compare_excel_values(l, r);
1242                if sort_order < 0.0 { ord.reverse() } else { ord }
1243            }
1244        }
1245    }
1246
1247    fn is_excel_number_str(s: &str) -> bool {
1248        let s = s.trim();
1249        if s.is_empty() {
1250            return false;
1251        }
1252        let bytes = s.as_bytes();
1253        let first = bytes[0];
1254        if first == b'e' || first == b'E' {
1255            return false;
1256        }
1257        if (first == b'+' || first == b'-') && bytes.len() > 1 {
1258            let second = bytes[1];
1259            if second == b'e' || second == b'E' {
1260                return false;
1261            }
1262        }
1263        true
1264    }
1265
1266    fn compare_excel_strings(a: &str, b: &str) -> std::cmp::Ordering {
1267        let a_low = a.to_lowercase();
1268        let b_low = b.to_lowercase();
1269        let char_weight = |ch: char| -> u32 {
1270            match ch {
1271                '-' => 1,
1272                '(' => 2,
1273                ')' => 3,
1274                _ => (ch as u32) + 10,
1275            }
1276        };
1277        for (ca, cb) in a_low.chars().zip(b_low.chars()) {
1278            if ca != cb {
1279                let wa = char_weight(ca);
1280                let wb = char_weight(cb);
1281                return wa.cmp(&wb);
1282            }
1283        }
1284        a_low.len().cmp(&b_low.len())
1285    }
1286
1287    /// Snaps a float to its 15-significant-digit rounding when the two are
1288    /// within floating-point noise of each other, so accumulated error does
1289    /// not leak into a result Excel would show as exact.
1290    ///
1291    /// Left alone if the rounding moves the value by more than that, and for
1292    /// zero and non-finite values.
1293    pub(crate) fn clean_float(val: f64) -> f64 {
1294        if val == 0.0 || !val.is_finite() {
1295            return val;
1296        }
1297        let abs_val = val.abs();
1298        let exp = abs_val.log10().floor() as i32;
1299        let factor = 10.0f64.powi(15 - 1 - exp);
1300        if factor.is_finite() && factor != 0.0 {
1301            let rounded = (val * factor).round() / factor;
1302            if (val - rounded).abs() <= 1e-14 * abs_val {
1303                return rounded;
1304            }
1305        }
1306        val
1307    }
1308
1309    /// Coerces a value to a number the way an Excel arithmetic operator does:
1310    /// a blank is 0, a boolean is 0 or 1, and text is converted if it reads as
1311    /// a number or a date (a date becoming its serial).
1312    ///
1313    /// `None` for text that is not numeric and for every other value,
1314    /// including errors -- callers turn that into `#VALUE!`.
1315    ///
1316    /// Not every function coerces this way; the stricter families reject text
1317    /// and booleans outright.
1318    pub(crate) fn to_f64(&self, val: &ResultData) -> Option<f64> {
1319        match val {
1320            ResultData::None => Some(0.0),
1321            ResultData::Float(f) => Some(*f),
1322            ResultData::Integer(i) => Some(*i as f64),
1323            ResultData::Boolean(b) => Some(if *b { 1.0 } else { 0.0 }),
1324            ResultData::String(s) => {
1325                let s_trim = s.trim();
1326                if Self::is_excel_number_str(s_trim) {
1327                    if let Ok(f) = s_trim.parse::<f64>() {
1328                        return Some(f);
1329                    }
1330                    if let Some((date, _)) = crate::core::date::parse_date(s_trim) {
1331                        return Some(crate::core::date::date_to_excel_serial(date));
1332                    }
1333                    None
1334                } else if let Some((date, _)) = crate::core::date::parse_date(s_trim) {
1335                    Some(crate::core::date::date_to_excel_serial(date))
1336                } else {
1337                    None
1338                }
1339            }
1340            _ => None,
1341        }
1342    }
1343
1344    fn to_f64_arg(&self, arg_opt: Option<&ResultData>, fn_name: &str) -> Result<f64, EngineError> {
1345        let val = arg_opt.ok_or_else(|| {
1346            EngineError::EvalError(EvalError::UnknownFunction(format!(
1347                "{} requires argument",
1348                fn_name
1349            )))
1350        })?;
1351        if let ResultData::Error(e) = val {
1352            return Err(EngineError::EvalError(EvalError::UnknownFunction(
1353                e.clone(),
1354            )));
1355        }
1356        self.to_f64(val).ok_or_else(|| {
1357            EngineError::EvalError(EvalError::UnknownFunction("#VALUE!".to_string()))
1358        })
1359    }
1360
1361    fn find_error_in_args(args: &[ResultData]) -> Option<ResultData> {
1362        for arg in args {
1363            match arg {
1364                ResultData::Error(_) => return Some(arg.clone()),
1365                ResultData::List(list) => {
1366                    if let Some(err) = Self::find_error_in_args(list) {
1367                        return Some(err);
1368                    }
1369                }
1370                _ => {}
1371            }
1372        }
1373        None
1374    }
1375
1376    fn check_arg_errors(&self, args: &[ResultData], is_direct: &[bool]) -> Option<ResultData> {
1377        for (i, arg) in args.iter().enumerate() {
1378            match arg {
1379                ResultData::Error(_) => return Some(arg.clone()),
1380                ResultData::List(list) => {
1381                    if let Some(err) = self.check_arg_errors(list, &[]) {
1382                        return Some(err);
1383                    }
1384                }
1385                ResultData::String(_)
1386                    if is_direct.get(i).copied().unwrap_or(false) && self.to_f64(arg).is_none() =>
1387                {
1388                    return Some(ResultData::Error("#VALUE!".to_string()));
1389                }
1390                _ => {}
1391            }
1392        }
1393        None
1394    }
1395
1396    fn sum_helper(&self, arg: &ResultData, is_direct: bool) -> f64 {
1397        match arg {
1398            ResultData::Float(f) => *f,
1399            ResultData::Integer(i) => *i as f64,
1400            ResultData::Boolean(b) => {
1401                if is_direct {
1402                    if *b { 1.0 } else { 0.0 }
1403                } else {
1404                    0.0
1405                }
1406            }
1407            ResultData::String(_) => {
1408                if is_direct {
1409                    self.to_f64(arg).unwrap_or(0.0)
1410                } else {
1411                    0.0
1412                }
1413            }
1414            ResultData::List(list) => {
1415                let mut sum = 0.0;
1416                for item in list {
1417                    sum += self.sum_helper(item, false);
1418                }
1419                sum
1420            }
1421            _ => 0.0,
1422        }
1423    }
1424
1425    /// Flattens a single argument (which may be a range/array `List`) into
1426    /// an ordered `Vec<f64>` for the financial functions that take a
1427    /// cashflow series (`NPV`, `IRR`, `MIRR`, `XNPV`, `XIRR`, `FVSCHEDULE`).
1428    /// Mirrors `sum_helper`'s convention: booleans/text only count when
1429    /// passed directly (not through a range).
1430    fn flatten_finance_numbers(&self, arg: &ResultData, is_direct: bool) -> Vec<f64> {
1431        match arg {
1432            ResultData::Float(f) => vec![*f],
1433            ResultData::Integer(i) => vec![*i as f64],
1434            ResultData::Boolean(b) => {
1435                if is_direct {
1436                    vec![if *b { 1.0 } else { 0.0 }]
1437                } else {
1438                    vec![]
1439                }
1440            }
1441            ResultData::String(_) => {
1442                if is_direct {
1443                    self.to_f64(arg).into_iter().collect()
1444                } else {
1445                    vec![]
1446                }
1447            }
1448            ResultData::List(list) => list
1449                .iter()
1450                .flat_map(|v| self.flatten_finance_numbers(v, false))
1451                .collect(),
1452            _ => vec![],
1453        }
1454    }
1455
1456    fn flatten_stat_numbers(&self, arg: &ResultData, is_direct: bool) -> Vec<f64> {
1457        match arg {
1458            ResultData::Float(f) => vec![*f],
1459            ResultData::Integer(i) => vec![*i as f64],
1460            ResultData::Boolean(b) => {
1461                if is_direct {
1462                    vec![if *b { 1.0 } else { 0.0 }]
1463                } else {
1464                    vec![]
1465                }
1466            }
1467            ResultData::String(_) => {
1468                if is_direct {
1469                    self.to_f64(arg).into_iter().collect()
1470                } else {
1471                    vec![]
1472                }
1473            }
1474            ResultData::List(list) => list
1475                .iter()
1476                .flat_map(|v| self.flatten_stat_numbers(v, false))
1477                .collect(),
1478            _ => vec![],
1479        }
1480    }
1481
1482    /// Flattens one argument positionally: `Some(n)` for a numeric cell,
1483    /// `None` for anything real Excel excludes from a paired statistical
1484    /// calculation (text, boolean, blank). Unlike flatten_stat_numbers,
1485    /// excluded cells still occupy a slot, so two ranges of the same
1486    /// shape always produce vectors of the same length and element `i` of
1487    /// one still lines up with element `i` of the other.
1488    fn flatten_positional(
1489        &self,
1490        arg: &ResultData,
1491        out: &mut Vec<Option<f64>>,
1492        first_err: &mut Option<String>,
1493    ) {
1494        match arg {
1495            ResultData::List(items) => {
1496                for item in items {
1497                    self.flatten_positional(item, out, first_err);
1498                }
1499            }
1500            ResultData::Float(f) => out.push(Some(*f)),
1501            ResultData::Integer(i) => out.push(Some(*i as f64)),
1502            ResultData::Error(e) => {
1503                if first_err.is_none() {
1504                    *first_err = Some(e.clone());
1505                }
1506                out.push(None);
1507            }
1508            _ => out.push(None),
1509        }
1510    }
1511
1512    fn positional_numbers(
1513        &self,
1514        arg: Option<&ResultData>,
1515        first_err: &mut Option<String>,
1516    ) -> Vec<Option<f64>> {
1517        let mut out = Vec::new();
1518        if let Some(a) = arg {
1519            self.flatten_positional(a, &mut out, first_err);
1520        }
1521        out
1522    }
1523
1524    /// Excel's paired statistical functions (CORREL/PEARSON/COVAR/
1525    /// COVARIANCE.P/COVARIANCE.S/SLOPE/INTERCEPT/RSQ/STEYX/FORECAST/
1526    /// TREND/LINEST/GROWTH/LOGEST/T.TEST/SUMX2PY2/SUMXMY2/SUMX2MY2/PROB)
1527    /// compare the two ranges' *raw* element counts first -- a mismatch
1528    /// is #N/A regardless of content -- and then drop every (x, y) pair
1529    /// where either side is non-numeric, keeping what survives aligned.
1530    ///
1531    /// Verified directly against real Excel: `COVAR(A1:A4, B1:B4)` with
1532    /// one text cell in B returns exactly the value of the 3-element
1533    /// ranges with that whole pair physically removed, and the same holds
1534    /// for SLOPE/INTERCEPT/RSQ/PEARSON/STEYX/FORECAST/T.TEST/SUMX*.
1535    /// Booleans and blanks are excluded the same way text is.
1536    ///
1537    /// This is deliberately *not* the same as flattening each side
1538    /// independently (what flatten_stat_numbers does): dropping a
1539    /// non-numeric from only one side shifts every later element against
1540    /// its partner, silently correlating the wrong values together.
1541    /// F.TEST/FTEST is the exception that genuinely does want independent
1542    /// per-array flattening -- it compares two samples' variances and
1543    /// doesn't require equal sizes at all (confirmed against real Excel:
1544    /// `FTEST(4-cell-with-text, ...)` equals `FTEST(full-4-cell, ...)`
1545    /// against the 3-cell survivor, i.e. each side shrinks on its own).
1546    fn pair_and_filter(
1547        xs_raw: Vec<Option<f64>>,
1548        ys_raw: Vec<Option<f64>>,
1549    ) -> Result<(Vec<f64>, Vec<f64>), String> {
1550        if xs_raw.len() != ys_raw.len() {
1551            return Err("#N/A".to_string());
1552        }
1553        let mut xs = Vec::with_capacity(xs_raw.len());
1554        let mut ys = Vec::with_capacity(ys_raw.len());
1555        for (x, y) in xs_raw.into_iter().zip(ys_raw) {
1556            if let (Some(x), Some(y)) = (x, y) {
1557                xs.push(x);
1558                ys.push(y);
1559            }
1560        }
1561        Ok((xs, ys))
1562    }
1563
1564    /// pair_and_filter over two argument slots.
1565    fn paired_args(
1566        &self,
1567        x_arg: Option<&ResultData>,
1568        y_arg: Option<&ResultData>,
1569    ) -> Result<(Vec<f64>, Vec<f64>), String> {
1570        // The size check has to come *before* propagating any error cell
1571        // sitting inside either range: real Excel reports #N/A for two
1572        // differently-sized ranges even when one of them contains a live
1573        // error (confirmed by probing `CORREL` over a 4-cell and a 3-cell
1574        // range whose second range held a #DIV/0!, which answers #N/A).
1575        // These functions are therefore excluded from the generic
1576        // "any error in an argument short-circuits the call" pre-pass, and
1577        // re-raise the error here only once the shapes agree.
1578        // A *scalar* operand carrying an error propagates before any
1579        // shape logic runs: Excel resolves a 1x1 reference to a plain
1580        // value first, and an error value in an ordinary operand position
1581        // short-circuits the call. So `SUMX2PY2(A1:A4, P1:P1)` with a
1582        // #DIV/0! in P1 is #DIV/0!, even though the two operands are
1583        // differently sized.
1584        //
1585        // An error inside a *multi-cell* range does not get that
1586        // treatment -- there the size check wins, and
1587        // `SUMX2PY2(A1:A4, N1:N3)` with an error inside N1:N3 is #N/A.
1588        // Both confirmed against real Excel, and consistently across
1589        // CORREL/SLOPE/STEYX/SUMX2PY2.
1590        for arg in [x_arg, y_arg].into_iter().flatten() {
1591            // A one-cell *range* evaluates to a one-element List rather
1592            // than a bare scalar, so both spellings have to be unwrapped
1593            // here -- matching only the bare form let
1594            // `STEYX(H6:H6, F2:H2)` report the shape mismatch (#N/A)
1595            // instead of the error sitting in H6.
1596            let scalar = match arg {
1597                ResultData::List(items) if items.len() == 1 => &items[0],
1598                other => other,
1599            };
1600            if let ResultData::Error(e) = scalar {
1601                return Err(e.clone());
1602            }
1603            // A one-cell operand that is *empty* isn't a one-element array,
1604            // it's a missing operand: Excel answers #VALUE! rather than the
1605            // #N/A a shape mismatch would give. Note this is specifically
1606            // about blankness -- a one-cell operand holding text or a
1607            // boolean still reports #N/A, so it can't be folded into the
1608            // general non-numeric handling (all three confirmed against
1609            // real Excel with CORREL against a 4-cell range).
1610            if Self::is_empty_scalar_operand(arg) {
1611                return Err("#VALUE!".to_string());
1612            }
1613        }
1614        let mut first_err = None;
1615        let xs_raw = self.positional_numbers(x_arg, &mut first_err);
1616        let ys_raw = self.positional_numbers(y_arg, &mut first_err);
1617        if xs_raw.len() != ys_raw.len() {
1618            return Err("#N/A".to_string());
1619        }
1620        if let Some(e) = first_err {
1621            return Err(e);
1622        }
1623        Self::pair_and_filter(xs_raw, ys_raw)
1624    }
1625
1626    /// Like flatten_stat_numbers, but errors instead of silently dropping
1627    /// a cell real Excel won't accept. Excel's array/matrix-argument
1628    /// functions don't ignore text the way SUM/AVERAGE-style aggregates
1629    /// do -- one bad cell makes the whole call #VALUE!.
1630    ///
1631    /// `blanks` selects between the three behaviours real Excel actually
1632    /// exhibits here, each established by probing it directly:
1633    ///  - `BlankPolicy::Zero` (GCD/LCM): a blank counts as 0 and the call
1634    ///    still succeeds. `GCD` over `{4, 6, <blank>, 8}` is 2 and `LCM`
1635    ///    over it is 0 (i.e. the blank really did participate as a zero),
1636    ///    while the same range with `TRUE` in place of the blank is
1637    ///    #VALUE!.
1638    ///  - `BlankPolicy::Skip` (SERIESSUM): a blank is dropped outright,
1639    ///    which *shifts* every later coefficient down a power.
1640    ///    `SERIESSUM(0.5, 0, 2, {4, 6, <blank>, 8})` is 6.0 -- exactly the
1641    ///    3-coefficient answer -- not the 5.625 a zero in that slot gives.
1642    ///  - `BlankPolicy::Reject` (LINEST/TREND/GROWTH/LOGEST/MMULT): text,
1643    ///    booleans *and* blanks are all #VALUE!. LINEST returns #VALUE!
1644    ///    for each of those three separately and only computes when every
1645    ///    cell is a real number.
1646    ///
1647    /// Note this deliberately does not go through `to_f64`, which is the
1648    /// lenient coercion used for scalar arguments -- that maps a blank to
1649    /// 0, a boolean to 1/0, and a numeric-looking string to its value,
1650    /// none of which these functions accept.
1651    fn flatten_strict_inner(
1652        &self,
1653        arg: &ResultData,
1654        blanks: BlankPolicy,
1655        out: &mut Vec<f64>,
1656    ) -> Result<(), String> {
1657        match arg {
1658            ResultData::List(items) => {
1659                for item in items {
1660                    self.flatten_strict_inner(item, blanks, out)?;
1661                }
1662                Ok(())
1663            }
1664            ResultData::Error(e) => Err(e.clone()),
1665            ResultData::Float(f) => {
1666                out.push(*f);
1667                Ok(())
1668            }
1669            ResultData::Integer(i) => {
1670                out.push(*i as f64);
1671                Ok(())
1672            }
1673            ResultData::None => match blanks {
1674                BlankPolicy::Zero => {
1675                    out.push(0.0);
1676                    Ok(())
1677                }
1678                BlankPolicy::Skip => Ok(()),
1679                BlankPolicy::Reject => Err("#VALUE!".to_string()),
1680            },
1681            // Numeric text is coerced, non-numeric text is not: real Excel
1682            // gives GCD("12", 8) = 4, LCM("4", 6) = 12 and
1683            // MULTINOMIAL("3", 2) = 10, while GCD("x", 8) is #VALUE!.
1684            // Booleans stay rejected -- GCD(TRUE, 8) is #VALUE! -- which
1685            // is why this can't just fall through to `to_f64`.
1686            ResultData::String(_) => match self.to_f64(arg) {
1687                Some(f) => {
1688                    out.push(f);
1689                    Ok(())
1690                }
1691                None => Err("#VALUE!".to_string()),
1692            },
1693            _ => Err("#VALUE!".to_string()),
1694        }
1695    }
1696
1697    fn flatten_strict_numbers(&self, arg: &ResultData) -> Result<Vec<f64>, String> {
1698        let mut out = Vec::new();
1699        self.flatten_strict_inner(arg, BlankPolicy::Zero, &mut out)?;
1700        Ok(out)
1701    }
1702
1703    /// flatten_strict_numbers with blanks dropped rather than zero-filled.
1704    fn flatten_skipping_blanks(&self, arg: Option<&ResultData>) -> Result<Vec<f64>, String> {
1705        let mut out = Vec::new();
1706        if let Some(a) = arg {
1707            self.flatten_strict_inner(a, BlankPolicy::Skip, &mut out)?;
1708        }
1709        Ok(out)
1710    }
1711
1712    /// flatten_strict_numbers with the stricter "a blank is also #VALUE!"
1713    /// rule the regression-array and matrix functions use.
1714    fn flatten_numbers_only(&self, arg: &ResultData) -> Result<Vec<f64>, String> {
1715        let mut out = Vec::new();
1716        self.flatten_strict_inner(arg, BlankPolicy::Reject, &mut out)?;
1717        Ok(out)
1718    }
1719
1720    /// The value of one cell of a SUMIF/AVERAGEIF/MAXIFS/MINIFS-style
1721    /// *aggregate* range. Only a real number counts: Excel silently skips
1722    /// text and booleans in the range being summed/averaged/compared
1723    /// (confirmed directly -- `SUMIF` over a range holding
1724    /// `{100, TRUE, 200, "txt", 300}` is 600, and MAXIFS over the same
1725    /// range is 300, not the boolean coerced to 1). Using the lenient
1726    /// `to_f64` here instead folded `TRUE` in as a 1, which both shifted
1727    /// sums/averages and could win a MAX/MIN outright.
1728    fn aggregate_range_number(val: &ResultData) -> Option<f64> {
1729        match val {
1730            ResultData::Float(f) => Some(*f),
1731            ResultData::Integer(i) => Some(*i as f64),
1732            _ => None,
1733        }
1734    }
1735
1736    fn flatten_numbers_only_arg(&self, arg: Option<&ResultData>) -> Result<Vec<f64>, String> {
1737        match arg {
1738            Some(a) => self.flatten_numbers_only(a),
1739            None => Ok(vec![]),
1740        }
1741    }
1742
1743    /// `flatten_stat_numbers` across an argument list, applying Excel's rule
1744    /// for text supplied *directly* as an argument: it is coerced if it
1745    /// looks numeric, and is `#VALUE!` if it does not. Text reached through
1746    /// a reference is skipped instead, which is what `flatten_stat_numbers`
1747    /// already does on its own.
1748    ///
1749    /// The split matters because silently skipping uncoercible direct text
1750    /// turns a wrong formula into a plausible number: `DEVSQ("abc",3,4,5)`
1751    /// answered 2 (the spread of the remaining three) where Excel answers
1752    /// `#VALUE!`. Verified against real Excel for SUM, AVERAGE, DEVSQ,
1753    /// STDEV, VAR, MEDIAN, MAX, MIN, PRODUCT, SUMSQ, GEOMEAN, AVEDEV, SKEW
1754    /// and KURT. COUNT is the deliberate exception -- it never errors, it
1755    /// just doesn't count what it can't read -- and does not call this.
1756    fn flatten_args_stat_numbers(
1757        &self,
1758        args: &[ResultData],
1759        is_direct: &[bool],
1760    ) -> Result<Vec<f64>, String> {
1761        let mut out = Vec::new();
1762        for (i, arg) in args.iter().enumerate() {
1763            let direct = is_direct.get(i).copied().unwrap_or(false);
1764            if direct && matches!(arg, ResultData::String(_)) && self.to_f64(arg).is_none() {
1765                return Err("#VALUE!".to_string());
1766            }
1767            out.extend(self.flatten_stat_numbers(arg, direct));
1768        }
1769        Ok(out)
1770    }
1771
1772    /// Flatten arguments for the `*A` statistical family (AVERAGEA, MAXA,
1773    /// MINA, STDEVA, STDEVPA, VARA, VARPA), which count text and booleans
1774    /// rather than skipping them.
1775    ///
1776    /// Text is where the family gets interesting, and the rule depends on
1777    /// *how* the text arrived. Inside a reference it counts as 0, which is
1778    /// the documented behaviour everyone knows. Passed directly as an
1779    /// argument it is coerced instead, and a value that will not coerce is
1780    /// an error rather than a zero. Against real Excel, with A1 holding the
1781    /// text "12":
1782    ///
1783    /// ```text
1784    /// AVERAGEA(A1, 3)     = 1.5        text in a reference counts as 0
1785    /// AVERAGEA("12", 3)   = 7.5        direct text is coerced
1786    /// AVERAGEA("abc", 3)  = #VALUE!    ... and must coerce
1787    /// ```
1788    fn flatten_stat_numbers_a(
1789        &self,
1790        arg: &ResultData,
1791        is_direct: bool,
1792    ) -> Result<Vec<f64>, String> {
1793        Ok(match arg {
1794            ResultData::Float(f) => vec![*f],
1795            ResultData::Integer(i) => vec![*i as f64],
1796            ResultData::Boolean(b) => vec![if *b { 1.0 } else { 0.0 }],
1797            ResultData::String(_) => {
1798                if is_direct {
1799                    match self.to_f64(arg) {
1800                        Some(f) => vec![f],
1801                        None => return Err("#VALUE!".to_string()),
1802                    }
1803                } else {
1804                    vec![0.0]
1805                }
1806            }
1807            ResultData::Error(e) => return Err(e.clone()),
1808            // Anything nested is a reference, never a direct argument.
1809            ResultData::List(list) => {
1810                let mut out = Vec::new();
1811                for v in list {
1812                    out.extend(self.flatten_stat_numbers_a(v, false)?);
1813                }
1814                out
1815            }
1816            ResultData::None => vec![],
1817            _ => vec![0.0],
1818        })
1819    }
1820
1821    /// `flatten_stat_numbers_a` over a whole argument list, using the
1822    /// caller's per-argument direct/reference classification.
1823    fn flatten_args_stat_numbers_a(
1824        &self,
1825        args: &[ResultData],
1826        is_direct: &[bool],
1827    ) -> Result<Vec<f64>, String> {
1828        let mut out = Vec::new();
1829        for (i, arg) in args.iter().enumerate() {
1830            out.extend(
1831                self.flatten_stat_numbers_a(arg, is_direct.get(i).copied().unwrap_or(false))?,
1832            );
1833        }
1834        Ok(out)
1835    }
1836
1837    fn extract_matrix(&self, arg: &ResultData) -> Vec<Vec<f64>> {
1838        match arg {
1839            ResultData::List(list) => {
1840                let mut rows = Vec::new();
1841                for item in list {
1842                    match item {
1843                        ResultData::List(sub_list) => {
1844                            let row: Vec<f64> =
1845                                sub_list.iter().flat_map(|v| self.to_f64(v)).collect();
1846                            if !row.is_empty() {
1847                                rows.push(row);
1848                            }
1849                        }
1850                        _ => {
1851                            if let Some(f) = self.to_f64(item) {
1852                                rows.push(vec![f]);
1853                            }
1854                        }
1855                    }
1856                }
1857                rows
1858            }
1859            _ => vec![],
1860        }
1861    }
1862
1863    /// Reshapes a range argument's flat evaluated list back into a 2D
1864    /// row-major matrix using the *reference's* own width.
1865    ///
1866    /// A plain rectangular range like `F1:G2` evaluates to a flat
1867    /// `List` of 4 scalars with no nesting, so extract_matrix (which can
1868    /// only treat a nested `List` as a row) turned it into a 4x1 column
1869    /// instead of a 2x2 square -- and every matrix function then reported
1870    /// #VALUE! on a perfectly valid square range. MMULT already
1871    /// reconstructed its operands' shapes from the argument expression
1872    /// this way; this shares that logic with MDETERM/MINVERSE.
1873    fn matrix_from_arg(
1874        &self,
1875        expr: &crate::core::parser::Expr,
1876        value: &ResultData,
1877    ) -> Vec<Vec<f64>> {
1878        // A list of lists already carries its own shape.
1879        if let ResultData::List(items) = value
1880            && items.iter().any(|i| matches!(i, ResultData::List(_)))
1881        {
1882            return self.extract_matrix(value);
1883        }
1884        // Only real numbers: the matrix functions reject text, booleans
1885        // and blanks alike (all confirmed #VALUE! against real Excel), so
1886        // a cell that isn't a number collapses the whole matrix rather
1887        // than being coerced by to_f64.
1888        fn plain(v: &ResultData) -> Option<f64> {
1889            match v {
1890                ResultData::Float(f) => Some(*f),
1891                ResultData::Integer(i) => Some(*i as f64),
1892                _ => None,
1893            }
1894        }
1895        let items: Vec<&ResultData> = match value {
1896            ResultData::List(items) => items.iter().collect(),
1897            other => vec![other],
1898        };
1899        if items.iter().any(|v| plain(v).is_none()) {
1900            return Vec::new();
1901        }
1902        let flat: Vec<f64> = items.iter().filter_map(|v| plain(v)).collect();
1903        let cols = match Self::range_bounds(expr) {
1904            Some((_, _, start_col, _, end_col)) => end_col.saturating_sub(start_col) + 1,
1905            None => flat.len().max(1),
1906        };
1907        if cols == 0 || !flat.len().is_multiple_of(cols) {
1908            return self.extract_matrix(value);
1909        }
1910        flat.chunks(cols).map(|c| c.to_vec()).collect()
1911    }
1912
1913    /// An optional numeric argument. An *absent* argument falls back to
1914    /// `default`, but one that is present and non-numeric is #VALUE! --
1915    /// the `.and_then(to_f64).unwrap_or(default)` shape used in places
1916    /// conflates the two, so e.g. `LOG(3.14, "E")` quietly computed
1917    /// base-10 instead of erroring.
1918    /// `#DIV/0!` when either operand of a paired sum contains no numeric
1919    /// value at all.
1920    ///
1921    /// This is *not* the same as "no pair survived exclusion", which is
1922    /// simply 0. Real Excel, with a column [53, TRUE] against a row
1923    /// [TRUE, -10]: every pair is dropped (each holds a boolean), yet the
1924    /// answer is 0 rather than an error, because each range does hold a
1925    /// number. Swap in a range that is entirely text or entirely booleans
1926    /// and it becomes #DIV/0!.
1927    ///
1928    /// Fitted against eleven real-Excel cases spanning text, booleans and
1929    /// mixtures, at one, two and three elements per range.
1930    fn paired_sum_has_no_numbers(&self, arg: Option<&ResultData>) -> bool {
1931        let mut ignored = None;
1932        let slots = self.positional_numbers(arg, &mut ignored);
1933        slots.iter().all(|v| v.is_none())
1934    }
1935
1936    /// True when an argument is a *single-cell* operand that is empty.
1937    ///
1938    /// Excel treats that as a missing operand and answers #VALUE!, rather
1939    /// than as a one-element array of nothing. The distinction is
1940    /// specifically about a single cell: `SUMPRODUCT(<one blank cell>)` is
1941    /// #VALUE! while `SUMPRODUCT(<two blank cells>)` is 0, and
1942    /// `SUMPRODUCT(-50, <blank>)` is #VALUE! too. Same for MULTINOMIAL and
1943    /// the paired statistical functions.
1944    ///
1945    /// A one-cell range evaluates to a one-element `List` rather than a
1946    /// bare scalar, so both spellings have to be unwrapped. Note this is
1947    /// about blankness only -- a one-cell operand holding text or a
1948    /// boolean behaves differently again.
1949    fn is_empty_scalar_operand(arg: &ResultData) -> bool {
1950        let scalar = match arg {
1951            ResultData::List(items) if items.len() == 1 => &items[0],
1952            other => other,
1953        };
1954        matches!(scalar, ResultData::None)
1955    }
1956
1957    /// True when the first argument is a boolean and the function is one
1958    /// of the few that refuse them.
1959    ///
1960    /// Excel's numeric coercion is not uniform here. SQRT, FACT, SIGN,
1961    /// INT, EXP, ROMAN and most of their neighbours take TRUE as 1
1962    /// without complaint, but ERF, ERFC, FACTDOUBLE and SQRTPI all answer
1963    /// #VALUE! -- verified one function at a time against real Excel,
1964    /// because the split does not follow from anything about the
1965    /// functions themselves.
1966    fn first_arg_is_boolean(args: &[ResultData]) -> bool {
1967        matches!(args.first(), Some(ResultData::Boolean(_)))
1968    }
1969
1970    fn opt_f64_arg(&self, args: &[ResultData], i: usize, default: f64) -> Result<f64, EngineError> {
1971        match args.get(i) {
1972            None => Ok(default),
1973            // A supplied-but-blank argument is 0, not the default. Excel
1974            // draws that line sharply: LOG(1, <blank>) is #NUM! because the
1975            // base is 0, while LOG(1) uses base 10 and returns 0. Same for
1976            // LEFT("abcd", <blank>) = "" and MROUND(10, <blank>) = 0.
1977            Some(ResultData::None) => Ok(0.0),
1978            Some(v) => self.to_f64(v).ok_or_else(|| {
1979                EngineError::EvalError(EvalError::UnknownFunction("#VALUE!".to_string()))
1980            }),
1981        }
1982    }
1983
1984    fn opt_f64(&self, args: &[ResultData], i: usize, default: f64) -> f64 {
1985        args.get(i).and_then(|v| self.to_f64(v)).unwrap_or(default)
1986    }
1987
1988    fn average_helper(&self, arg: &ResultData, is_direct: bool) -> (f64, usize) {
1989        match arg {
1990            ResultData::Float(f) => (*f, 1),
1991            ResultData::Integer(i) => (*i as f64, 1),
1992            ResultData::Boolean(b) => {
1993                if is_direct {
1994                    (if *b { 1.0 } else { 0.0 }, 1)
1995                } else {
1996                    (0.0, 0)
1997                }
1998            }
1999            ResultData::String(_) => {
2000                if is_direct {
2001                    if let Some(f) = self.to_f64(arg) {
2002                        (f, 1)
2003                    } else {
2004                        (0.0, 0)
2005                    }
2006                } else {
2007                    (0.0, 0)
2008                }
2009            }
2010            ResultData::List(list) => {
2011                let mut sum = 0.0;
2012                let mut count = 0;
2013                for item in list {
2014                    let (s, c) = self.average_helper(item, false);
2015                    sum += s;
2016                    count += c;
2017                }
2018                (sum, count)
2019            }
2020            _ => (0.0, 0),
2021        }
2022    }
2023
2024    fn count_helper(&self, arg: &ResultData) -> usize {
2025        match arg {
2026            ResultData::Float(_) | ResultData::Integer(_) => 1,
2027            ResultData::List(list) => {
2028                let mut count = 0;
2029                for item in list {
2030                    count += self.count_helper(item);
2031                }
2032                count
2033            }
2034            _ => 0,
2035        }
2036    }
2037
2038    fn min_helper(&self, arg: &ResultData, is_direct: bool) -> f64 {
2039        match arg {
2040            ResultData::Float(f) => *f,
2041            ResultData::Integer(i) => *i as f64,
2042            ResultData::Boolean(b) => {
2043                if is_direct {
2044                    if *b { 1.0 } else { 0.0 }
2045                } else {
2046                    f64::INFINITY
2047                }
2048            }
2049            ResultData::String(_) => {
2050                if is_direct {
2051                    self.to_f64(arg).unwrap_or(f64::INFINITY)
2052                } else {
2053                    f64::INFINITY
2054                }
2055            }
2056            ResultData::List(list) => {
2057                let mut min_val = f64::INFINITY;
2058                for item in list {
2059                    min_val = min_val.min(self.min_helper(item, false));
2060                }
2061                min_val
2062            }
2063            _ => f64::INFINITY,
2064        }
2065    }
2066
2067    fn max_helper(&self, arg: &ResultData, is_direct: bool) -> f64 {
2068        match arg {
2069            ResultData::Float(f) => *f,
2070            ResultData::Integer(i) => *i as f64,
2071            ResultData::Boolean(b) => {
2072                if is_direct {
2073                    if *b { 1.0 } else { 0.0 }
2074                } else {
2075                    f64::NEG_INFINITY
2076                }
2077            }
2078            ResultData::String(_) => {
2079                if is_direct {
2080                    self.to_f64(arg).unwrap_or(f64::NEG_INFINITY)
2081                } else {
2082                    f64::NEG_INFINITY
2083                }
2084            }
2085            ResultData::List(list) => {
2086                let mut max_val = f64::NEG_INFINITY;
2087                for item in list {
2088                    max_val = max_val.max(self.max_helper(item, false));
2089                }
2090                max_val
2091            }
2092            _ => f64::NEG_INFINITY,
2093        }
2094    }
2095
2096    fn concat_helper(&self, arg: &ResultData, out: &mut String) {
2097        match arg {
2098            ResultData::List(list) => {
2099                for item in list {
2100                    self.concat_helper(item, out);
2101                }
2102            }
2103            other => {
2104                out.push_str(&other.to_string());
2105            }
2106        }
2107    }
2108
2109    fn counta_helper(&self, arg: &ResultData) -> usize {
2110        match arg {
2111            ResultData::None => 0,
2112            // COUNTA counts every non-blank value, and the empty string is a
2113            // value -- Excel counts both a text cell holding "" and a formula
2114            // that returned "".
2115            ResultData::List(list) => {
2116                let mut count = 0;
2117                for item in list {
2118                    count += self.counta_helper(item);
2119                }
2120                count
2121            }
2122            _ => 1,
2123        }
2124    }
2125
2126    fn product_helper(&self, arg: &ResultData, is_direct: bool) -> (f64, bool) {
2127        match arg {
2128            ResultData::Float(f) => (*f, true),
2129            ResultData::Integer(i) => (*i as f64, true),
2130            ResultData::Boolean(b) => {
2131                if is_direct {
2132                    (if *b { 1.0 } else { 0.0 }, true)
2133                } else {
2134                    (1.0, false)
2135                }
2136            }
2137            ResultData::String(_) => {
2138                if is_direct {
2139                    if let Some(f) = self.to_f64(arg) {
2140                        (f, true)
2141                    } else {
2142                        (1.0, false)
2143                    }
2144                } else {
2145                    (1.0, false)
2146                }
2147            }
2148            ResultData::List(list) => {
2149                let mut prod = 1.0;
2150                let mut has_nums = false;
2151                for item in list {
2152                    let (p, h) = self.product_helper(item, false);
2153                    if h {
2154                        // Raw here; the 15-significant-digit snap belongs
2155                        // on the final product only. See the PRODUCT arm.
2156                        prod *= p;
2157                        has_nums = true;
2158                    }
2159                }
2160                (prod, has_nums)
2161            }
2162            _ => (1.0, false),
2163        }
2164    }
2165
2166    fn to_bool_opt(&self, val: &ResultData) -> Option<bool> {
2167        match val {
2168            ResultData::Boolean(b) => Some(*b),
2169            ResultData::Integer(i) => Some(*i != 0),
2170            ResultData::Float(f) => Some(*f != 0.0),
2171            ResultData::String(s) => {
2172                let s_trim = s.trim();
2173                if s_trim.eq_ignore_ascii_case("true") {
2174                    Some(true)
2175                } else if s_trim.eq_ignore_ascii_case("false") {
2176                    Some(false)
2177                } else if let Ok(f) = s_trim.parse::<f64>() {
2178                    Some(f != 0.0)
2179                } else {
2180                    None
2181                }
2182            }
2183            ResultData::None => Some(false),
2184            _ => None,
2185        }
2186    }
2187
2188    fn to_bool(&self, val: &ResultData) -> bool {
2189        self.to_bool_opt(val).unwrap_or(false)
2190    }
2191
2192    /// Strict "is this a genuine number" check for range-value aggregation
2193    /// (DCOUNT/DSUM/DAVERAGE/... and friends), as opposed to `to_f64`'s
2194    /// scalar-arithmetic coercion (which maps blank -> 0 and booleans ->
2195    /// 1/0). Confirmed against real Excel via the differential fuzzer that
2196    /// blank and boolean database cells must be excluded here the same
2197    /// way SUM/COUNT/AVERAGE ignore them within a range argument -- using
2198    /// `to_f64` instead let a blank row zero out DPRODUCT entirely and
2199    /// skewed DCOUNT/DSUM/DAVERAGE by counting/summing blanks and
2200    /// TRUE/FALSE as 0/1.
2201    fn range_numeric(val: &ResultData) -> Option<f64> {
2202        match val {
2203            ResultData::Integer(i) => Some(*i as f64),
2204            ResultData::Float(f) => Some(*f),
2205            _ => None,
2206        }
2207    }
2208
2209    /// Exact-match ("match_type 0" / "range_lookup FALSE") comparison for
2210    /// MATCH/VLOOKUP/HLOOKUP/XLOOKUP.
2211    ///
2212    /// A *blank* lookup value is coerced to 0 (Excel's usual empty-cell
2213    /// coercion) and a blank cell in the searched range never matches
2214    /// anything. Comparing the two blanks as equal strings instead --
2215    /// which is what a plain `to_string()` comparison does, since both
2216    /// render as "" -- made `MATCH(A1, A1:A4, 0)` over a blank A1 report
2217    /// a hit at position 1 where real Excel reports #N/A.
2218    fn exact_lookup_matches(lookup: &ResultData, candidate: &ResultData) -> bool {
2219        if matches!(candidate, ResultData::None) {
2220            return false;
2221        }
2222        let lookup_key = match lookup {
2223            ResultData::None => "0".to_string(),
2224            other => other.to_string(),
2225        };
2226        candidate.to_string() == lookup_key
2227    }
2228
2229    fn match_criteria(&self, val: &ResultData, criteria: &ResultData) -> bool {
2230        let crit_str = criteria.to_string();
2231        if let Some(rest) = crit_str.strip_prefix(">=") {
2232            // A numeric comparison can only ever be satisfied by a genuine
2233            // number -- confirmed against real Excel via the differential
2234            // fuzzer (fuzzing the new database D* functions): blank, text,
2235            // and boolean cells must all fail ">"/"<" criteria outright,
2236            // not fall back to comparing as if they were 0.
2237            let val_f = match Self::range_numeric(val) {
2238                Some(f) => f,
2239                None => return false,
2240            };
2241            let crit_f = rest.trim().parse::<f64>().unwrap_or(0.0);
2242            val_f >= crit_f
2243        } else if let Some(rest) = crit_str.strip_prefix('>') {
2244            let val_f = match Self::range_numeric(val) {
2245                Some(f) => f,
2246                None => return false,
2247            };
2248            let crit_f = rest.trim().parse::<f64>().unwrap_or(0.0);
2249            val_f > crit_f
2250        } else if let Some(rest) = crit_str.strip_prefix("<>") {
2251            let remainder = rest.trim().to_string();
2252            val.to_string() != remainder
2253        } else if let Some(rest) = crit_str.strip_prefix("<=") {
2254            let val_f = match Self::range_numeric(val) {
2255                Some(f) => f,
2256                None => return false,
2257            };
2258            let crit_f = rest.trim().parse::<f64>().unwrap_or(0.0);
2259            val_f <= crit_f
2260        } else if let Some(rest) = crit_str.strip_prefix('<') {
2261            let val_f = match Self::range_numeric(val) {
2262                Some(f) => f,
2263                None => return false,
2264            };
2265            let crit_f = rest.trim().parse::<f64>().unwrap_or(0.0);
2266            val_f < crit_f
2267        } else if let Some(rest) = crit_str.strip_prefix('=') {
2268            let remainder = rest.trim().to_string();
2269            val.to_string() == remainder
2270        } else {
2271            val.to_string() == crit_str
2272        }
2273    }
2274
2275    /// Resolves an argument `Expr` to its raw `(sheet, start_row, start_col,
2276    /// end_row, end_col)` range bounds, for functions (like the database
2277    /// `D*` family below) that need genuine 2D shape and can't work off the
2278    /// pre-flattened `ResultData::List` every other argument already went
2279    /// through in `evaluated_args`.
2280    fn range_bounds(
2281        expr: &crate::core::parser::Expr,
2282    ) -> Option<(Option<String>, usize, usize, usize, usize)> {
2283        use crate::core::parser::Expr;
2284        match expr {
2285            Expr::RangeRef {
2286                sheet,
2287                start_row,
2288                start_col,
2289                end_row,
2290                end_col,
2291                ..
2292            } => Some((sheet.clone(), *start_row, *start_col, *end_row, *end_col)),
2293            Expr::CellRef {
2294                sheet, row, col, ..
2295            } => Some((sheet.clone(), *row, *col, *row, *col)),
2296            _ => None,
2297        }
2298    }
2299
2300    /// Reads a range's cells into a row-major grid, resolving a whole-column
2301    /// range's `end_row` sentinel and cross-sheet references via `context`.
2302    /// Materializing into an owned `Vec<Vec<ResultData>>` (rather than
2303    /// keeping a live `&Sheet` around) sidesteps the local-vs-remote
2304    /// lifetime split for the rest of the database-function logic, and
2305    /// database/criteria ranges are small enough that this is cheap.
2306    fn materialize_range(
2307        &self,
2308        sheet_opt: &Option<String>,
2309        start_row: usize,
2310        start_col: usize,
2311        end_row: usize,
2312        end_col: usize,
2313        context: Option<&Context>,
2314    ) -> Option<Vec<Vec<ResultData>>> {
2315        let is_self = match sheet_opt {
2316            Some(name) => name == &self.name,
2317            None => true,
2318        };
2319        let source: &Sheet = if is_self {
2320            self
2321        } else {
2322            context?.sheets.get(sheet_opt.as_ref()?)?
2323        };
2324        let actual_end_row = if end_row == usize::MAX {
2325            source.row_count().saturating_sub(1)
2326        } else {
2327            end_row
2328        };
2329        if actual_end_row < start_row || end_col < start_col {
2330            return Some(Vec::new());
2331        }
2332        let mut grid = Vec::with_capacity(actual_end_row - start_row + 1);
2333        for r in start_row..=actual_end_row {
2334            let mut row = Vec::with_capacity(end_col - start_col + 1);
2335            for c in start_col..=end_col {
2336                row.push(source.get_result_data(&CellRef::new(r, c)));
2337            }
2338            grid.push(row);
2339        }
2340        Some(grid)
2341    }
2342
2343    /// Shared implementation for the 12 database `D*` functions
2344    /// (DAVERAGE/DCOUNT/DCOUNTA/DGET/DMAX/DMIN/DPRODUCT/DSTDEV/DSTDEVP/
2345    /// DSUM/DVAR/DVARP): each reduces to "match database rows against the
2346    /// criteria table, then aggregate one field column of the matches" --
2347    /// they differ only in which aggregation runs at the end.
2348    ///
2349    /// `database`/`criteria` are read from the raw `args` AST nodes (not
2350    /// `evaluated_args`) specifically to recover real row/column bounds;
2351    /// `field` (name or 1-based index) still comes from `evaluated_args`
2352    /// since it's a scalar. Criteria semantics match Excel's: multiple
2353    /// criteria *rows* are OR'd together, multiple non-blank cells within
2354    /// one criteria row are AND'd, and a blank criteria cell imposes no
2355    /// constraint on that field.
2356    fn evaluate_database_function(
2357        &self,
2358        func_name: &str,
2359        args: &[crate::core::parser::Expr],
2360        evaluated_args: &[ResultData],
2361        context: Option<&Context>,
2362    ) -> Result<ResultData, EngineError> {
2363        if args.len() < 3 || evaluated_args.len() < 3 {
2364            return Ok(ResultData::Error("#VALUE!".to_string()));
2365        }
2366        let (db_sheet, db_sr, db_sc, db_er, db_ec) = match Self::range_bounds(&args[0]) {
2367            Some(v) => v,
2368            None => return Ok(ResultData::Error("#VALUE!".to_string())),
2369        };
2370        let (crit_sheet, crit_sr, crit_sc, crit_er, crit_ec) = match Self::range_bounds(&args[2]) {
2371            Some(v) => v,
2372            None => return Ok(ResultData::Error("#VALUE!".to_string())),
2373        };
2374        let db = match self.materialize_range(&db_sheet, db_sr, db_sc, db_er, db_ec, context) {
2375            Some(g) => g,
2376            None => return Ok(ResultData::Error("#REF!".to_string())),
2377        };
2378        let crit = match self.materialize_range(
2379            &crit_sheet,
2380            crit_sr,
2381            crit_sc,
2382            crit_er,
2383            crit_ec,
2384            context,
2385        ) {
2386            Some(g) => g,
2387            None => return Ok(ResultData::Error("#REF!".to_string())),
2388        };
2389        if db.len() < 2 || crit.len() < 2 {
2390            return Ok(ResultData::Error("#VALUE!".to_string()));
2391        }
2392
2393        let db_headers: Vec<String> = db[0].iter().map(|v| v.to_string()).collect();
2394        let field_idx: usize = match &evaluated_args[1] {
2395            ResultData::String(s) => {
2396                match db_headers.iter().position(|h| h.eq_ignore_ascii_case(s)) {
2397                    Some(idx) => idx,
2398                    None => return Ok(ResultData::Error("#VALUE!".to_string())),
2399                }
2400            }
2401            other => match self.to_f64(other) {
2402                Some(n) if n >= 1.0 && (n as usize) <= db_headers.len() => n as usize - 1,
2403                _ => return Ok(ResultData::Error("#VALUE!".to_string())),
2404            },
2405        };
2406
2407        let crit_headers: Vec<String> = crit[0].iter().map(|v| v.to_string()).collect();
2408        let crit_to_db: Vec<Option<usize>> = crit_headers
2409            .iter()
2410            .map(|h| db_headers.iter().position(|dh| dh.eq_ignore_ascii_case(h)))
2411            .collect();
2412
2413        let mut matched: Vec<ResultData> = Vec::new();
2414        for row in db.iter().skip(1) {
2415            let row_matches_any_criteria_row = crit.iter().skip(1).any(|crit_row| {
2416                crit_row.iter().enumerate().all(|(ci, cell)| {
2417                    if matches!(cell, ResultData::None) {
2418                        return true;
2419                    }
2420                    match crit_to_db.get(ci).copied().flatten() {
2421                        Some(db_col) => self.match_criteria(&row[db_col], cell),
2422                        None => false,
2423                    }
2424                })
2425            });
2426            if row_matches_any_criteria_row {
2427                matched.push(row[field_idx].clone());
2428            }
2429        }
2430
2431        match func_name {
2432            "DGET" => match matched.len() {
2433                0 => Ok(ResultData::Error("#VALUE!".to_string())),
2434                1 => Ok(matched.into_iter().next().unwrap()),
2435                _ => Ok(ResultData::Error("#NUM!".to_string())),
2436            },
2437            "DCOUNT" => Ok(ResultData::Float(
2438                matched
2439                    .iter()
2440                    .filter(|v| Self::range_numeric(v).is_some())
2441                    .count() as f64,
2442            )),
2443            "DCOUNTA" => Ok(ResultData::Float(
2444                matched.iter().map(|v| self.counta_helper(v)).sum::<usize>() as f64,
2445            )),
2446            _ => {
2447                let nums: Vec<f64> = matched.iter().filter_map(Self::range_numeric).collect();
2448                match func_name {
2449                    "DSUM" => Ok(ResultData::Float(nums.iter().sum())),
2450                    "DPRODUCT" => Ok(ResultData::Float(if nums.is_empty() {
2451                        0.0
2452                    } else {
2453                        nums.iter().product()
2454                    })),
2455                    "DMAX" => {
2456                        let m = nums.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
2457                        Ok(ResultData::Float(if m.is_finite() { m } else { 0.0 }))
2458                    }
2459                    "DMIN" => {
2460                        let m = nums.iter().cloned().fold(f64::INFINITY, f64::min);
2461                        Ok(ResultData::Float(if m.is_finite() { m } else { 0.0 }))
2462                    }
2463                    "DAVERAGE" => {
2464                        if nums.is_empty() {
2465                            Ok(ResultData::Error("#DIV/0!".to_string()))
2466                        } else {
2467                            Ok(ResultData::Float(
2468                                nums.iter().sum::<f64>() / nums.len() as f64,
2469                            ))
2470                        }
2471                    }
2472                    "DSTDEV" => match crate::core::stats::stdev_s(&nums) {
2473                        Ok(v) => Ok(ResultData::Float(v)),
2474                        Err(e) => Ok(ResultData::Error(e)),
2475                    },
2476                    "DSTDEVP" => match crate::core::stats::stdev_p(&nums) {
2477                        Ok(v) => Ok(ResultData::Float(v)),
2478                        Err(e) => Ok(ResultData::Error(e)),
2479                    },
2480                    "DVAR" => match crate::core::stats::var_s(&nums) {
2481                        Ok(v) => Ok(ResultData::Float(v)),
2482                        Err(e) => Ok(ResultData::Error(e)),
2483                    },
2484                    "DVARP" => match crate::core::stats::var_p(&nums) {
2485                        Ok(v) => Ok(ResultData::Float(v)),
2486                        Err(e) => Ok(ResultData::Error(e)),
2487                    },
2488                    _ => unreachable!(),
2489                }
2490            }
2491        }
2492    }
2493
2494    fn proper(&self, s: &str) -> String {
2495        // Per Microsoft's own definition, PROPER capitalizes a letter
2496        // preceded by "any character that is not a letter" -- that
2497        // includes digits, not just punctuation/spacing, which is why
2498        // PROPER("123abc") is "123Abc": the digits aren't letters, so the
2499        // 'a' right after them still counts as the start of a new word.
2500        let mut c_chars = Vec::new();
2501        let mut capitalize_next = true;
2502        for c in s.chars() {
2503            if c.is_alphabetic() {
2504                if capitalize_next {
2505                    c_chars.extend(c.to_uppercase());
2506                } else {
2507                    c_chars.extend(c.to_lowercase());
2508                }
2509                capitalize_next = false;
2510            } else {
2511                c_chars.push(c);
2512                capitalize_next = true;
2513            }
2514        }
2515        c_chars.into_iter().collect()
2516    }
2517
2518    fn get_ymd_hms(&self) -> ((i32, u32, u32), (u32, u32, u32)) {
2519        let now = web_time::SystemTime::now()
2520            .duration_since(web_time::SystemTime::UNIX_EPOCH)
2521            .unwrap_or_default()
2522            .as_secs();
2523        let secs_in_day = 86400;
2524        let days_since_epoch = (now / secs_in_day) as i32;
2525        let seconds_of_day = (now % secs_in_day) as u32;
2526
2527        let hour = seconds_of_day / 3600;
2528        let minute = (seconds_of_day % 3600) / 60;
2529        let second = seconds_of_day % 60;
2530
2531        let era = (if days_since_epoch >= -719468 {
2532            days_since_epoch + 719468
2533        } else {
2534            days_since_epoch + 719468 - 146096
2535        }) / 146097;
2536        let doe = (days_since_epoch + 719468 - era * 146097) as u32;
2537        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2538        let y = (yoe as i32) + era * 400;
2539        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2540        let mp = (5 * doy + 2) / 153;
2541        let d = doy - (153 * mp + 2) / 5 + 1;
2542        let m = if mp < 10 { mp + 3 } else { mp - 9 };
2543        let year = if m <= 2 { y + 1 } else { y };
2544
2545        ((year, m, d), (hour, minute, second))
2546    }
2547
2548    /// Evaluates Excel's LET(name1, value1, [name2, value2, ...],
2549    /// calculation). Binds each name/value pair in order -- value2 (and
2550    /// later pairs, and the final calculation) can reference name1, per
2551    /// Excel's LET semantics -- by recursing one pair at a time so each
2552    /// level's scope chain only needs to borrow the *previous* level's
2553    /// binding rather than mutate a shared map (see `LetScope`).
2554    fn evaluate_let(
2555        &self,
2556        args: &[crate::core::parser::Expr],
2557        context: Option<&Context>,
2558        row: Option<usize>,
2559        col: Option<usize>,
2560        deps: &mut Vec<Dependency>,
2561        scope: &LetScope<'_>,
2562    ) -> Result<ResultData, EngineError> {
2563        use crate::core::parser::Expr;
2564
2565        if args.is_empty() || args.len().is_multiple_of(2) {
2566            // Needs one or more name/value pairs followed by a calculation,
2567            // i.e. an odd number of arguments overall.
2568            return Ok(ResultData::Error("#VALUE!".to_string()));
2569        }
2570        if args.len() == 1 {
2571            return self.evaluate_ast(&args[0], context, row, col, deps, scope);
2572        }
2573
2574        let name = match &args[0] {
2575            Expr::Identifier(n) => n.as_str(),
2576            _ => return Ok(ResultData::Error("#VALUE!".to_string())),
2577        };
2578        // Excel rejects reusing a name across a single LET's own pairs,
2579        // rather than letting a later pair silently shadow an earlier one.
2580        let remaining_pairs = args.len() / 2 - 1;
2581        let is_duplicate = args[2..]
2582            .iter()
2583            .step_by(2)
2584            .take(remaining_pairs)
2585            .any(|a| matches!(a, Expr::Identifier(n2) if n2.eq_ignore_ascii_case(name)));
2586        if is_duplicate {
2587            return Ok(ResultData::Error("#VALUE!".to_string()));
2588        }
2589
2590        let value = self.evaluate_ast(&args[1], context, row, col, deps, scope)?;
2591        let inner_scope = LetScope::Bound {
2592            name,
2593            value: &value,
2594            parent: scope,
2595        };
2596        self.evaluate_let(&args[2..], context, row, col, deps, &inner_scope)
2597    }
2598
2599    /// Recognizes `expr` as a `LAMBDA(param1, [param2, ...], body)` call
2600    /// and, if so, returns its declared parameter names alongside the
2601    /// (still-unevaluated) body expression. Used by every function below
2602    /// that takes a lambda argument: the lambda is never evaluated as an
2603    /// ordinary function call (there's no value a bare LAMBDA could
2604    /// produce on its own -- see the `#CALC!` case in `evaluate_function`)
2605    /// -- callers instead inspect its raw AST here and invoke the body
2606    /// themselves, once per element, via `invoke_lambda`.
2607    fn extract_lambda(
2608        expr: &crate::core::parser::Expr,
2609    ) -> Option<(Vec<&str>, &crate::core::parser::Expr)> {
2610        use crate::core::parser::Expr;
2611        let Expr::FunctionCall { name, args } = expr else {
2612            return None;
2613        };
2614        if !name.eq_ignore_ascii_case("LAMBDA") || args.is_empty() {
2615            return None;
2616        }
2617        let (body, params) = args.split_last().unwrap();
2618        let param_names: Vec<&str> = params
2619            .iter()
2620            .filter_map(|p| match p {
2621                Expr::Identifier(n) => Some(n.as_str()),
2622                _ => None,
2623            })
2624            .collect();
2625        if param_names.len() != params.len() {
2626            return None;
2627        }
2628        Some((param_names, body))
2629    }
2630
2631    /// Evaluates a lambda's body with each of `params` bound (via
2632    /// `LetScope`) to the corresponding entry of `values`, which must be
2633    /// the same length. `values` is borrowed rather than consumed so
2634    /// callers can reuse per-element storage across many invocations
2635    /// (e.g. MAP calling this once per array element).
2636    #[allow(clippy::too_many_arguments)]
2637    fn invoke_lambda<'v>(
2638        &self,
2639        params: &[&str],
2640        values: &'v [ResultData],
2641        body: &crate::core::parser::Expr,
2642        context: Option<&Context>,
2643        row: Option<usize>,
2644        col: Option<usize>,
2645        deps: &mut Vec<Dependency>,
2646        scope: &LetScope<'v>,
2647    ) -> Result<ResultData, EngineError> {
2648        match (params.split_first(), values.split_first()) {
2649            (Some((&pname, prest)), Some((vfirst, vrest))) => {
2650                let inner_scope = LetScope::Bound {
2651                    name: pname,
2652                    value: vfirst,
2653                    parent: scope,
2654                };
2655                self.invoke_lambda(prest, vrest, body, context, row, col, deps, &inner_scope)
2656            }
2657            _ => self.evaluate_ast(body, context, row, col, deps, scope),
2658        }
2659    }
2660
2661    /// Flattens `expr` (evaluated) into a `Vec<ResultData>`, treating a
2662    /// scalar as a single-element array -- shared by MAP/REDUCE/SCAN,
2663    /// which all iterate an "array" argument that might just be one cell.
2664    fn eval_as_array(
2665        &self,
2666        expr: &crate::core::parser::Expr,
2667        context: Option<&Context>,
2668        row: Option<usize>,
2669        col: Option<usize>,
2670        deps: &mut Vec<Dependency>,
2671        scope: &LetScope<'_>,
2672    ) -> Result<Vec<ResultData>, EngineError> {
2673        Ok(
2674            match self.evaluate_ast(expr, context, row, col, deps, scope)? {
2675                ResultData::List(items) => Self::flatten_row_major(items).0,
2676                other => vec![other],
2677            },
2678        )
2679    }
2680
2681    /// `SEQUENCE`/`MUNIT` (unlike every array-*reshaping* function added
2682    /// this session) return their 2D result as a genuinely nested
2683    /// `List(List(row_values), ...)`, one inner list per row, rather than
2684    /// a flat row-major list -- that's the only place in this engine a
2685    /// `ResultData::List` still carries real shape. Detect that shape
2686    /// here and flatten it so downstream consumers (`array_shape`,
2687    /// `INDEX`, reshape functions) don't need to special-case it; a list
2688    /// that isn't uniformly nested (the flat convention) passes through
2689    /// unchanged, with `None` signaling "no shape recovered here".
2690    fn flatten_row_major(items: Vec<ResultData>) -> (Vec<ResultData>, Option<usize>) {
2691        if !items.is_empty() && items.iter().all(|v| matches!(v, ResultData::List(_))) {
2692            let cols = match &items[0] {
2693                ResultData::List(inner) => inner.len().max(1),
2694                _ => 1,
2695            };
2696            let flat = items
2697                .into_iter()
2698                .flat_map(|v| match v {
2699                    ResultData::List(inner) => inner,
2700                    other => vec![other],
2701                })
2702                .collect();
2703            (flat, Some(cols))
2704        } else {
2705            (items, None)
2706        }
2707    }
2708
2709    /// Infers `(flat_values, num_cols)` for an array-like argument: real
2710    /// column count from a `RangeRef`/`CellRef` AST node when available,
2711    /// otherwise treats the flattened result as a single row -- the same
2712    /// convention `INDEX`'s 3-arg form already uses (see its `num_cols`
2713    /// match on `args[0]`), since a computed/nested array result (e.g. the
2714    /// output of another array function) carries no shape of its own in
2715    /// this engine's flat-`ResultData::List` representation.
2716    fn array_shape(
2717        &self,
2718        expr: &crate::core::parser::Expr,
2719        context: Option<&Context>,
2720        row: Option<usize>,
2721        col: Option<usize>,
2722        deps: &mut Vec<Dependency>,
2723        scope: &LetScope<'_>,
2724    ) -> Result<(Vec<ResultData>, usize), EngineError> {
2725        use crate::core::parser::Expr;
2726        let items = match self.evaluate_ast(expr, context, row, col, deps, scope)? {
2727            ResultData::List(items) => items,
2728            other => vec![other],
2729        };
2730        let (flat, nested_cols) = Self::flatten_row_major(items);
2731        if let Some(cols) = nested_cols {
2732            return Ok((flat, cols));
2733        }
2734        let num_cols = match expr {
2735            Expr::RangeRef {
2736                start_col, end_col, ..
2737            } => (end_col - start_col + 1).max(1),
2738            Expr::CellRef { .. } => 1,
2739            Expr::FunctionCall { name, args } => self
2740                .function_call_cols(name, args, context, row, col, deps, scope)
2741                .unwrap_or_else(|| flat.len().max(1)),
2742            _ => flat.len().max(1),
2743        };
2744        Ok((flat, num_cols))
2745    }
2746
2747    /// Recovers the column count an array-reshaping function call's result
2748    /// would have, purely from its argument expressions -- needed because
2749    /// this engine's flat `ResultData::List` carries no shape of its own,
2750    /// so nesting one of these calls inside another (e.g.
2751    /// `INDEX(EXPAND(A1:B2,3,3,0),3,3)`) previously fell back to treating
2752    /// the whole result as a single row, corrupting the flat-index math.
2753    /// Returns `None` for anything not in this known set, so callers fall
2754    /// back to the single-row assumption.
2755    #[allow(clippy::too_many_arguments)]
2756    fn function_call_cols(
2757        &self,
2758        name: &str,
2759        args: &[crate::core::parser::Expr],
2760        context: Option<&Context>,
2761        row: Option<usize>,
2762        col: Option<usize>,
2763        deps: &mut Vec<Dependency>,
2764        scope: &LetScope<'_>,
2765    ) -> Option<usize> {
2766        let mut upper = name.to_ascii_uppercase();
2767        if let Some(rest) = upper.strip_prefix("_XLFN.") {
2768            upper = rest.to_string();
2769        }
2770        if let Some(rest) = upper.strip_prefix("_XLWS.") {
2771            upper = rest.to_string();
2772        }
2773        match upper.as_str() {
2774            "TRANSPOSE" => {
2775                let (flat, cols) = self
2776                    .array_shape(args.first()?, context, row, col, deps, scope)
2777                    .ok()?;
2778                Some((flat.len().checked_div(cols).unwrap_or(0)).max(1))
2779            }
2780            "HSTACK" => {
2781                let mut total = 0usize;
2782                for a in args {
2783                    total += self.array_shape(a, context, row, col, deps, scope).ok()?.1;
2784                }
2785                Some(total)
2786            }
2787            "VSTACK" => {
2788                let mut max_cols = 0usize;
2789                for a in args {
2790                    max_cols =
2791                        max_cols.max(self.array_shape(a, context, row, col, deps, scope).ok()?.1);
2792                }
2793                Some(max_cols)
2794            }
2795            "CHOOSEROWS" => Some(
2796                self.array_shape(args.first()?, context, row, col, deps, scope)
2797                    .ok()?
2798                    .1,
2799            ),
2800            "CHOOSECOLS" => Some(args.len().saturating_sub(1).max(1)),
2801            "DROP" | "TAKE" => {
2802                let (_, cols) = self
2803                    .array_shape(args.first()?, context, row, col, deps, scope)
2804                    .ok()?;
2805                let is_take = upper == "TAKE";
2806                match args.get(2) {
2807                    Some(e) => {
2808                        let n = self
2809                            .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope).ok()?)
2810                            .unwrap_or(0.0) as isize;
2811                        let (s, e2) = Self::drop_take_bounds(cols as isize, n, is_take);
2812                        Some((e2 - s).max(0) as usize)
2813                    }
2814                    None => Some(if is_take { cols } else { 0 }),
2815                }
2816            }
2817            "EXPAND" => {
2818                let (_, cols) = self
2819                    .array_shape(args.first()?, context, row, col, deps, scope)
2820                    .ok()?;
2821                match args.get(2) {
2822                    Some(e) => Some(
2823                        self.to_f64(&self.evaluate_ast(e, context, row, col, deps, scope).ok()?)
2824                            .unwrap_or(cols as f64) as usize,
2825                    ),
2826                    None => Some(cols),
2827                }
2828            }
2829            "TOCOL" => Some(1),
2830            "WRAPROWS" => {
2831                let n = self
2832                    .to_f64(
2833                        &self
2834                            .evaluate_ast(args.get(1)?, context, row, col, deps, scope)
2835                            .ok()?,
2836                    )
2837                    .unwrap_or(1.0)
2838                    .max(1.0) as usize;
2839                Some(n)
2840            }
2841            "WRAPCOLS" => {
2842                let (flat, _) = self
2843                    .array_shape(args.first()?, context, row, col, deps, scope)
2844                    .ok()?;
2845                let wrap = self
2846                    .to_f64(
2847                        &self
2848                            .evaluate_ast(args.get(1)?, context, row, col, deps, scope)
2849                            .ok()?,
2850                    )
2851                    .unwrap_or(1.0)
2852                    .max(1.0) as usize;
2853                Some(flat.len().div_ceil(wrap).max(1))
2854            }
2855            "UNIQUE" | "SORT" | "SORTBY" | "FILTER" | "TRIMRANGE" => Some(
2856                self.array_shape(args.first()?, context, row, col, deps, scope)
2857                    .ok()?
2858                    .1,
2859            ),
2860            "SEQUENCE" => match args.get(1) {
2861                Some(e) => Some(
2862                    self.to_f64(&self.evaluate_ast(e, context, row, col, deps, scope).ok()?)
2863                        .unwrap_or(1.0)
2864                        .max(1.0) as usize,
2865                ),
2866                None => Some(1),
2867            },
2868            "MUNIT" => {
2869                let n = self
2870                    .to_f64(
2871                        &self
2872                            .evaluate_ast(args.first()?, context, row, col, deps, scope)
2873                            .ok()?,
2874                    )
2875                    .unwrap_or(1.0)
2876                    .max(1.0) as usize;
2877                Some(n)
2878            }
2879            "MAKEARRAY" => match args.get(1) {
2880                Some(e) => Some(
2881                    self.to_f64(&self.evaluate_ast(e, context, row, col, deps, scope).ok()?)
2882                        .unwrap_or(1.0)
2883                        .max(1.0) as usize,
2884                ),
2885                None => Some(1),
2886            },
2887            _ => None,
2888        }
2889    }
2890
2891    /// Shared `[start, end)` bound computation for `TAKE`/`DROP`: a
2892    /// positive count counts from the start, negative from the end;
2893    /// `is_take` selects which side of that split is kept.
2894    fn drop_take_bounds(total: isize, n: isize, is_take: bool) -> (isize, isize) {
2895        let n = n.clamp(-total, total);
2896        if is_take {
2897            if n >= 0 { (0, n) } else { (total + n, total) }
2898        } else if n >= 0 {
2899            (n, total)
2900        } else {
2901            (0, total + n)
2902        }
2903    }
2904
2905    /// Shared implementation for MAP/BYROW/BYCOL/REDUCE/SCAN/MAKEARRAY:
2906    /// each applies a `LAMBDA` argument to some shape of input (parallel
2907    /// arrays, rows, columns, an accumulator, or generated row/col
2908    /// indices) and collects the results -- see each branch for the
2909    /// specific shape. Dynamic-array results are returned as a flat,
2910    /// row-major `ResultData::List`, the same convention `SEQUENCE`/
2911    /// `MUNIT`/etc. already use, since this engine doesn't spill formulas
2912    /// across cells; callers pull out a single value with `INDEX`.
2913    #[allow(clippy::too_many_arguments)]
2914    fn evaluate_lambda_function(
2915        &self,
2916        func_name: &str,
2917        args: &[crate::core::parser::Expr],
2918        context: Option<&Context>,
2919        row: Option<usize>,
2920        col: Option<usize>,
2921        deps: &mut Vec<Dependency>,
2922        scope: &LetScope<'_>,
2923    ) -> Result<ResultData, EngineError> {
2924        use crate::core::parser::Expr;
2925
2926        match func_name {
2927            "MAP" => {
2928                if args.len() < 2 {
2929                    return Ok(ResultData::Error("#VALUE!".to_string()));
2930                }
2931                let (lambda_expr, array_exprs) = args.split_last().unwrap();
2932                let Some((params, body)) = Self::extract_lambda(lambda_expr) else {
2933                    return Ok(ResultData::Error("#VALUE!".to_string()));
2934                };
2935                if params.len() != array_exprs.len() {
2936                    return Ok(ResultData::Error("#VALUE!".to_string()));
2937                }
2938                let arrays: Vec<Vec<ResultData>> = array_exprs
2939                    .iter()
2940                    .map(|e| self.eval_as_array(e, context, row, col, deps, scope))
2941                    .collect::<Result<_, _>>()?;
2942                let len = arrays.iter().map(|a| a.len()).max().unwrap_or(0);
2943                let mut results = Vec::with_capacity(len);
2944                for i in 0..len {
2945                    let values: Vec<ResultData> = arrays
2946                        .iter()
2947                        .map(|a| a.get(i).cloned().unwrap_or(ResultData::None))
2948                        .collect();
2949                    results.push(
2950                        self.invoke_lambda(&params, &values, body, context, row, col, deps, scope)?,
2951                    );
2952                }
2953                Ok(ResultData::List(results))
2954            }
2955            "BYROW" | "BYCOL" => {
2956                if args.len() != 2 {
2957                    return Ok(ResultData::Error("#VALUE!".to_string()));
2958                }
2959                let Some((params, body)) = Self::extract_lambda(&args[1]) else {
2960                    return Ok(ResultData::Error("#VALUE!".to_string()));
2961                };
2962                if params.len() != 1 {
2963                    return Ok(ResultData::Error("#VALUE!".to_string()));
2964                }
2965                // Recovers real column count the same way INDEX's 3-arg
2966                // form does: re-matching the raw AST node, since the
2967                // already-evaluated array argument is just a flat List.
2968                let num_cols = match &args[0] {
2969                    Expr::RangeRef {
2970                        start_col, end_col, ..
2971                    } => (end_col - start_col + 1).max(1),
2972                    _ => 1,
2973                };
2974                let flat = self.eval_as_array(&args[0], context, row, col, deps, scope)?;
2975                let num_rows = if num_cols == 0 {
2976                    0
2977                } else {
2978                    flat.len().div_ceil(num_cols)
2979                };
2980                let mut results = Vec::new();
2981                if func_name == "BYROW" {
2982                    for r in 0..num_rows {
2983                        let row_vals: Vec<ResultData> = (0..num_cols)
2984                            .filter_map(|c| flat.get(r * num_cols + c).cloned())
2985                            .collect();
2986                        let arg = vec![ResultData::List(row_vals)];
2987                        results.push(
2988                            self.invoke_lambda(
2989                                &params, &arg, body, context, row, col, deps, scope,
2990                            )?,
2991                        );
2992                    }
2993                } else {
2994                    for c in 0..num_cols {
2995                        let col_vals: Vec<ResultData> = (0..num_rows)
2996                            .filter_map(|r| flat.get(r * num_cols + c).cloned())
2997                            .collect();
2998                        let arg = vec![ResultData::List(col_vals)];
2999                        results.push(
3000                            self.invoke_lambda(
3001                                &params, &arg, body, context, row, col, deps, scope,
3002                            )?,
3003                        );
3004                    }
3005                }
3006                Ok(ResultData::List(results))
3007            }
3008            "REDUCE" | "SCAN" => {
3009                // initial_value is optional in real Excel's 3-argument
3010                // REDUCE/SCAN; since the parser has no dedicated "omitted
3011                // argument" syntax to express that, this implementation
3012                // also accepts a plain 2-argument call (array, lambda) as
3013                // the omitted-initial-value form, seeding the accumulator
3014                // from the array's own first element and folding over the
3015                // rest -- rather than only supporting a literal 3rd
3016                // argument that happens to error out.
3017                if args.len() != 2 && args.len() != 3 {
3018                    return Ok(ResultData::Error("#VALUE!".to_string()));
3019                }
3020                let lambda_idx = args.len() - 1;
3021                let array_idx = args.len() - 2;
3022                let Some((params, body)) = Self::extract_lambda(&args[lambda_idx]) else {
3023                    return Ok(ResultData::Error("#VALUE!".to_string()));
3024                };
3025                if params.len() != 2 {
3026                    return Ok(ResultData::Error("#VALUE!".to_string()));
3027                }
3028                let array = self.eval_as_array(&args[array_idx], context, row, col, deps, scope)?;
3029                // SCAN's output has the same length as `array` -- an
3030                // explicit initial_value (3-arg form) is external to the
3031                // array and doesn't get its own output entry (every entry
3032                // is a real fold), whereas the 2-arg fallback's seed *is*
3033                // the array's own first element, so it does.
3034                let (mut acc, rest, mut history): (ResultData, &[ResultData], Vec<ResultData>) =
3035                    if args.len() == 3 {
3036                        let init = self.evaluate_ast(&args[0], context, row, col, deps, scope)?;
3037                        (init, &array[..], Vec::new())
3038                    } else {
3039                        match array.split_first() {
3040                            Some((first, rest)) => (first.clone(), rest, vec![first.clone()]),
3041                            None => return Ok(ResultData::Error("#VALUE!".to_string())),
3042                        }
3043                    };
3044                for item in rest {
3045                    let call_args = [acc.clone(), item.clone()];
3046                    acc = self
3047                        .invoke_lambda(&params, &call_args, body, context, row, col, deps, scope)?;
3048                    history.push(acc.clone());
3049                }
3050                if func_name == "REDUCE" {
3051                    Ok(acc)
3052                } else {
3053                    Ok(ResultData::List(history))
3054                }
3055            }
3056            "MAKEARRAY" => {
3057                if args.len() != 3 {
3058                    return Ok(ResultData::Error("#VALUE!".to_string()));
3059                }
3060                let Some((params, body)) = Self::extract_lambda(&args[2]) else {
3061                    return Ok(ResultData::Error("#VALUE!".to_string()));
3062                };
3063                if params.len() != 2 {
3064                    return Ok(ResultData::Error("#VALUE!".to_string()));
3065                }
3066                let rows_val = self.evaluate_ast(&args[0], context, row, col, deps, scope)?;
3067                let cols_val = self.evaluate_ast(&args[1], context, row, col, deps, scope)?;
3068                let num_rows = self.to_f64(&rows_val).unwrap_or(0.0).max(0.0) as usize;
3069                let num_cols = self.to_f64(&cols_val).unwrap_or(0.0).max(0.0) as usize;
3070                let mut results = Vec::with_capacity(num_rows * num_cols);
3071                for r in 1..=num_rows {
3072                    for c in 1..=num_cols {
3073                        let call_args = [ResultData::Float(r as f64), ResultData::Float(c as f64)];
3074                        results.push(self.invoke_lambda(
3075                            &params, &call_args, body, context, row, col, deps, scope,
3076                        )?);
3077                    }
3078                }
3079                Ok(ResultData::List(results))
3080            }
3081            _ => unreachable!(),
3082        }
3083    }
3084
3085    /// Minimal A1-notation string parser for `INDIRECT`: `"A1"`,
3086    /// `"B2:C5"`, `"Sheet1!A1"`, `"Sheet1!A1:B2"`, with optional `$`
3087    /// absolute markers and an optional `'quoted sheet name'!` prefix.
3088    /// Deliberately small and local rather than shared with
3089    /// `visi/src/utils.rs`'s equivalent parser (`parse_cell_ref`/
3090    /// `parse_range_ref`): `visi-core` cannot depend on the `visi` crate
3091    /// (the dependency direction is the other way), so this necessarily
3092    /// duplicates that logic in miniature.
3093    fn parse_a1_reference(text: &str) -> Option<(Option<String>, usize, usize, usize, usize)> {
3094        let text = text.trim();
3095        let (sheet_part, ref_part) = match text.rfind('!') {
3096            Some(idx) => (Some(&text[..idx]), &text[idx + 1..]),
3097            None => (None, text),
3098        };
3099        let sheet = sheet_part.map(|s| s.trim().trim_matches('\'').to_string());
3100
3101        fn parse_cell(s: &str) -> Option<(usize, usize)> {
3102            let s = s.replace('$', "");
3103            let col_end = s.find(|c: char| c.is_ascii_digit())?;
3104            let (col_str, row_str) = s.split_at(col_end);
3105            if col_str.is_empty() || row_str.is_empty() {
3106                return None;
3107            }
3108            let mut col = 0usize;
3109            for ch in col_str.chars() {
3110                if !ch.is_ascii_alphabetic() {
3111                    return None;
3112                }
3113                col = col * 26 + (ch.to_ascii_uppercase() as usize - 'A' as usize + 1);
3114            }
3115            let row: usize = row_str.parse().ok()?;
3116            if row == 0 || col == 0 {
3117                return None;
3118            }
3119            Some((row - 1, col - 1))
3120        }
3121
3122        if let Some((start, end)) = ref_part.split_once(':') {
3123            let (r1, c1) = parse_cell(start)?;
3124            let (r2, c2) = parse_cell(end)?;
3125            Some((sheet, r1.min(r2), c1.min(c2), r1.max(r2), c1.max(c2)))
3126        } else {
3127            let (r, c) = parse_cell(ref_part)?;
3128            Some((sheet, r, c, r, c))
3129        }
3130    }
3131
3132    /// Reads a single cell, registering the appropriate local/remote
3133    /// dependency -- the same local-vs-remote branch used throughout this
3134    /// file (see e.g. `evaluate_ast`'s `Expr::CellRef` arm), factored out
3135    /// since `CELL`/`FORMULATEXT`/`ISFORMULA`/`INDIRECT`/`OFFSET` all need
3136    /// it for a reference resolved dynamically rather than parsed as an
3137    /// AST node.
3138    fn read_cell_with_deps(
3139        &self,
3140        sheet_opt: &Option<String>,
3141        r: usize,
3142        c: usize,
3143        context: Option<&Context>,
3144        deps: &mut Vec<Dependency>,
3145    ) -> ResultData {
3146        let is_self = sheet_opt.as_deref().is_none_or(|n| n == self.name);
3147        if is_self {
3148            deps.push(Dependency::Local(CellRef::new(r, c)));
3149            self.get_result_data(&CellRef::new(r, c))
3150        } else if let Some(ctx) = context {
3151            let name = sheet_opt.clone().unwrap();
3152            deps.push(Dependency::Remote {
3153                sheet: name.clone(),
3154                cell: CellRef::new(r, c),
3155            });
3156            ctx.sheets
3157                .get(&name)
3158                .map(|s| s.get_result_data(&CellRef::new(r, c)))
3159                .unwrap_or(ResultData::None)
3160        } else {
3161            ResultData::None
3162        }
3163    }
3164
3165    /// Shared implementation for the range/reference-introspection and
3166    /// workbook-metadata functions: ROW/ROWS/COLUMN/COLUMNS need the raw
3167    /// reference's real bounds (not a flattened `evaluated_args` value);
3168    /// AREAS/ISREF are purely syntactic checks on the argument's AST
3169    /// shape; FORMULATEXT/ISFORMULA need the cell's raw source text;
3170    /// INDIRECT/OFFSET build a reference dynamically instead of relying
3171    /// on one already resolved at parse time; SHEET/SHEETS/CELL/INFO
3172    /// report workbook/environment metadata.
3173    #[allow(clippy::too_many_arguments)]
3174    fn evaluate_range_info_function(
3175        &self,
3176        func_name: &str,
3177        args: &[crate::core::parser::Expr],
3178        context: Option<&Context>,
3179        row: Option<usize>,
3180        col: Option<usize>,
3181        deps: &mut Vec<Dependency>,
3182        scope: &LetScope<'_>,
3183    ) -> Result<ResultData, EngineError> {
3184        use crate::core::parser::Expr;
3185
3186        match func_name {
3187            "ROW" => match args.first() {
3188                // A multi-row reference returns an array of row numbers
3189                // (one per row spanned), not just the first one -- a
3190                // single-row reference (including a plain cell, where
3191                // start_row == end_row) still returns the plain scalar.
3192                Some(arg) => match Self::range_bounds(arg) {
3193                    Some((_, start_row, _, end_row, _)) if end_row > start_row => {
3194                        Ok(ResultData::List(
3195                            (start_row..=end_row)
3196                                .map(|r| ResultData::Float((r + 1) as f64))
3197                                .collect(),
3198                        ))
3199                    }
3200                    Some((_, start_row, _, _, _)) => Ok(ResultData::Float((start_row + 1) as f64)),
3201                    None => Ok(ResultData::Error("#VALUE!".to_string())),
3202                },
3203                None => match row {
3204                    Some(r) => Ok(ResultData::Float((r + 1) as f64)),
3205                    None => Ok(ResultData::Error("#VALUE!".to_string())),
3206                },
3207            },
3208            "COLUMN" => match args.first() {
3209                // Same array-vs-scalar distinction as ROW, but across
3210                // columns instead of rows.
3211                Some(arg) => match Self::range_bounds(arg) {
3212                    Some((_, _, start_col, _, end_col)) if end_col > start_col => {
3213                        Ok(ResultData::List(
3214                            (start_col..=end_col)
3215                                .map(|c| ResultData::Float((c + 1) as f64))
3216                                .collect(),
3217                        ))
3218                    }
3219                    Some((_, _, start_col, _, _)) => Ok(ResultData::Float((start_col + 1) as f64)),
3220                    None => Ok(ResultData::Error("#VALUE!".to_string())),
3221                },
3222                None => match col {
3223                    Some(c) => Ok(ResultData::Float((c + 1) as f64)),
3224                    None => Ok(ResultData::Error("#VALUE!".to_string())),
3225                },
3226            },
3227            "ROWS" => {
3228                let Some(arg) = args.first() else {
3229                    return Ok(ResultData::Error("#VALUE!".to_string()));
3230                };
3231                let Some((sheet_opt, start_row, _, end_row, _)) = Self::range_bounds(arg) else {
3232                    return Ok(ResultData::Error("#VALUE!".to_string()));
3233                };
3234                let is_self = sheet_opt.as_deref().is_none_or(|n| n == self.name);
3235                let actual_end_row = if end_row == usize::MAX {
3236                    if is_self {
3237                        self.row_count().saturating_sub(1)
3238                    } else {
3239                        context
3240                            .and_then(|ctx| sheet_opt.as_ref().and_then(|n| ctx.sheets.get(n)))
3241                            .map(|s| s.row_count().saturating_sub(1))
3242                            .unwrap_or(0)
3243                    }
3244                } else {
3245                    end_row
3246                };
3247                Ok(ResultData::Float(
3248                    (actual_end_row.saturating_sub(start_row) + 1) as f64,
3249                ))
3250            }
3251            "COLUMNS" => {
3252                let Some(arg) = args.first() else {
3253                    return Ok(ResultData::Error("#VALUE!".to_string()));
3254                };
3255                match Self::range_bounds(arg) {
3256                    Some((_, _, start_col, _, end_col)) => Ok(ResultData::Float(
3257                        (end_col.saturating_sub(start_col) + 1) as f64,
3258                    )),
3259                    None => Ok(ResultData::Error("#VALUE!".to_string())),
3260                }
3261            }
3262            "AREAS" => {
3263                // This engine's parser has no multi-area (comma-separated
3264                // union) reference syntax, so every reference is exactly
3265                // one area.
3266                if args.is_empty() {
3267                    Ok(ResultData::Error("#VALUE!".to_string()))
3268                } else {
3269                    Ok(ResultData::Float(1.0))
3270                }
3271            }
3272            "ISREF" => Ok(ResultData::Boolean(matches!(
3273                args.first(),
3274                Some(Expr::CellRef { .. } | Expr::RangeRef { .. } | Expr::StructuredRef { .. })
3275            ))),
3276            "FORMULATEXT" | "ISFORMULA" => {
3277                let Some(arg) = args.first() else {
3278                    return Ok(ResultData::Error("#VALUE!".to_string()));
3279                };
3280                let Some((sheet_opt, r, c, _, _)) = Self::range_bounds(arg) else {
3281                    return Ok(ResultData::Error("#VALUE!".to_string()));
3282                };
3283                let is_self = sheet_opt.as_deref().is_none_or(|n| n == self.name);
3284                let src = if is_self {
3285                    deps.push(Dependency::Local(CellRef::new(r, c)));
3286                    self.get_src_str(&CellRef::new(r, c))
3287                } else if let Some(ctx) = context {
3288                    let name = sheet_opt.unwrap();
3289                    deps.push(Dependency::Remote {
3290                        sheet: name.clone(),
3291                        cell: CellRef::new(r, c),
3292                    });
3293                    ctx.sheets
3294                        .get(&name)
3295                        .map(|s| s.get_src_str(&CellRef::new(r, c)))
3296                        .unwrap_or_default()
3297                } else {
3298                    String::new()
3299                };
3300                let is_formula = src.starts_with('=');
3301                if func_name == "ISFORMULA" {
3302                    Ok(ResultData::Boolean(is_formula))
3303                } else if is_formula {
3304                    Ok(ResultData::String(src))
3305                } else {
3306                    Ok(ResultData::Error("#N/A".to_string()))
3307                }
3308            }
3309            "SHEETS" => Ok(ResultData::Float(
3310                context.map(|c| c.sheets.len() + 1).unwrap_or(1) as f64,
3311            )),
3312            "SHEET" => {
3313                // With no argument, report this sheet's own ordinal. With
3314                // a reference argument, report the *referenced* sheet's
3315                // ordinal (a bare reference with no explicit sheet, e.g.
3316                // `SHEET(A1)`, means this sheet). Excel also accepts a
3317                // plain text sheet name, e.g. `SHEET("Sheet2")`.
3318                let sheet_name = match args.first() {
3319                    None => Some(self.name.clone()),
3320                    Some(arg) => match Self::range_bounds(arg) {
3321                        Some((sheet_opt, ..)) => {
3322                            Some(sheet_opt.unwrap_or_else(|| self.name.clone()))
3323                        }
3324                        None => self
3325                            .evaluate_ast(arg, context, row, col, deps, scope)
3326                            .ok()
3327                            .map(|v| v.to_string()),
3328                    },
3329                };
3330
3331                match sheet_name {
3332                    Some(name) => {
3333                        let ordinal = context
3334                            .and_then(|c| {
3335                                c.sheet_order
3336                                    .iter()
3337                                    .position(|n| n.eq_ignore_ascii_case(&name))
3338                            })
3339                            .map(|i| i + 1)
3340                            // No context (standalone eval outside a
3341                            // WorkbookManager pass) or the name wasn't
3342                            // found in workbook order: 1 is the same
3343                            // approximation this used unconditionally
3344                            // before.
3345                            .unwrap_or(1);
3346                        Ok(ResultData::Float(ordinal as f64))
3347                    }
3348                    None => Ok(ResultData::Error("#N/A".to_string())),
3349                }
3350            }
3351            "CELL" => {
3352                if args.is_empty() {
3353                    return Ok(ResultData::Error("#VALUE!".to_string()));
3354                }
3355                let info_type = self
3356                    .evaluate_ast(&args[0], context, row, col, deps, scope)?
3357                    .to_string()
3358                    .to_lowercase();
3359                let bounds = args.get(1).and_then(Self::range_bounds);
3360                match info_type.as_str() {
3361                    "row" => match bounds.map(|b| b.1).or(row) {
3362                        Some(r) => Ok(ResultData::Float((r + 1) as f64)),
3363                        None => Ok(ResultData::Error("#VALUE!".to_string())),
3364                    },
3365                    "col" => match bounds {
3366                        Some((_, _, c, _, _)) => Ok(ResultData::Float((c + 1) as f64)),
3367                        None => Ok(ResultData::Error("#VALUE!".to_string())),
3368                    },
3369                    "address" => match bounds {
3370                        Some((_, r, c, _, _)) => Ok(ResultData::String(format!(
3371                            "${}${}",
3372                            crate::core::parser::col_idx_to_letters(c),
3373                            r + 1
3374                        ))),
3375                        None => Ok(ResultData::Error("#VALUE!".to_string())),
3376                    },
3377                    "contents" => match bounds {
3378                        Some((sheet_opt, r, c, _, _)) => {
3379                            Ok(self.read_cell_with_deps(&sheet_opt, r, c, context, deps))
3380                        }
3381                        None => Ok(ResultData::Error("#VALUE!".to_string())),
3382                    },
3383                    _ => Ok(ResultData::Error("#VALUE!".to_string())),
3384                }
3385            }
3386            "INFO" => {
3387                if args.is_empty() {
3388                    return Ok(ResultData::Error("#VALUE!".to_string()));
3389                }
3390                let info_type = self
3391                    .evaluate_ast(&args[0], context, row, col, deps, scope)?
3392                    .to_string()
3393                    .to_lowercase();
3394                match info_type.as_str() {
3395                    "numfile" => Ok(ResultData::Float(
3396                        context.map(|c| c.sheets.len() + 1).unwrap_or(1) as f64,
3397                    )),
3398                    "release" => Ok(ResultData::String("16.0".to_string())),
3399                    "system" => Ok(ResultData::String(
3400                        if cfg!(target_os = "macos") {
3401                            "mac"
3402                        } else {
3403                            "pcdos"
3404                        }
3405                        .to_string(),
3406                    )),
3407                    _ => Ok(ResultData::Error("#VALUE!".to_string())),
3408                }
3409            }
3410            "INDIRECT" => {
3411                if args.is_empty() {
3412                    return Ok(ResultData::Error("#VALUE!".to_string()));
3413                }
3414                let text = self
3415                    .evaluate_ast(&args[0], context, row, col, deps, scope)?
3416                    .to_string();
3417                let a1_style = match args.get(1) {
3418                    Some(a) => self.to_bool(&self.evaluate_ast(a, context, row, col, deps, scope)?),
3419                    None => true,
3420                };
3421                if !a1_style {
3422                    // R1C1-style reference text isn't supported.
3423                    return Ok(ResultData::Error("#VALUE!".to_string()));
3424                }
3425                match Self::parse_a1_reference(&text) {
3426                    Some((sheet_opt, start_row, start_col, end_row, end_col)) => {
3427                        if start_row == end_row && start_col == end_col {
3428                            Ok(self.read_cell_with_deps(
3429                                &sheet_opt, start_row, start_col, context, deps,
3430                            ))
3431                        } else {
3432                            match self.materialize_range(
3433                                &sheet_opt, start_row, start_col, end_row, end_col, context,
3434                            ) {
3435                                Some(grid) => {
3436                                    Ok(ResultData::List(grid.into_iter().flatten().collect()))
3437                                }
3438                                None => Ok(ResultData::Error("#REF!".to_string())),
3439                            }
3440                        }
3441                    }
3442                    None => Ok(ResultData::Error("#REF!".to_string())),
3443                }
3444            }
3445            "OFFSET" => {
3446                if args.len() < 3 {
3447                    return Ok(ResultData::Error("#VALUE!".to_string()));
3448                }
3449                let Some((sheet_opt, base_row, base_col, base_end_row, base_end_col)) =
3450                    Self::range_bounds(&args[0])
3451                else {
3452                    return Ok(ResultData::Error("#VALUE!".to_string()));
3453                };
3454                let row_offset = self
3455                    .to_f64(&self.evaluate_ast(&args[1], context, row, col, deps, scope)?)
3456                    .unwrap_or(0.0) as isize;
3457                let col_offset = self
3458                    .to_f64(&self.evaluate_ast(&args[2], context, row, col, deps, scope)?)
3459                    .unwrap_or(0.0) as isize;
3460                let base_height = (base_end_row.saturating_sub(base_row) + 1) as isize;
3461                let base_width = (base_end_col.saturating_sub(base_col) + 1) as isize;
3462                let height = match args.get(3) {
3463                    Some(a) => self
3464                        .to_f64(&self.evaluate_ast(a, context, row, col, deps, scope)?)
3465                        .unwrap_or(base_height as f64) as isize,
3466                    None => base_height,
3467                };
3468                let width = match args.get(4) {
3469                    Some(a) => self
3470                        .to_f64(&self.evaluate_ast(a, context, row, col, deps, scope)?)
3471                        .unwrap_or(base_width as f64) as isize,
3472                    None => base_width,
3473                };
3474                let new_row = base_row as isize + row_offset;
3475                let new_col = base_col as isize + col_offset;
3476                if new_row < 0 || new_col < 0 || height <= 0 || width <= 0 {
3477                    return Ok(ResultData::Error("#REF!".to_string()));
3478                }
3479                let (start_row, start_col) = (new_row as usize, new_col as usize);
3480                let (end_row, end_col) = (
3481                    start_row + (height - 1) as usize,
3482                    start_col + (width - 1) as usize,
3483                );
3484                if start_row == end_row && start_col == end_col {
3485                    Ok(self.read_cell_with_deps(&sheet_opt, start_row, start_col, context, deps))
3486                } else {
3487                    match self.materialize_range(
3488                        &sheet_opt, start_row, start_col, end_row, end_col, context,
3489                    ) {
3490                        Some(grid) => Ok(ResultData::List(grid.into_iter().flatten().collect())),
3491                        None => Ok(ResultData::Error("#REF!".to_string())),
3492                    }
3493                }
3494            }
3495            _ => unreachable!(),
3496        }
3497    }
3498
3499    /// `GETPIVOTDATA(data_field, pivot_table_ref, [field, item]...)`.
3500    /// `pivot_table_ref` must stay an unevaluated cell reference (not a
3501    /// flattened value) so its sheet/row/col can be matched against
3502    /// `context.pivot_tables`' rendered destination ranges -- the same
3503    /// reason `ROW`/`OFFSET`/etc. go through `evaluate_range_info_function`
3504    /// instead of the generic eagerly-evaluated-args path below.
3505    fn evaluate_getpivotdata(
3506        &self,
3507        args: &[crate::core::parser::Expr],
3508        context: Option<&Context>,
3509        row: Option<usize>,
3510        col: Option<usize>,
3511        deps: &mut Vec<Dependency>,
3512        scope: &LetScope<'_>,
3513    ) -> Result<ResultData, EngineError> {
3514        if args.len() < 2 || !(args.len() - 2).is_multiple_of(2) {
3515            return Ok(ResultData::Error("#VALUE!".to_string()));
3516        }
3517
3518        let data_field = self
3519            .evaluate_ast(&args[0], context, row, col, deps, scope)?
3520            .to_string();
3521
3522        let (sheet_opt, target_row, target_col, _, _) = match Self::range_bounds(&args[1]) {
3523            Some(bounds) => bounds,
3524            None => return Ok(ResultData::Error("#REF!".to_string())),
3525        };
3526        // Registers the usual dependency on the referenced cell, mirroring
3527        // how INDIRECT/OFFSET treat a dynamically resolved reference.
3528        self.read_cell_with_deps(&sheet_opt, target_row, target_col, context, deps);
3529
3530        let sheet_id = match &sheet_opt {
3531            None => self.id,
3532            Some(name) if name == &self.name => self.id,
3533            Some(name) => match context.and_then(|c| c.sheets.get(name)) {
3534                Some(s) => s.id,
3535                None => return Ok(ResultData::Error("#REF!".to_string())),
3536            },
3537        };
3538
3539        let pivot_tables = context.map(|c| c.pivot_tables).unwrap_or(&[]);
3540        let pivot = match pivot_tables.iter().find(|p| {
3541            p.dest_sheet_id == sheet_id
3542                && p.last_output_end_row
3543                    .is_some_and(|end| target_row >= p.dest_row && target_row <= end)
3544                && p.last_output_end_col
3545                    .is_some_and(|end| target_col >= p.dest_col && target_col <= end)
3546        }) {
3547            Some(p) => p,
3548            None => return Ok(ResultData::Error("#REF!".to_string())),
3549        };
3550
3551        let mut criteria: Vec<(String, String)> = Vec::new();
3552        let mut i = 2;
3553        while i < args.len() {
3554            let field = self
3555                .evaluate_ast(&args[i], context, row, col, deps, scope)?
3556                .to_string();
3557            let item = self
3558                .evaluate_ast(&args[i + 1], context, row, col, deps, scope)?
3559                .to_string();
3560            criteria.push((field, item));
3561            i += 2;
3562        }
3563
3564        let mut sheet_refs: Vec<&Sheet> = context
3565            .map(|c| c.sheets.values().copied().collect())
3566            .unwrap_or_default();
3567        sheet_refs.push(self);
3568
3569        match crate::core::pivot::getpivotdata(&sheet_refs, pivot, &data_field, &criteria) {
3570            Ok(v) => Ok(v),
3571            Err(e) => Ok(ResultData::Error(e)),
3572        }
3573    }
3574
3575    /// Shared implementation for the dynamic-array reshaping functions.
3576    /// All operate on `array_shape`'s `(flat, num_cols)` view and return a
3577    /// flat, row-major `ResultData::List` -- the same convention
3578    /// `SEQUENCE`/`MUNIT`/`MAKEARRAY`/etc. already use, since this engine
3579    /// doesn't spill formulas across cells (a caller pulls out a single
3580    /// value with `INDEX`, or consumes the whole list with e.g. `SUM`).
3581    ///
3582    /// Known simplifications, each accepted given limited fuzzing time
3583    /// against real Excel for this batch: `UNIQUE`'s `by_col` and `SORT`'s
3584    /// `by_col` arguments are ignored (both always operate row-wise);
3585    /// `SORTBY` only supports a single `by_array`/`sort_order` pair, not
3586    /// the documented repeating list; `XMATCH`'s wildcard match mode and
3587    /// binary/reverse search modes aren't implemented (falls through to a
3588    /// forward linear scan).
3589    #[allow(clippy::too_many_arguments)]
3590    fn evaluate_array_reshape_function(
3591        &self,
3592        func_name: &str,
3593        args: &[crate::core::parser::Expr],
3594        context: Option<&Context>,
3595        row: Option<usize>,
3596        col: Option<usize>,
3597        deps: &mut Vec<Dependency>,
3598        scope: &LetScope<'_>,
3599    ) -> Result<ResultData, EngineError> {
3600        match func_name {
3601            "TRANSPOSE" => {
3602                let Some(arg) = args.first() else {
3603                    return Ok(ResultData::Error("#VALUE!".to_string()));
3604                };
3605                let (flat, cols) = self.array_shape(arg, context, row, col, deps, scope)?;
3606                let rows = flat.len().checked_div(cols).unwrap_or(0);
3607                let mut result = Vec::with_capacity(flat.len());
3608                for c in 0..cols {
3609                    for r in 0..rows {
3610                        result.push(flat[r * cols + c].clone());
3611                    }
3612                }
3613                Ok(ResultData::List(result))
3614            }
3615            "HSTACK" | "VSTACK" => {
3616                if args.is_empty() {
3617                    return Ok(ResultData::Error("#VALUE!".to_string()));
3618                }
3619                let mut shapes = Vec::with_capacity(args.len());
3620                for a in args {
3621                    shapes.push(self.array_shape(a, context, row, col, deps, scope)?);
3622                }
3623                let mut result = Vec::new();
3624                if func_name == "HSTACK" {
3625                    let max_rows = shapes
3626                        .iter()
3627                        .map(|(f, c)| if *c == 0 { 0 } else { f.len() / c })
3628                        .max()
3629                        .unwrap_or(0);
3630                    for r in 0..max_rows {
3631                        for (flat, cols) in &shapes {
3632                            let rows = if *cols == 0 { 0 } else { flat.len() / cols };
3633                            for c in 0..*cols {
3634                                result.push(if r < rows {
3635                                    flat[r * cols + c].clone()
3636                                } else {
3637                                    ResultData::Error("#N/A".to_string())
3638                                });
3639                            }
3640                        }
3641                    }
3642                } else {
3643                    let max_cols = shapes.iter().map(|(_, c)| *c).max().unwrap_or(0);
3644                    for (flat, cols) in &shapes {
3645                        let rows = if *cols == 0 { 0 } else { flat.len() / cols };
3646                        for r in 0..rows {
3647                            for c in 0..max_cols {
3648                                result.push(if c < *cols {
3649                                    flat[r * cols + c].clone()
3650                                } else {
3651                                    ResultData::Error("#N/A".to_string())
3652                                });
3653                            }
3654                        }
3655                    }
3656                }
3657                Ok(ResultData::List(result))
3658            }
3659            "CHOOSEROWS" | "CHOOSECOLS" => {
3660                if args.len() < 2 {
3661                    return Ok(ResultData::Error("#VALUE!".to_string()));
3662                }
3663                let (flat, cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3664                let rows = flat.len().checked_div(cols).unwrap_or(0);
3665                let total = if func_name == "CHOOSEROWS" {
3666                    rows
3667                } else {
3668                    cols
3669                } as isize;
3670                let mut indices = Vec::with_capacity(args.len() - 1);
3671                for idx_expr in &args[1..] {
3672                    let n = self
3673                        .to_f64(&self.evaluate_ast(idx_expr, context, row, col, deps, scope)?)
3674                        .unwrap_or(0.0) as isize;
3675                    let real_idx = if n < 0 { total + n } else { n - 1 };
3676                    if real_idx < 0 || real_idx >= total {
3677                        return Ok(ResultData::Error("#VALUE!".to_string()));
3678                    }
3679                    indices.push(real_idx as usize);
3680                }
3681                let mut result = Vec::new();
3682                if func_name == "CHOOSEROWS" {
3683                    for r in indices {
3684                        for c in 0..cols {
3685                            result.push(flat[r * cols + c].clone());
3686                        }
3687                    }
3688                } else {
3689                    for r in 0..rows {
3690                        for &c in &indices {
3691                            result.push(flat[r * cols + c].clone());
3692                        }
3693                    }
3694                }
3695                Ok(ResultData::List(result))
3696            }
3697            "DROP" | "TAKE" => {
3698                if args.len() < 2 {
3699                    return Ok(ResultData::Error("#VALUE!".to_string()));
3700                }
3701                let (flat, cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3702                let num_rows = flat.len().checked_div(cols).unwrap_or(0) as isize;
3703                let is_take = func_name == "TAKE";
3704                let rows_n = self
3705                    .to_f64(&self.evaluate_ast(&args[1], context, row, col, deps, scope)?)
3706                    .unwrap_or(0.0) as isize;
3707                let cols_n = match args.get(2) {
3708                    Some(e) => self
3709                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3710                        .unwrap_or(0.0) as isize,
3711                    None => {
3712                        if is_take {
3713                            cols as isize
3714                        } else {
3715                            0
3716                        }
3717                    }
3718                };
3719                let (row_start, row_end) = Self::drop_take_bounds(num_rows, rows_n, is_take);
3720                let (col_start, col_end) = Self::drop_take_bounds(cols as isize, cols_n, is_take);
3721                if row_start >= row_end || col_start >= col_end {
3722                    return Ok(ResultData::Error("#CALC!".to_string()));
3723                }
3724                let mut result = Vec::new();
3725                for r in row_start..row_end {
3726                    for c in col_start..col_end {
3727                        result.push(flat[(r as usize) * cols + (c as usize)].clone());
3728                    }
3729                }
3730                Ok(ResultData::List(result))
3731            }
3732            "EXPAND" => {
3733                if args.len() < 2 {
3734                    return Ok(ResultData::Error("#VALUE!".to_string()));
3735                }
3736                let (flat, cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3737                let orig_rows = flat.len().checked_div(cols).unwrap_or(0);
3738                let new_rows = self
3739                    .to_f64(&self.evaluate_ast(&args[1], context, row, col, deps, scope)?)
3740                    .unwrap_or(orig_rows as f64) as usize;
3741                let new_cols = match args.get(2) {
3742                    Some(e) => self
3743                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3744                        .unwrap_or(cols as f64) as usize,
3745                    None => cols,
3746                };
3747                let pad = match args.get(3) {
3748                    Some(e) => self.evaluate_ast(e, context, row, col, deps, scope)?,
3749                    None => ResultData::Error("#N/A".to_string()),
3750                };
3751                if new_rows < orig_rows || new_cols < cols {
3752                    return Ok(ResultData::Error("#VALUE!".to_string()));
3753                }
3754                let mut result = Vec::with_capacity(new_rows * new_cols);
3755                for r in 0..new_rows {
3756                    for c in 0..new_cols {
3757                        result.push(if r < orig_rows && c < cols {
3758                            flat[r * cols + c].clone()
3759                        } else {
3760                            pad.clone()
3761                        });
3762                    }
3763                }
3764                Ok(ResultData::List(result))
3765            }
3766            "TOCOL" | "TOROW" => {
3767                let Some(arg) = args.first() else {
3768                    return Ok(ResultData::Error("#VALUE!".to_string()));
3769                };
3770                let (flat, cols) = self.array_shape(arg, context, row, col, deps, scope)?;
3771                let rows = flat.len().checked_div(cols).unwrap_or(0);
3772                let ignore = match args.get(1) {
3773                    Some(e) => self
3774                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3775                        .unwrap_or(0.0) as i64,
3776                    None => 0,
3777                };
3778                let scan_by_col = match args.get(2) {
3779                    Some(e) => self.to_bool(&self.evaluate_ast(e, context, row, col, deps, scope)?),
3780                    None => false,
3781                };
3782                let ordered: Vec<ResultData> = if scan_by_col {
3783                    let mut v = Vec::with_capacity(flat.len());
3784                    for c in 0..cols {
3785                        for r in 0..rows {
3786                            v.push(flat[r * cols + c].clone());
3787                        }
3788                    }
3789                    v
3790                } else {
3791                    flat
3792                };
3793                let filtered: Vec<ResultData> = ordered
3794                    .into_iter()
3795                    .filter(|v| match ignore {
3796                        1 => !matches!(v, ResultData::None),
3797                        2 => !matches!(v, ResultData::Error(_)),
3798                        3 => !matches!(v, ResultData::None | ResultData::Error(_)),
3799                        _ => true,
3800                    })
3801                    .collect();
3802                Ok(ResultData::List(filtered))
3803            }
3804            "WRAPROWS" | "WRAPCOLS" => {
3805                if args.len() < 2 {
3806                    return Ok(ResultData::Error("#VALUE!".to_string()));
3807                }
3808                let (flat, _cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3809                let wrap = self
3810                    .to_f64(&self.evaluate_ast(&args[1], context, row, col, deps, scope)?)
3811                    .unwrap_or(1.0)
3812                    .max(1.0) as usize;
3813                let pad = match args.get(2) {
3814                    Some(e) => self.evaluate_ast(e, context, row, col, deps, scope)?,
3815                    None => ResultData::Error("#N/A".to_string()),
3816                };
3817                if func_name == "WRAPROWS" {
3818                    // Row-major flat storage with num_cols == wrap is
3819                    // exactly the padded input sequence itself.
3820                    let mut result = flat;
3821                    let rem = result.len() % wrap;
3822                    if rem != 0 {
3823                        result.extend(std::iter::repeat_n(pad, wrap - rem));
3824                    }
3825                    Ok(ResultData::List(result))
3826                } else {
3827                    let num_result_cols = flat.len().div_ceil(wrap).max(1);
3828                    let total = wrap * num_result_cols;
3829                    let mut result = Vec::with_capacity(total);
3830                    for i in 0..total {
3831                        let col = i / wrap;
3832                        let r = i % wrap;
3833                        let target = r * num_result_cols + col;
3834                        while result.len() <= target {
3835                            result.push(pad.clone());
3836                        }
3837                        if i < flat.len() {
3838                            result[target] = flat[i].clone();
3839                        }
3840                    }
3841                    Ok(ResultData::List(result))
3842                }
3843            }
3844            "UNIQUE" => {
3845                let Some(arg) = args.first() else {
3846                    return Ok(ResultData::Error("#VALUE!".to_string()));
3847                };
3848                let (flat, _cols) = self.array_shape(arg, context, row, col, deps, scope)?;
3849                let exactly_once = match args.get(2) {
3850                    Some(e) => self.to_bool(&self.evaluate_ast(e, context, row, col, deps, scope)?),
3851                    None => false,
3852                };
3853                let mut seen: Vec<(String, ResultData, usize)> = Vec::new();
3854                for v in &flat {
3855                    let key = v.to_string();
3856                    match seen.iter_mut().find(|(k, ..)| k == &key) {
3857                        Some(entry) => entry.2 += 1,
3858                        None => seen.push((key, v.clone(), 1)),
3859                    }
3860                }
3861                let result: Vec<ResultData> = seen
3862                    .into_iter()
3863                    .filter(|(_, _, count)| !exactly_once || *count == 1)
3864                    .map(|(_, v, _)| v)
3865                    .collect();
3866                Ok(ResultData::List(result))
3867            }
3868            "SORT" => {
3869                let Some(arg) = args.first() else {
3870                    return Ok(ResultData::Error("#VALUE!".to_string()));
3871                };
3872                let (flat, cols) = self.array_shape(arg, context, row, col, deps, scope)?;
3873                let rows = flat.len().checked_div(cols).unwrap_or(0);
3874                let sort_index = match args.get(1) {
3875                    Some(e) => self
3876                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3877                        .unwrap_or(1.0) as usize,
3878                    None => 1,
3879                };
3880                let sort_order = match args.get(2) {
3881                    Some(e) => self
3882                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3883                        .unwrap_or(1.0),
3884                    None => 1.0,
3885                };
3886                let col_idx = sort_index.saturating_sub(1).min(cols.saturating_sub(1));
3887                let mut row_indices: Vec<usize> = (0..rows).collect();
3888                row_indices.sort_by(|&a, &b| {
3889                    Self::sort_compare_blanks_last(
3890                        &flat[a * cols + col_idx],
3891                        &flat[b * cols + col_idx],
3892                        sort_order,
3893                    )
3894                });
3895                let mut result = Vec::with_capacity(flat.len());
3896                for r in row_indices {
3897                    for c in 0..cols {
3898                        result.push(flat[r * cols + c].clone());
3899                    }
3900                }
3901                Ok(ResultData::List(result))
3902            }
3903            "SORTBY" => {
3904                if args.len() < 2 {
3905                    return Ok(ResultData::Error("#VALUE!".to_string()));
3906                }
3907                let (flat, cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3908                let rows = flat.len().checked_div(cols).unwrap_or(0);
3909                let by = self.eval_as_array(&args[1], context, row, col, deps, scope)?;
3910                let order = match args.get(2) {
3911                    Some(e) => self
3912                        .to_f64(&self.evaluate_ast(e, context, row, col, deps, scope)?)
3913                        .unwrap_or(1.0),
3914                    None => 1.0,
3915                };
3916                let mut row_indices: Vec<usize> = (0..rows).collect();
3917                row_indices.sort_by(|&a, &b| {
3918                    let va = by.get(a).cloned().unwrap_or(ResultData::None);
3919                    let vb = by.get(b).cloned().unwrap_or(ResultData::None);
3920                    Self::sort_compare_blanks_last(&va, &vb, order)
3921                });
3922                let mut result = Vec::with_capacity(flat.len());
3923                for r in row_indices {
3924                    for c in 0..cols {
3925                        result.push(flat[r * cols + c].clone());
3926                    }
3927                }
3928                Ok(ResultData::List(result))
3929            }
3930            "FILTER" => {
3931                if args.len() < 2 {
3932                    return Ok(ResultData::Error("#VALUE!".to_string()));
3933                }
3934                let (flat, cols) = self.array_shape(&args[0], context, row, col, deps, scope)?;
3935                let rows = flat.len().checked_div(cols).unwrap_or(0);
3936                let include = self.eval_as_array(&args[1], context, row, col, deps, scope)?;
3937                let mut result = Vec::new();
3938                for r in 0..rows {
3939                    let keep = include.get(r).map(|v| self.to_bool(v)).unwrap_or(false);
3940                    if keep {
3941                        for c in 0..cols {
3942                            result.push(flat[r * cols + c].clone());
3943                        }
3944                    }
3945                }
3946                if result.is_empty() {
3947                    match args.get(2) {
3948                        Some(e) => Ok(self.evaluate_ast(e, context, row, col, deps, scope)?),
3949                        None => Ok(ResultData::Error("#CALC!".to_string())),
3950                    }
3951                } else {
3952                    Ok(ResultData::List(result))
3953                }
3954            }
3955            "TRIMRANGE" => {
3956                let Some(arg) = args.first() else {
3957                    return Ok(ResultData::Error("#VALUE!".to_string()));
3958                };
3959                let (flat, cols) = self.array_shape(arg, context, row, col, deps, scope)?;
3960                let rows = flat.len().checked_div(cols).unwrap_or(0);
3961                let is_blank = |v: &ResultData| {
3962                    matches!(v, ResultData::None)
3963                        || matches!(v, ResultData::String(s) if s.is_empty())
3964                };
3965                let row_blank = |r: usize| (0..cols).all(|c| is_blank(&flat[r * cols + c]));
3966                let col_blank = |c: usize| (0..rows).all(|r| is_blank(&flat[r * cols + c]));
3967                let mut r_start = 0;
3968                while r_start < rows && row_blank(r_start) {
3969                    r_start += 1;
3970                }
3971                let mut r_end = rows;
3972                while r_end > r_start && row_blank(r_end - 1) {
3973                    r_end -= 1;
3974                }
3975                let mut c_start = 0;
3976                while c_start < cols && col_blank(c_start) {
3977                    c_start += 1;
3978                }
3979                let mut c_end = cols;
3980                while c_end > c_start && col_blank(c_end - 1) {
3981                    c_end -= 1;
3982                }
3983                let mut result = Vec::new();
3984                for r in r_start..r_end {
3985                    for c in c_start..c_end {
3986                        result.push(flat[r * cols + c].clone());
3987                    }
3988                }
3989                Ok(ResultData::List(result))
3990            }
3991            _ => unreachable!(),
3992        }
3993    }
3994
3995    /// The raw text typed into a cell -- `"10"`, `"=SUM(A1:A2)"` -- or `None`
3996    /// if the cell is outside the sheet's allocated grid.
3997    ///
3998    /// This is the input, not the result; see [`Sheet::get_result_data`] for
3999    /// the computed value and `Sheet::get_display_string` for what a user
4000    /// should see.
4001    pub fn get_src(&self, cell: &CellRef) -> Option<&String> {
4002        let col = self.columns.get(cell.col);
4003        if let Some(col) = col {
4004            col.src.get(cell.row)
4005        } else {
4006            None
4007        }
4008    }
4009
4010    /// [`Sheet::get_src`] with an out-of-range cell flattened to an owned
4011    /// empty string.
4012    pub fn get_src_str(&self, cell: &CellRef) -> String {
4013        let col = self.columns.get(cell.col);
4014        if let Some(col) = col {
4015            col.src.get(cell.row).cloned().unwrap_or("".to_string())
4016        } else {
4017            "".to_string()
4018        }
4019    }
4020
4021    /// [`Sheet::get_src`] as a borrowed `&str`, for callers that only read.
4022    pub fn get_src_str_ref(&self, cell: &CellRef) -> Option<&str> {
4023        let col = self.columns.get(cell.col)?;
4024        col.src.get(cell.row).map(|s| s.as_str())
4025    }
4026
4027    /// The word surrounding `char_offset` in a cell's source text, as a
4028    /// half-open range of character (not byte) indices -- what an editor needs
4029    /// for word-wise selection. See [`get_word_boundaries_from_str`].
4030    pub fn get_word_boundaries(&self, cell: &CellRef, char_offset: usize) -> (usize, usize) {
4031        let text = self.get_src_str(cell);
4032        get_word_boundaries_from_str(&text, char_offset)
4033    }
4034}