From b1fa239b583d2bb74ed9d449f435ddaa1de4702b Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:39:30 -0400 Subject: [PATCH 01/13] XLSX: legacy formulas (no dynamic-array cm) open with Excel's implicit @ and calculate like Excel; implied @ saved back without cm Co-Authored-By: Claude Opus 5.5 --- crates/calc/src/tests.rs | 35 ++ crates/engine/src/io.rs | 13 +- crates/formula/src/parser.rs | 6 +- crates/formula/src/tests.rs | 9 + crates/xlsx/src/array_formula.rs | 573 ++++++++++++++++++++------ crates/xlsx/src/fmla.rs | 10 +- crates/xlsx/src/lib.rs | 49 ++- crates/xlsx/src/read.rs | 13 +- crates/xlsx/src/sheet_read.rs | 5 + crates/xlsx/src/sheet_write.rs | 22 +- crates/xlsx/src/tests/array_export.rs | 10 +- crates/xlsx/src/tests/fixtures.rs | 68 +++ crates/xlsx/src/tests/roundtrip.rs | 43 +- crates/xlsx/src/write.rs | 7 +- docs/decisions.md | 4 +- docs/file-format-parity.md | 5 +- docs/function-parity.md | 5 +- 17 files changed, 713 insertions(+), 164 deletions(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..fd660dcdd0 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1266,3 +1266,38 @@ fn offset_extreme_arguments_return_ref() { assert_eq!(crate::evaluate(&wb, 0, c("D1"), formula), Value::Number(expected), "{formula}"); } } + +/// `@` intersects a reference with the formula's row (a column range) or column (a row range); +/// a 2D range or one the formula does not line up with gives #VALUE!. An array gives its +/// top-left value. Legacy formulas read from files use it where Excel intersects implicitly. +#[test] +fn implicit_intersection_operator() { + let mut t = T::new(); + for (at, v) in [("A1", "1"), ("A2", "2"), ("A3", "3"), ("A5", "4"), ("B5", "5"), ("C5", "6")] { + t.set(at, v); + } + t.set("B2", "=TANH(@A1:A3)"); + t.set("B7", "=TANH(@A5:C5)"); + t.set("B3", "=@A1:C3"); + t.set("B9", "=@A1:A3"); + t.set("E9", "=@A5:C5"); + t.set("D1", "=@{7,8;9,10}"); + t.set("D2", "=@A2"); + t.set("D3", "=SUM(@A1:A3)"); + assert_eq!(t.num("B2"), 2f64.tanh()); + assert_eq!(t.num("B7"), 5f64.tanh()); + for at in ["B3", "B9", "E9"] { + assert_eq!(t.get(at), Value::Error(CellError::Value), "{at}"); + } + assert_eq!(t.num("D1"), 7.0); + assert_eq!(t.num("D2"), 2.0); + assert_eq!(t.num("D3"), 3.0); + // An array result shows its top-left value (T of a reference reads its top-left cell). + t.set("A11", "x"); + t.set("C11", "y"); + t.set("E1", "=@T(A11:C11)"); + assert_eq!(t.get("E1"), Value::text("x")); + // Without `@` (a dynamic-array formula) the same formula spills. + t.set("F1", "=TANH(A1:A3)"); + assert_eq!((t.num("F1"), t.num("F2"), t.num("F3")), (1f64.tanh(), 2f64.tanh(), 3f64.tanh())); +} diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 3e84036cbc..ca5919a005 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -7,6 +7,13 @@ use gridcraft_model::{Sheet, Workbook}; use crate::{EngineError, Result}; +/// The function library's answers to what the XLSX reader and writer need to know about functions +/// (which names are built in, which parameters take a single value). +pub const XLSX_FUNCTIONS: gridcraft_xlsx::FunctionInfo = gridcraft_xlsx::FunctionInfo { + is_builtin: |name| gridcraft_functions::lookup(name).is_some(), + is_scalar_arg: |name, i| gridcraft_functions::lookup(name).is_none_or(|s| s.is_scalar_arg(i)), +}; + /// File formats GridCraft reads or writes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FileKind { @@ -140,7 +147,8 @@ fn open_plain(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec)> { } // Text named `.xlsx` is read as text. if sniffed == gridcraft_xlsx::Format::Xlsx || (kind == Some(FileKind::Xlsx) && sniffed != gridcraft_xlsx::Format::Csv) { - let (wb, report) = gridcraft_xlsx::read_xlsx(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?; + let (wb, report) = + gridcraft_xlsx::read_xlsx_with(bytes, XLSX_FUNCTIONS).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?; return Ok((wb, report.warnings)); } match kind { @@ -200,7 +208,8 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result gridcraft_xlsx::write_xlsx_as(wb, gridcraft_xlsx::XlsxKind::from_path(path)).map_err(|e| EngineError::Other(e.to_string())), + FileKind::Xlsx => gridcraft_xlsx::write_xlsx_with(wb, gridcraft_xlsx::XlsxKind::from_path(path), XLSX_FUNCTIONS) + .map_err(|e| EngineError::Other(e.to_string())), FileKind::Xls => { Err(EngineError::Other("Excel 97-2003 (.xls) is supported for import only. Save as .xlsx or another supported export format.".into())) } diff --git a/crates/formula/src/parser.rs b/crates/formula/src/parser.rs index 3ea97085e6..4bd584d81e 100644 --- a/crates/formula/src/parser.rs +++ b/crates/formula/src/parser.rs @@ -252,11 +252,15 @@ impl Parser { { return Ok(Expr::Unary(UnOp::Spill, Box::new(r))); } - // Files write `@x` as `_xlfn.SINGLE(x)`. + // Files write `@x` as `_xlfn.SINGLE(x)`; `SINGLE(A1:A3*2)` is `@(A1:A3*2)`. if name == "SINGLE" && args.len() == 1 && let Some(x) = args.pop() { + let x = match x { + Expr::Binary(..) | Expr::Unary(UnOp::Neg | UnOp::Plus | UnOp::Percent, _) => Expr::Paren(Box::new(x)), + x => x, + }; return Ok(Expr::Unary(UnOp::At, Box::new(x))); } // Files may spell a trim reference as a function call (`_xlfn._TRO_ALL(A1:E10)`). diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index 103a26bd1c..d37d94b464 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -93,6 +93,15 @@ fn spill_operator() { assert_eq!(print(&crate::adjust::delete_sheet(parse("SUM(Data!A1#)").unwrap(), "Data", &[])), "SUM(#REF!)"); } +/// Files spell `@x` as `_xlfn.SINGLE(x)`; an operation inside keeps its parentheses. +#[test] +fn single_is_the_implicit_intersection_operator() { + assert_eq!(rt("_xlfn.SINGLE(A1:A3)*2"), "@A1:A3*2"); + assert_eq!(rt("_xlfn.SINGLE(A1:A3*2)"), "@(A1:A3*2)"); + assert_eq!(rt("_xlfn.SINGLE(-A1:A3)"), "@(-A1:A3)"); + assert_eq!(rt("SQRT(_xlfn.SINGLE(Data[Qty]))"), "SQRT(@Data[Qty])"); +} + #[test] fn delete_sheet_shrinks_3d_span() { let order: Vec = ["Sheet1", "Sheet2", "Sheet3", "Results"].iter().map(|s| s.to_string()).collect(); diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index caa5e8e9f6..254755415b 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -1,68 +1,217 @@ -//! Export-time implicit-intersection analysis, without evaluating the workbook. +//! Legacy (pre-dynamic-array) cell formulas and implicit intersection, without evaluating. //! -//! A range is harmless in SUM, but not in SQRT or arithmetic. Keep the result's shape separate -//! from affected operations inside it: SUM(range * range) returns a scalar yet needs array -//! evaluation. Legacy array-aware contexts such as SUMPRODUCT already preserve those operations. +//! Excel evaluates a cell formula saved without dynamic-array metadata (no `cm` attribute) the +//! legacy way: a reference that may cover several cells, used where one value is expected, is +//! intersected with the formula's row or column, and a multi-valued result shows its top-left +//! value. Dynamic-array Excel displays such a formula with the implicit intersection operator `@` +//! inserted where that happens (Microsoft support, "Implicit intersection operator: @"). The +//! reader does the same ([`apply_legacy`]), so the dynamic-array evaluator computes the legacy +//! result; the writer ([`export`]) saves a formula that is the legacy reading of some text as +//! that text, without `@`, and gives every other formula dynamic-array metadata. +//! +//! A range is harmless in SUM, but not in SQRT or arithmetic: `SUM(A1:A3*B1:B3)` intersects both +//! operands. Legacy array-aware parameters such as SUMPRODUCT's evaluate everything inside as +//! arrays, so nothing there is intersected. This is file-format policy, not a second evaluator: +//! unknown results are never calculated. + +use std::sync::Arc; use gridcraft_core::CellRef; use gridcraft_formula::{BinOp, Expr, SheetSel, StructItem, UnOp}; use gridcraft_model::{Formula, Workbook}; -#[derive(Clone, Copy, Default)] -struct Shape { - array: bool, - affected: bool, +use crate::FunctionInfo; + +/// What an expression produces, as far as implicit intersection is concerned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// One value, or a reference to one cell. + Scalar, + /// A reference that may cover several cells. + Ref, + /// Several values that are not a reference. + Array, } -impl Shape { - fn array() -> Self { - Self { array: true, affected: false } +impl Kind { + fn join(self, other: Kind) -> Kind { + match (self, other) { + (Kind::Array, _) | (_, Kind::Array) => Kind::Array, + (Kind::Ref, _) | (_, Kind::Ref) => Kind::Ref, + _ => Kind::Scalar, + } } } -pub(crate) fn needs_array(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula) -> bool { - let Some(expr) = formula.expr_arc() else { return false }; - let mut scan = Scan { wb, at, remaining: 4096, locals: Vec::new() }; - let shape = scan.expr(&expr, sheet, false, 0); - // An explicit `@` is written as `_xlfn.SINGLE`, which only dynamic-array formulas carry. - let mut at = false; - expr.walk(&mut |e| at |= matches!(e, Expr::Unary(UnOp::At, _))); - shape.array || shape.affected || at +/// How a position consumes its operand in a legacy formula. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Ctx { + /// One value: a multi-cell reference is intersected. + Value, + /// A reference or array as such (SUM's arguments); nested operations still take values. + Ref, + /// Array evaluation of everything inside (SUMPRODUCT's arguments): nothing is intersected. + Array, +} + +/// A function parameter's legacy evaluation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Param { + Value, + Ref, + Array, + /// The parameter is evaluated like the call itself (IF's and CHOOSE's results). + Pass, + /// A value read from the top-left cell of a reference, never intersected (T: Excel caches + /// `T(H12:J12)` as T of H12 in a formula outside columns H:J). The function lifts over the + /// cells, so the legacy result is the top-left one. + First, + /// An array parameter of a dynamic-array-era function: whether Excel evaluates a legacy + /// formula there as an array is not established, so such formulas are written as dynamic. + Uncertain, +} + +/// How the writer saves a formula that neither spills nor is a legacy CSE array. +pub(crate) enum Export { + /// As it is, without dynamic-array metadata. + Unchanged, + /// As this expression (the formula without its implicit `@`), without dynamic-array metadata. + Legacy(Expr), + /// With dynamic-array metadata: legacy evaluation would differ. + Dynamic, +} + +pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo) -> Export { + let Some(expr) = formula.expr_arc() else { return Export::Unchanged }; + let mut explicit = false; + expr.walk(&mut |e| explicit |= matches!(e, Expr::Unary(UnOp::At, _))); + let plain = if explicit { strip(expr.as_ref().clone()) } else { expr.as_ref().clone() }; + let mut legacy = Legacy::new(wb, at, functions); + let read_back = legacy.formula(plain.clone(), sheet); + if !legacy.certain { + return Export::Dynamic; + } + if !explicit { + return if legacy.inserted { Export::Dynamic } else { Export::Unchanged }; + } + if gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } +} + +/// Rewrites the legacy cell formulas at `cells` (model sheet index, positions) to their +/// dynamic-array reading, with `@` where Excel intersects. Runs once names and tables are loaded. +pub(crate) fn apply_legacy(wb: &mut Workbook, cells: Vec<(usize, Vec)>, functions: FunctionInfo) { + for (si, positions) in cells { + let Some(sheet) = wb.sheet(si) else { continue }; + let mut changed = Vec::new(); + for at in positions { + let Some(formula) = sheet.cell(at).and_then(|c| c.formula.as_deref()) else { continue }; + if let Some(f) = legacy(wb, si, at, formula, functions) { + changed.push((at, f)); + } + } + if changed.is_empty() { + continue; + } + let Some(sheet) = wb.sheet_mut(si) else { continue }; + for (at, f) in changed { + if let Some(cell) = sheet.cells.get_mut(at) { + cell.formula = Some(Arc::new(f)); + } + } + } +} + +/// The dynamic-array reading of a legacy formula, when it differs. +fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo) -> Option { + if formula.array.is_some() { + return None; + } + let expr = formula.expr_arc()?; + let mut legacy = Legacy::new(wb, at, functions); + let out = legacy.formula(expr.as_ref().clone(), sheet); + // Text round trip: the stored expression is exactly what the text parses to. + legacy.inserted.then(|| Formula::new(&gridcraft_formula::print(&out))) } -struct Scan<'a> { +/// Removes every `@` (and the parentheses [`at`] adds). +fn strip(e: Expr) -> Expr { + e.map(&mut |x| match x { + Expr::Unary(UnOp::At, inner) => match *inner { + Expr::Paren(p) if !atomic(&p) => *p, + other => other, + }, + other => other, + }) +} + +/// `@e`, parenthesized unless `e` prints as one operand. +fn at(e: Expr) -> Expr { + let e = if atomic(&e) { e } else { Expr::Paren(Box::new(e)) }; + Expr::Unary(UnOp::At, Box::new(e)) +} + +fn atomic(e: &Expr) -> bool { + matches!(e, Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_) | Expr::Call(..) | Expr::Paren(_) | Expr::Array(_)) +} + +struct Legacy<'a> { wb: &'a Workbook, at: CellRef, + functions: FunctionInfo, remaining: usize, - locals: Vec<(String, Shape)>, + locals: Vec<(String, Kind)>, + /// An `@` was inserted. + inserted: bool, + /// The analysis finished and covered only established legacy semantics. + certain: bool, } -impl Scan<'_> { - fn expr(&mut self, e: &Expr, sheet: usize, array_context: bool, depth: usize) -> Shape { +impl<'a> Legacy<'a> { + fn new(wb: &'a Workbook, at: CellRef, functions: FunctionInfo) -> Self { + Legacy { wb, at, functions, remaining: 4096, locals: Vec::new(), inserted: false, certain: true } + } + + /// The whole cell formula: a multi-valued result shows its top-left value. + fn formula(&mut self, e: Expr, sheet: usize) -> Expr { + let (e, kind) = self.expr(e, sheet, Ctx::Value, 0); + if kind == Kind::Array { + self.inserted = true; + at(e) + } else { + e + } + } + + fn expr(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { // Names can be cyclic, and a short chain of repeated names can expand exponentially. - // Preserve array evaluation when analysis cannot safely finish. if depth >= 64 || self.remaining == 0 { - return Shape { array: true, affected: true }; + self.certain = false; + return (e, Kind::Array); } self.remaining -= 1; + let (e, kind) = self.node(e, sheet, ctx, depth); + if ctx == Ctx::Value && kind == Kind::Ref { + self.inserted = true; + (at(e), Kind::Scalar) + } else { + (e, kind) + } + } + + fn node(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { + let inner = |wanted: Ctx| if ctx == Ctx::Array { Ctx::Array } else { wanted }; match e { - Expr::Ref(r) => Shape { array: !r.range().is_single() || matches!(r.sheet, SheetSel::Span(_, _)), affected: false }, - Expr::Array(rows) => Shape { array: rows.len() > 1 || rows.first().is_some_and(|r| r.len() > 1), affected: false }, + Expr::Ref(r) => { + let kind = if r.range().is_single() && !matches!(r.sheet, SheetSel::Span(_, _)) { Kind::Scalar } else { Kind::Ref }; + (Expr::Ref(r), kind) + } + Expr::Array(rows) => { + let kind = if rows.len() > 1 || rows.first().is_some_and(|r| r.len() > 1) { Kind::Array } else { Kind::Scalar }; + (Expr::Array(rows), kind) + } Expr::Name(n) => { - if let Some((_, shape)) = self.locals.iter().rev().find(|(key, _)| key.eq_ignore_ascii_case(n)) { - return *shape; - } - let (scope, bare) = match n.rsplit_once('!') { - Some((s, name)) => (self.wb.sheet_index(&s.trim_matches('\'').replace("''", "'")).unwrap_or(sheet), name), - None => (sheet, n.as_str()), - }; - if let Some(def) = self.wb.name(bare, scope) { - return match gridcraft_formula::parse(def.formula.trim_start_matches('=')) { - Ok(expr) => self.expr(&expr, def.scope.unwrap_or(scope), array_context, depth + 1), - Err(_) => Shape::array(), - }; - } - Shape { array: self.wb.table(bare).is_some(), affected: false } + let kind = self.name(&n, sheet, depth); + (Expr::Name(n), kind) } Expr::Struct(r) => { let table = if r.table.is_empty() { @@ -76,110 +225,198 @@ impl Scan<'_> { (Some(_), None) => true, _ => table.is_some_and(|t| t.columns.len() == 1), }; - Shape { array: !(one_row && one_col), affected: false } + (Expr::Struct(r), if one_row && one_col { Kind::Scalar } else { Kind::Ref }) + } + Expr::Paren(x) => { + let (x, kind) = self.expr(*x, sheet, ctx, depth + 1); + (Expr::Paren(Box::new(x)), kind) + } + Expr::Unary(UnOp::At, x) => { + let (x, _) = self.expr(*x, sheet, inner(Ctx::Ref), depth + 1); + (Expr::Unary(UnOp::At, Box::new(x)), Kind::Scalar) + } + // A trim reference is a reference operator, like `:`. + Expr::Unary(op @ (UnOp::Spill | UnOp::Trim(_)), x) => { + let (x, _) = self.expr(*x, sheet, inner(Ctx::Ref), depth + 1); + (Expr::Unary(op, Box::new(x)), Kind::Ref) } - Expr::Paren(x) => self.expr(x, sheet, array_context, depth + 1), Expr::Unary(op, x) => { - let child = self.expr(x, sheet, array_context, depth + 1); - match op { - UnOp::At => Shape { array: false, affected: child.affected }, - // A trim reference is a reference operator, like `:`. - UnOp::Spill | UnOp::Trim(_) => Shape { array: true, affected: child.affected }, - _ => Shape { array: child.array, affected: child.affected || (child.array && !array_context) }, - } + let (x, kind) = self.expr(*x, sheet, inner(Ctx::Value), depth + 1); + (Expr::Unary(op, Box::new(x)), if kind == Kind::Scalar { Kind::Scalar } else { Kind::Array }) + } + Expr::Binary(op @ (BinOp::Range | BinOp::Union | BinOp::Intersect), a, b) => { + let (a, _) = self.expr(*a, sheet, inner(Ctx::Ref), depth + 1); + let (b, _) = self.expr(*b, sheet, inner(Ctx::Ref), depth + 1); + (Expr::Binary(op, Box::new(a), Box::new(b)), Kind::Ref) } Expr::Binary(op, a, b) => { - let a = self.expr(a, sheet, array_context, depth + 1); - let b = self.expr(b, sheet, array_context, depth + 1); - let reference = matches!(op, BinOp::Range | BinOp::Union | BinOp::Intersect); - let array = reference || a.array || b.array; - Shape { array, affected: a.affected || b.affected || (!reference && array && !array_context) } + let (a, ka) = self.expr(*a, sheet, inner(Ctx::Value), depth + 1); + let (b, kb) = self.expr(*b, sheet, inner(Ctx::Value), depth + 1); + let kind = if ka == Kind::Scalar && kb == Kind::Scalar { Kind::Scalar } else { Kind::Array }; + (Expr::Binary(op, Box::new(a), Box::new(b)), kind) + } + Expr::Call(name, args) => self.call(name, args, sheet, ctx, depth + 1), + Expr::Invoke(f, args) => { + self.certain = false; + (Expr::Invoke(f, args), Kind::Array) } - Expr::Call(name, args) => self.call(name, args, sheet, array_context, depth + 1), - Expr::Invoke(_, _) => Shape { array: true, affected: false }, - _ => Shape::default(), + other => (other, Kind::Scalar), } } - fn call(&mut self, name: &str, args: &[Expr], sheet: usize, array_context: bool, depth: usize) -> Shape { - if name == "LET" - && args.len() >= 3 - && let Some((last, bindings)) = args.split_last() + fn name(&mut self, n: &str, sheet: usize, depth: usize) -> Kind { + if let Some((_, kind)) = self.locals.iter().rev().find(|(key, _)| key.eq_ignore_ascii_case(n)) { + return *kind; + } + let (scope, bare) = match n.rsplit_once('!') { + Some((s, name)) => (self.wb.sheet_index(&s.trim_matches('\'').replace("''", "'")).unwrap_or(sheet), name), + None => (sheet, n), + }; + if let Some(def) = self.wb.name(bare, scope) { + let Ok(expr) = gridcraft_formula::parse(def.formula.trim_start_matches('=')) else { return Kind::Array }; + // A name's own formula does not see the formula's LET variables. + let locals = std::mem::take(&mut self.locals); + let (_, kind) = self.expr(expr, def.scope.unwrap_or(scope), Ctx::Array, depth + 1); + self.locals = locals; + return kind; + } + if self.wb.table(bare).is_some() { Kind::Ref } else { Kind::Scalar } + } + + fn call(&mut self, name: String, args: Vec, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { + if name == "LET" && args.len() >= 3 { + return self.let_(args, sheet, ctx, depth); + } + let lambda_name = !(self.functions.is_builtin)(&name) && !host_function(&name) && self.wb.name(&name, sheet).is_some(); + if args.len() > 255 + || lambda_name + || matches!(name.as_str(), "LAMBDA" | "MAP" | "REDUCE" | "SCAN" | "BYROW" | "BYCOL" | "MAKEARRAY" | "ISOMITTED") { - let saved = self.locals.len(); - let mut affected = false; - for pair in bindings.as_chunks::<2>().0 { - if let [Expr::Name(n), value] = pair { - let shape = self.expr(value, sheet, array_context, depth); - affected |= shape.affected; - self.locals.push((n.clone(), shape)); - } - } - let mut result = self.expr(last, sheet, array_context, depth); - result.affected |= affected; - self.locals.truncate(saved); - return result; + self.certain = false; + return (Expr::Call(name, args), Kind::Array); } - let legacy_array = - matches!(name, "SUMPRODUCT" | "MMULT" | "MINVERSE" | "MDETERM" | "TRANSPOSE" | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH"); - let mut affected = false; let mut lifted = false; - let mut shapes = Vec::with_capacity(args.len().min(256)); - if args.len() > 255 { - return Shape { array: true, affected: true }; - } - for (i, arg) in args.iter().enumerate() { - let context = array_context || legacy_array || (name == "INDEX" && i == 0); - let shape = self.expr(arg, sheet, context, depth); - affected |= shape.affected; - if shape.array && scalar_arg(name, i) { - lifted = true; - affected |= !context; - } - shapes.push(shape); - } - let first_array = shapes.first().is_some_and(|s| s.array); - let array = match name { - "INDIRECT" => match args.first() { - Some(Expr::Text(text)) if !matches!(args.get(1), Some(Expr::Bool(false))) => { - gridcraft_formula::parse(text).map(|e| self.expr(&e, sheet, array_context, depth).array).unwrap_or(true) + let mut kinds = Vec::with_capacity(args.len()); + let mut out = Vec::with_capacity(args.len()); + for (i, arg) in args.into_iter().enumerate() { + let param = param(&name, i, self.functions); + let arg_ctx = match param { + Param::Value => Ctx::Value, + Param::Ref | Param::First => Ctx::Ref, + Param::Pass => ctx, + Param::Array => Ctx::Array, + Param::Uncertain => { + self.certain = false; + Ctx::Array } - _ => true, + }; + let arg_ctx = if ctx == Ctx::Array { Ctx::Array } else { arg_ctx }; + let (arg, kind) = self.expr(arg, sheet, arg_ctx, depth); + // A value parameter given several values evaluates the function once per value. + lifted |= match param { + Param::Value => kind == Kind::Array || (kind == Kind::Ref && arg_ctx == Ctx::Array), + Param::First => kind != Kind::Scalar, + _ => false, + }; + kinds.push(kind); + out.push(arg); + } + let first = kinds.first().copied().unwrap_or(Kind::Scalar); + let kind = match name.as_str() { + "IF" | "CHOOSE" if !lifted => kinds.iter().skip(1).fold(Kind::Scalar, |k, x| k.join(*x)), + "ROW" | "COLUMN" => { + if first == Kind::Scalar { + Kind::Scalar + } else if ctx == Ctx::Array { + Kind::Array + } else { + // Outside array evaluation, ROW and COLUMN of a range give its first row or column. + self.inserted = true; + return (at(Expr::Call(name, out)), Kind::Scalar); + } + } + "INDIRECT" => match out.first() { + Some(Expr::Text(text)) if !matches!(out.get(1), Some(Expr::Bool(false))) => match gridcraft_formula::parse(text) { + Ok(e) => { + let (_, kind) = self.expr(e, sheet, Ctx::Array, depth); + if kind == Kind::Scalar { Kind::Scalar } else { Kind::Ref } + } + Err(_) => Kind::Ref, + }, + _ => Kind::Ref, }, "OFFSET" => { - // Omitted dimensions retain the source reference's shape; unknown dimensions - // might become multiple cells on a later calculation. - if args.len() <= 3 { first_array } else { !args.get(3).is_some_and(one) || args.get(4).map_or(first_array, |e| !one(e)) } + // Omitted dimensions keep the source reference's shape; unknown dimensions might + // become several cells on a later calculation. + let first_multi = first != Kind::Scalar; + let multi = if out.len() <= 3 { first_multi } else { !out.get(3).is_some_and(one) || out.get(4).map_or(first_multi, |e| !one(e)) }; + if lifted { + Kind::Array + } else if multi { + Kind::Ref + } else { + Kind::Scalar + } } "INDEX" => { - let row = args.get(1); - let col = args.get(2); - !row.is_some_and(positive) || col.is_some_and(|e| !positive(e)) || (col.is_none() && !args.first().is_some_and(single_column)) - } - "ROW" | "COLUMN" => { - affected |= first_array && !array_context; - first_array - } - "IF" | "IFERROR" | "IFNA" | "IFS" | "SWITCH" | "CHOOSE" => shapes.iter().any(|s| s.array), - "XLOOKUP" => { - lifted - || match (args.get(1), args.get(2)) { - (Some(Expr::Ref(lookup)), Some(Expr::Ref(result))) => { - if lookup.range().width() == 1 { - result.range().width() > 1 - } else { - result.range().height() > 1 - } - } - _ => true, - } + let row = out.get(1); + let col = out.get(2); + let multi = !row.is_some_and(positive) || col.is_some_and(|e| !positive(e)) || (col.is_none() && !out.first().is_some_and(one_line)); + if multi { + if first == Kind::Array { Kind::Array } else { Kind::Ref } + } else if lifted { + Kind::Array + } else { + Kind::Scalar + } } + "XLOOKUP" if !lifted => match (out.get(1), out.get(2)) { + (Some(Expr::Ref(lookup)), Some(Expr::Ref(result))) => { + let multi = if lookup.range().width() == 1 { result.range().width() > 1 } else { result.range().height() > 1 }; + if multi { Kind::Ref } else { Kind::Scalar } + } + _ => Kind::Ref, + }, + "ANCHORARRAY" => Kind::Ref, "FILTER" | "SORT" | "SORTBY" | "UNIQUE" | "SEQUENCE" | "RANDARRAY" | "VSTACK" | "HSTACK" | "TOROW" | "TOCOL" | "WRAPROWS" | "WRAPCOLS" | "TAKE" | "DROP" | "CHOOSEROWS" | "CHOOSECOLS" | "EXPAND" | "GROUPBY" | "PIVOTBY" | "TRANSPOSE" | "MMULT" | "MINVERSE" - | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH" | "MAP" | "SCAN" | "BYROW" | "BYCOL" | "MAKEARRAY" | "ANCHORARRAY" => true, - _ => lifted || self.wb.name(name, sheet).is_some(), + | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH" => Kind::Array, + // A user-defined function may return a range or an array. + n if user_function(n, self.functions) => Kind::Array, + _ if lifted => Kind::Array, + _ => Kind::Scalar, }; - Shape { array, affected } + (Expr::Call(name, out), kind) + } + + fn let_(&mut self, args: Vec, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { + let saved = self.locals.len(); + let count = args.len(); + let mut out = Vec::with_capacity(count); + let mut pending: Option = None; + let mut kind = Kind::Scalar; + for (i, arg) in args.into_iter().enumerate() { + if i + 1 == count { + let (body, k) = self.expr(arg, sheet, ctx, depth); + out.push(body); + kind = k; + } else if i % 2 == 0 { + pending = match &arg { + Expr::Name(n) => Some(n.clone()), + _ => None, + }; + out.push(arg); + } else { + let value_ctx = if ctx == Ctx::Array { Ctx::Array } else { Ctx::Ref }; + let (value, k) = self.expr(arg, sheet, value_ctx, depth); + if let Some(n) = pending.take() { + self.locals.push((n, k)); + } + out.push(value); + } + } + self.locals.truncate(saved); + (Expr::Call("LET".into(), out), kind) } } @@ -191,12 +428,90 @@ fn one(e: &Expr) -> bool { matches!(e, Expr::Number(n) if *n == 1.0) } -fn single_column(e: &Expr) -> bool { - matches!(e, Expr::Ref(r) if r.range().width() == 1) +/// A one-column or one-row reference: INDEX with a single index picks one cell of it. +fn one_line(e: &Expr) -> bool { + matches!(e, Expr::Ref(r) if r.range().width() == 1 || r.range().height() == 1) +} + +/// Functions the calculation engine evaluates itself, whose parameters are described here +/// rather than by the function library's lifting metadata. +fn host_function(name: &str) -> bool { + matches!( + name, + "IF" | "IFS" + | "IFERROR" + | "IFNA" + | "CHOOSE" + | "SWITCH" + | "ROW" + | "COLUMN" + | "ROWS" + | "COLUMNS" + | "AREAS" + | "ISREF" + | "ISFORMULA" + | "FORMULATEXT" + | "SHEET" + | "SHEETS" + | "OFFSET" + | "INDIRECT" + | "INDEX" + | "CELL" + | "TRIMRANGE" + | "SUBTOTAL" + | "AGGREGATE" + | "TEXT" + | "LET" + | "LAMBDA" + | "ISOMITTED" + | "MAP" + | "REDUCE" + | "SCAN" + | "BYROW" + | "BYCOL" + | "MAKEARRAY" + | "ANCHORARRAY" + | "GETPIVOTDATA" + ) +} + +/// Not a built-in worksheet function: an add-in or VBA function. +fn user_function(name: &str, functions: FunctionInfo) -> bool { + !host_function(name) && !(functions.is_builtin)(name) +} + +fn param(name: &str, i: usize, functions: FunctionInfo) -> Param { + match name { + "IF" | "CHOOSE" => { + if i == 0 { + Param::Value + } else { + Param::Pass + } + } + "SUMPRODUCT" | "MMULT" | "MINVERSE" | "MDETERM" | "TRANSPOSE" | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH" => Param::Array, + "INDEX" if i == 0 => Param::Array, + // LOOKUP's vectors and AGGREGATE's array form evaluate their arguments as arrays. + "LOOKUP" if i > 0 => Param::Array, + "AGGREGATE" if i == 2 => Param::Array, + "ROW" | "COLUMN" | "ROWS" | "COLUMNS" | "AREAS" | "ISREF" | "ISFORMULA" | "FORMULATEXT" | "SHEET" | "SHEETS" | "TRIMRANGE" + | "ANCHORARRAY" => Param::Ref, + "CELL" | "GETPIVOTDATA" if i == 1 => Param::Ref, + "T" => Param::First, + "FILTER" | "SORT" | "SORTBY" | "UNIQUE" | "VSTACK" | "HSTACK" | "TOROW" | "TOCOL" | "WRAPROWS" | "WRAPCOLS" | "TAKE" | "DROP" + | "CHOOSEROWS" | "CHOOSECOLS" | "EXPAND" | "GROUPBY" | "PIVOTBY" + if !scalar_arg(name, i) => + { + Param::Uncertain + } + n if user_function(n, functions) => Param::Ref, + n if scalar_arg(n, i) && (host_function(n) || (functions.is_scalar_arg)(n, i)) => Param::Value, + _ => Param::Ref, + } } -/// Legacy reference/array-taking parameters. Other parameters consume a single value. -/// This is file-format policy, not a second evaluator: unknown results are never calculated. +/// Legacy reference/array-taking parameters. Other parameters consume a single value; the +/// function library's lifting metadata refines this for the functions it implements. fn scalar_arg(name: &str, i: usize) -> bool { match name { "SUM" | "AVERAGE" | "AVERAGEA" | "MIN" | "MINA" | "MAX" | "MAXA" | "COUNT" | "COUNTA" | "COUNTBLANK" | "PRODUCT" | "SUMSQ" | "MEDIAN" diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index ef263873e2..8ba4b18866 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -80,8 +80,14 @@ fn expr_to_file(e: Expr) -> String { // reference that became `#REF!` (its cell was deleted) as plain `#REF!`. Expr::Unary(gridcraft_formula::UnOp::Spill, r) if matches!(*r, Expr::Error(_)) => *r, Expr::Unary(gridcraft_formula::UnOp::Spill, r) => Expr::Call("_xlfn.ANCHORARRAY".into(), vec![*r]), - // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`. - Expr::Unary(gridcraft_formula::UnOp::At, x) => Expr::Call("_xlfn.SINGLE".into(), vec![*x]), + // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`, and `@(x)` likewise. + Expr::Unary(gridcraft_formula::UnOp::At, x) => Expr::Call( + "_xlfn.SINGLE".into(), + vec![match *x { + Expr::Paren(inner) => *inner, + other => other, + }], + ), // Nor the `[@Col]` shorthand: files spell it `[[#This Row],[Col]]`, or Excel repairs // the file and drops the table. Carried as a name, which prints verbatim. Expr::Struct(st) => Expr::Name(gridcraft_formula::printer::struct_ref_file(&st)), diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 3300f97fe5..2eb30c545e 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -79,10 +79,40 @@ impl ReadReport { } } +/// What reading and writing formulas needs to know about worksheet functions. The function +/// library sits beside this crate (format crates depend only on core, formula and model), so the +/// caller supplies its answers; the engine passes the library's. +/// +/// It decides how legacy formulas (saved without dynamic-array metadata) are read with Excel's +/// implicit `@`, and which formulas are saved with dynamic-array metadata. +#[derive(Clone, Copy, Debug)] +pub struct FunctionInfo { + /// Whether `name` (upper case, without `_xlfn.`) is a built-in worksheet function rather than + /// an add-in, VBA or LAMBDA function. + pub is_builtin: fn(&str) -> bool, + /// Whether parameter `i` of the built-in function `name` takes a single value, as opposed to + /// a reference or array taken as a whole. + pub is_scalar_arg: fn(&str, usize) -> bool, +} + +impl Default for FunctionInfo { + /// Without the function library: every name counts as built in, and this crate's table of + /// reference- and array-taking parameters alone decides parameter types. + fn default() -> Self { + FunctionInfo { is_builtin: |_| true, is_scalar_arg: |_, _| true } + } +} + /// Reads an `.xlsx` / `.xlsm` / `.xltx` / `.xltm` package (the workbook part is found through the -/// package relationships, so every main-part content type is accepted). +/// package relationships, so every main-part content type is accepted), with the default +/// [`FunctionInfo`]. pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { - read::read_xlsx(bytes) + read::read_xlsx(bytes, FunctionInfo::default()) +} + +/// [`read_xlsx`] with the function library's facts. +pub fn read_xlsx_with(bytes: &[u8], functions: FunctionInfo) -> Result<(Workbook, ReadReport), IoError> { + read::read_xlsx(bytes, functions) } /// Which member of the SpreadsheetML family a package is saved as. Only the content type of the @@ -128,14 +158,21 @@ impl XlsxKind { } } -/// Writes a workbook as an `.xlsx` package, or as an `.xlsm` one when it holds a VBA project. +/// Writes a workbook as an `.xlsx` package, or as an `.xlsm` one when it holds a VBA project, +/// with the default [`FunctionInfo`]. pub fn write_xlsx(wb: &Workbook) -> Result, IoError> { - write::write_xlsx(wb, if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook }) + let kind = if wb.vba_project.is_some() { XlsxKind::MacroWorkbook } else { XlsxKind::Workbook }; + write::write_xlsx(wb, kind, FunctionInfo::default()) } -/// Writes a workbook as the given member of the `.xlsx` family. +/// Writes a workbook as the given member of the `.xlsx` family, with the default [`FunctionInfo`]. pub fn write_xlsx_as(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { - write::write_xlsx(wb, kind) + write::write_xlsx(wb, kind, FunctionInfo::default()) +} + +/// [`write_xlsx_as`] with the function library's facts. +pub fn write_xlsx_with(wb: &Workbook, kind: XlsxKind, functions: FunctionInfo) -> Result, IoError> { + write::write_xlsx(wb, kind, functions) } /// CSV import options. diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 1a479081c2..3b1c20a826 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -30,6 +30,9 @@ pub struct Ctx<'a> { pub cell_pictures: Vec>>, /// x14 conditional-format ids of the current sheet's data bars, with the index of the rule in `cond_formats`. pub cf_ext_ids: Vec<(String, usize)>, + /// Cells of the worksheet being read whose formulas lack dynamic-array metadata (legacy + /// formulas, evaluated with implicit intersection), collected per sheet. + pub legacy_formulas: Vec, } impl Ctx<'_> { @@ -66,7 +69,7 @@ pub fn find_rel<'r>(rels: &'r [Rel], kind: &str) -> Option<&'r Rel> { rels.iter().find(|r| r.kind == kind) } -pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { +pub fn read_xlsx(bytes: &[u8], functions: crate::FunctionInfo) -> Result<(Workbook, ReadReport), IoError> { let pkg = Package::open(bytes)?; let mut cx = Ctx { pkg, @@ -82,6 +85,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { num_fmts: Default::default(), cell_pictures: vec![], cf_ext_ids: vec![], + legacy_formulas: vec![], }; let root_rels = cx.pkg.rels("")?; let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into()); @@ -198,6 +202,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { // Sheets. `file_to_model[i]` maps the i-th to a model sheet index. let mut file_to_model: Vec> = vec![]; + // Legacy formula cells per model sheet, rewritten once names and tables are known. + let mut legacy_formulas: Vec<(usize, Vec)> = vec![]; let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels); let sheet_els: Vec = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default(); for (i, se) in sheet_els.iter().enumerate() { @@ -219,14 +225,17 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { continue; } let name = unique_name(&wb, &name, i); + cx.legacy_formulas.clear(); let mut sheet = match crate::sheet_read::read_sheet(&mut cx, &rel.target, &name) { Ok(s) => s, Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), Err(e) => { cx.warn(format!("sheet \"{name}\" could not be read: {e}")); + cx.legacy_formulas.clear(); Sheet::new(name.clone()) } }; + legacy_formulas.push((wb.sheets.len(), std::mem::take(&mut cx.legacy_formulas))); match crate::pivot::read_pivots(&mut cx, &mut pivot_caches, &rel.target, &name) { Ok(p) => sheet.pivots = p, Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), @@ -342,6 +351,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { wb.preserved = kept.workbook(&mut cx, &wb_part, &wb_xml, &file_to_model); // Calls of LAMBDA names are spelled like the names (the parser upper-cases them). wb.apply_name_call_case(); + // Legacy formulas read as dynamic-array formulas with Excel's implicit `@`. + crate::array_formula::apply_legacy(&mut wb, legacy_formulas, functions); wb.styles = cx.styles; Ok((wb, cx.report)) } diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0194d22688..af74253525 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -452,6 +452,11 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos let dynamic = c.attr("cm").is_some(); let formula = c.child("f").and_then(|f| read_formula(cx, st, f, pos, dynamic)); let value = if formula.is_none() && st.dynamic.iter().any(|r| r.contains(pos) && r.start != pos) { Value::Empty } else { value }; + // A formula without dynamic-array metadata is a legacy formula, unless entered as a + // Ctrl+Shift+Enter array. + if !dynamic && formula.as_ref().is_some_and(|f| f.array.is_none() && f.expr_arc().is_some()) { + cx.legacy_formulas.push(pos); + } sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style }); } diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 78e1afaaef..48c64cd35e 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -5,8 +5,8 @@ use std::fmt::Write as _; use gridcraft_core::{CellError, CellRef, RangeRef, Value}; use gridcraft_model::{ - Cell, CfOperator, CfRule, CfValueKind, Color, CondFormat, ErrorStyle, FilterCriterion, LineInfo, Orientation, Sheet, SparklineKind, Style, Table, - TotalsFn, Validation, ValidationKind, Workbook, default_icon_thresholds, icon_count, + Cell, CfOperator, CfRule, CfValueKind, Color, CondFormat, ErrorStyle, FilterCriterion, Formula, LineInfo, Orientation, Sheet, SparklineKind, + Style, Table, TotalsFn, Validation, ValidationKind, Workbook, default_icon_thresholds, icon_count, }; use crate::drawing::{Obj, image_content_type, image_ext}; @@ -296,13 +296,25 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( } s.push('>'); for c in cells { - let cell = sheet.cells.get(*c); + let mut cell = sheet.cells.get(*c); let ov = overrides.get(c); let ex = extra.get(c); + let mut legacy_cell = None; let array = dynamic.get(c).copied().or_else(|| { - let f = cell?.formula.as_ref()?; - (f.array.is_none() && crate::array_formula::needs_array(wb, si, *c, f)).then_some(RangeRef::cell(*c)) + let f = cell?.formula.as_ref().filter(|f| f.array.is_none())?; + match crate::array_formula::export(wb, si, *c, f, out.functions) { + crate::array_formula::Export::Unchanged => None, + crate::array_formula::Export::Dynamic => Some(RangeRef::cell(*c)), + // Every `@` is one Excel implies in a legacy formula: write it without them. + crate::array_formula::Export::Legacy(e) => { + legacy_cell = cell.map(|x| Cell { formula: Some(std::sync::Arc::new(Formula::from_expr(e))), ..x.clone() }); + None + } + } }); + if legacy_cell.is_some() { + cell = legacy_cell.as_ref(); + } write_cell(&mut s, *c, cell, sheet.cell_pictures.get(c), ov, ex, array.as_ref(), &sid, out); } s.push_str(""); diff --git a/crates/xlsx/src/tests/array_export.rs b/crates/xlsx/src/tests/array_export.rs index b90b98668e..7f5f54ab2c 100644 --- a/crates/xlsx/src/tests/array_export.rs +++ b/crates/xlsx/src/tests/array_export.rs @@ -292,11 +292,13 @@ fn implicit_intersection_metadata_respects_function_argument_context() { ("SUM(A1:A3)", false), ("SUMPRODUCT(A1:A3*B1:B3)", false), ("SUMPRODUCT(SQRT(A1:A3))", false), - // An explicit `@` is written as `_xlfn.SINGLE`, a dynamic-array formula. Dropping it - // instead would need the reader to put it back on legacy formulas. - ("SQRT(@A1:A3)", true), - ("@A1:A3*2", true), + // An `@` that legacy Excel implies is dropped (the reader puts it back); any other + // `@` is written as `_xlfn.SINGLE`, which only dynamic-array formulas evaluate. + ("SQRT(@A1:A3)", false), + ("@A1:A3*2", false), ("@(A1:A3*2)", true), + ("SQRT(@A1)", true), + ("@SUM(A1:A3)", true), ("SQRT(INDIRECT(\"A1\"))", false), ("SUM(INDIRECT(\"A1:A3\"))", false), ("SQRT(INDIRECT(\"A1:A3\"))", true), diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 39ea30951b..95d2822184 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -577,3 +577,71 @@ fn user_defined_function_prefix_round_trips() { assert_eq!(cell.child("f").unwrap().text, f, "written {a}"); } } + +/// A formula saved without dynamic-array metadata is a legacy formula: Excel intersects a range +/// given where one value is expected with the formula's row or column, and shows the formula with +/// `@` there. Dynamic-array formulas (`cm`) and Ctrl+Shift+Enter arrays are read as written. +#[test] +fn legacy_formulas_read_with_implicit_intersection() { + let body = r#" + 1 + 2TANH(A1:A3)0.96TANH(A1:A3)0.76TANH(A1:A3)0.76 + 3SUM(A1:A3)6SUMPRODUCT(A1:A3*A1:A3)14 + A1:A3+Vals*2INDEX(A1:C3,0,1)IF(A1>0,A1:A3,0)SUM(IF(A1:A3>1,A1:A3)) + 456 + TANH(A5:C5)COUNTIF(A1:A3,">1")+ROWS(A1:A3)ROW(A1:A3)T(A5:C5) + "#; + let names = r#"Data!$A$1:$A$3"#; + let (wb, _) = read_xlsx(&minimal(body, &[], "", names)).unwrap(); + let s = wb.sheet(0).unwrap(); + let f = |a: &str| s.cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| (f.text.clone(), f.array)).unwrap(); + let cases = [ + ("B2", "TANH(@A1:A3)"), + ("C2", "TANH(A1:A3)"), + ("B3", "SUM(A1:A3)"), + ("E3", "SUMPRODUCT(A1:A3*A1:A3)"), + ("B4", "@A1:A3+@Vals*2"), + ("E4", "@INDEX(A1:C3,0,1)"), + ("F4", "IF(A1>0,@A1:A3,0)"), + ("G4", "SUM(IF(@A1:A3>1,A1:A3))"), + ("B7", "TANH(@A5:C5)"), + ("C7", "COUNTIF(A1:A3,\">1\")+ROWS(A1:A3)"), + ("D7", "@ROW(A1:A3)"), + // T reads a reference's top-left cell rather than intersecting it. + ("E7", "@T(A5:C5)"), + ]; + for (a, text) in cases { + assert_eq!(f(a), (text.to_string(), None), "{a}"); + } + assert_eq!(f("D2"), ("TANH(A1:A3)".to_string(), RangeRef::parse("D2:D4"))); +} + +/// The caller's function facts decide what a legacy formula means: an add-in function takes the +/// range whole and its result is intersected; a parameter the library says takes an array is not +/// intersected. Saving the intersected add-in call writes it back as the legacy formula it was. +#[test] +fn legacy_formulas_use_the_callers_function_facts() { + let body = r#" + 1 + 2MYUDF(A1:A3)TANH(A1:A3) + 3 + "#; + let bytes = minimal(body, &[], "", ""); + let library = crate::FunctionInfo { is_builtin: |n| n != "MYUDF", is_scalar_arg: |n, _| n != "TANH" }; + let text = + |wb: &gridcraft_model::Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + let (plain, _) = read_xlsx(&bytes).unwrap(); + assert_eq!(text(&plain, "B2"), "MYUDF(@A1:A3)", "without facts every function is built in"); + assert_eq!(text(&plain, "C2"), "TANH(@A1:A3)"); + let (wb, _) = crate::read_xlsx_with(&bytes, library).unwrap(); + assert_eq!(text(&wb, "B2"), "@MYUDF(A1:A3)"); + assert_eq!(text(&wb, "C2"), "TANH(A1:A3)"); + let out = crate::write_xlsx_with(&wb, crate::XlsxKind::Workbook, library).unwrap(); + let mut pkg = crate::package::Package::open(&out).unwrap(); + let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap(); + let b2 = sheet.child("sheetData").unwrap().kids("row").flat_map(|r| r.kids("c")).find(|c| c.attr("r") == Some("B2")).unwrap(); + assert_eq!(b2.attr("cm"), None); + assert_eq!(b2.child("f").map(|f| f.text.as_str()), Some("MYUDF(A1:A3)")); + let (back, _) = crate::read_xlsx_with(&out, library).unwrap(); + assert_eq!(text(&back, "B2"), "@MYUDF(A1:A3)"); +} diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 9018029051..f28bb48f64 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -859,10 +859,11 @@ fn icon_sets_always_write_one_cfvo_per_icon() { assert_eq!(rules, [3, 4, 5]); } -/// Files have no `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)` in a dynamic-array -/// formula, and reads it back as `@x`. +/// Files have no `@` operator. An `@` that legacy Excel implies is written without it in a +/// legacy formula (no dynamic-array metadata); any other `@x` is written as `_xlfn.SINGLE(x)` +/// in a dynamic-array formula. Both read back as written in the model. #[test] -fn implicit_intersection_is_written_as_single() { +fn implicit_intersection_is_written_as_legacy_or_single() { let mut wb = Workbook::new(); let s = wb.sheet_mut(0).unwrap(); for (r, n) in [(0, 1.0), (1, 3.0), (2, 5.0)] { @@ -870,16 +871,46 @@ fn implicit_intersection_is_written_as_single() { } s.cells.set(at("D3"), Cell { value: Value::Number(10.0), ..Cell::formula(Formula::new("@A1:A3*2")) }); s.cells.set(at("D4"), Cell { value: Value::Number(2.0), ..Cell::formula(Formula::new("A1*2")) }); + s.cells.set(at("D5"), Cell { value: Value::Number(2.0), ..Cell::formula(Formula::new("@(A1:A3*2)")) }); let bytes = write_xlsx(&wb).unwrap(); let (xml, metadata) = sheet1_xml(&bytes); - assert!(xml.contains("_xlfn.SINGLE(A1:A3)*210"), "{xml}"); + assert!(xml.contains("A1:A3*210"), "{xml}"); assert!(xml.contains("A1*2"), "{xml}"); + assert!(xml.contains("_xlfn.SINGLE(A1:A3*2)2"), "{xml}"); assert!(!xml.contains('@'), "{xml}"); assert!(metadata); let (back, _) = read_xlsx(&bytes).unwrap(); let sh = back.sheet(0).unwrap(); - assert_eq!(sh.cell(at("D3")).and_then(|c| c.formula.as_ref()).map(|f| f.text.as_str()), Some("@A1:A3*2")); - assert_eq!(sh.cell(at("D3")).and_then(|c| c.formula.as_ref()).and_then(|f| f.array), None); + let text = |a: &str| sh.cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()); + assert_eq!(text("D3").as_deref(), Some("@A1:A3*2")); + assert_eq!(text("D4").as_deref(), Some("A1*2")); + assert_eq!(text("D5").as_deref(), Some("@(A1:A3*2)")); + assert_eq!(sh.cell(at("D5")).and_then(|c| c.formula.as_ref()).and_then(|f| f.array), None); +} + +/// A legacy formula read from a file (shown with Excel's implicit `@`) is saved as it was read, +/// without dynamic-array metadata; a dynamic-array formula keeps its metadata. +#[test] +fn legacy_and_dynamic_formulas_keep_their_kind() { + let body = r#" + 1 + 2TANH(A1:A3)+A1:A34TANH(A1:A3)0.76TANH(A1:A3)0.76 + 3SUM(A1:A3)6 + "#; + let (wb, _) = read_xlsx(&super::minimal(body, &[], "", "")).unwrap(); + let text = |wb: &Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| (f.text.clone(), f.array)).unwrap(); + assert_eq!(text(&wb, "B2"), ("TANH(@A1:A3)+@A1:A3".to_string(), None)); + let bytes = write_xlsx(&wb).unwrap(); + let (xml, _) = sheet1_xml(&bytes); + assert!(xml.contains("TANH(A1:A3)+A1:A3"), "{xml}"); + assert!(xml.contains("SUM(A1:A3)"), "{xml}"); + // Uncalculated, the spill range is not known yet; the formula stays dynamic. + assert!(xml.contains("TANH(A1:A3)"), "{xml}"); + assert!(xml.contains("TANH(A1:A3)"), "{xml}"); + let (back, _) = read_xlsx(&bytes).unwrap(); + for a in ["B2", "B3", "C2", "D2"] { + assert_eq!(text(&back, a), text(&wb, a), "{a}"); + } } #[test] diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 06761f01d2..6ba8321d8e 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -9,7 +9,7 @@ use gridcraft_model::{CalcMode, CalcSettings, Style, Visibility, Workbook}; use crate::package::ZipOut; use crate::xml::{esc, esc_attr}; -use crate::{IoError, XlsxKind}; +use crate::{FunctionInfo, IoError, XlsxKind}; pub const NS_MAIN: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; pub const NS_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; @@ -126,6 +126,8 @@ pub struct Out { pub cell_pictures: crate::richdata::PicturesOut, /// Kept (pass-through) parts written so far. pub kept: crate::passthrough::KeptOut, + /// Decides which formulas need dynamic-array metadata. + pub functions: FunctionInfo, } impl Out { @@ -185,7 +187,7 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> { Ok(()) } -pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { +pub fn write_xlsx(wb: &Workbook, kind: XlsxKind, functions: FunctionInfo) -> Result, IoError> { if wb.sheets.is_empty() { return Err(IoError::Format("a workbook needs at least one sheet".into())); } @@ -211,6 +213,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { needs_calc: false, cell_pictures: Default::default(), kept: Default::default(), + functions, }; out.default_type("rels", "application/vnd.openxmlformats-package.relationships+xml"); out.default_type("xml", "application/xml"); diff --git a/docs/decisions.md b/docs/decisions.md index 7b0a99a384..58388bf2ea 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -17,9 +17,9 @@ GridCraft evaluates ordinary formulas with array semantics even when the final r The exporter inspects the parsed formula without evaluating it. It distinguishes range-taking functions such as `SUM` from scalar arguments and operators: `SUM(A1:A3)` and `A1*2` stay ordinary, while `SUM(A1:A3*B1:B3)` and `SQRT(A1:A3)` retain array evaluation. Legacy array-aware contexts such as `SUMPRODUCT` do not need an extra marker. Explicit `@` scalarizes its result without hiding array-sensitive operations inside it. -Names are resolved using workbook/sheet scope, and structured references distinguish one table-row cell from a column. Literal `INDIRECT` and `INDEX` arguments permit tighter classification; unresolved reference dimensions are conservatively treated as potentially multiple cells. Name/AST traversal is bounded, with array preservation as the fallback. This is an export classifier, not a claim of exact Excel metadata parity for every function or user-defined function. It stays within the format crate's existing dependencies and does not change calculation or import behavior. +Names are resolved using workbook/sheet scope, and structured references distinguish one table-row cell from a column. Literal `INDIRECT` and `INDEX` arguments permit tighter classification; unresolved reference dimensions are conservatively treated as potentially multiple cells. Name/AST traversal is bounded, with array preservation as the fallback. This is an export classifier, not a claim of exact Excel metadata parity for every function or user-defined function. It stays within the format crate's existing dependencies. -This is a writer policy; interpreting implicit intersection in imported legacy formulas remains separate work. See Microsoft's [Formula vs. Formula2 documentation](https://learn.microsoft.com/en-us/office/vba/excel/concepts/cells-and-ranges/range-formula-vs-formula2). +The reader applies the same classification in reverse: a formula without dynamic-array metadata (`cm`) and not entered as a CSE array is a legacy formula, and gets the `@` Excel implies where a range meets a single-value parameter, an operator or the cell result. The writer drops an `@` that legacy Excel would imply and saves that formula without `cm`; any other `@` stays `_xlfn.SINGLE` in a dynamic-array formula. Which names are built-in functions and which parameters take a single value comes from the function library, which the format crate may not depend on: the caller passes a `gridcraft_xlsx::FunctionInfo` (`read_xlsx_with`, `write_xlsx_with`; the engine supplies the library's answers), and `read_xlsx`/`write_xlsx`/`write_xlsx_as` use the crate's own table alone. See Microsoft's [Formula vs. Formula2 documentation](https://learn.microsoft.com/en-us/office/vba/excel/concepts/cells-and-ranges/range-formula-vs-formula2). ## Static cell pictures diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9884724146..43ae0c0016 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** trivial (XLSX chart sheets are kept on save (#727); previously minor: CSV save keeps the separator it was opened with) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (legacy vs dynamic-array formulas: `cm` metadata read and written) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -22,7 +22,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. Formulas without dynamic-array metadata (`cm`) are legacy formulas and open with Excel's implicit `@`; on save, a formula whose every `@` is implied is written without them and without `cm`, any other formula that legacy Excel would intersect gets dynamic-array metadata (`_xlfn.SINGLE` for an explicit `@`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Legacy vs dynamic-array formulas: no `cm` reads as legacy (implicit `@` inserted), implied `@` written back without `cm` | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..a550436ea9 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (legacy formulas from files evaluate with implicit intersection) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -76,7 +76,7 @@ PIVOTBY, REGEXTEST…) are all present. | Structured references (`Table1[Col]`, `[#Totals]`, `@`; the unbracketed `[[#This Row],Col]` some writers emit) | done | | Defined names (workbook and sheet scope), Create from Selection | done | | Dynamic arrays, spill, `#SPILL!`, spill operator `A1#` | done; stale-spill bugs (#133, #139; PRs #148, #157) | -| Implicit intersection `@`, legacy CSE array formulas | done; legacy array range fill (PR #156) | +| Implicit intersection `@`, legacy CSE array formulas | done; legacy array range fill (PR #156). Formulas saved without dynamic-array metadata (pre-dynamic-array Excel, or no `@` needed) open with Excel's implicit `@` inserted where a range meets a single-value parameter, operator or the cell result, and calculate like Excel's cached values (cells differing from Excel's cached value: FormulaEvalTestData 205 → 11, StructuredReferences 2 → 0). T reads a reference's top-left cell | | Trim references `A1:.E10` (trailing), `A1.:E10` (leading), `A1.:.E10` (both), also on whole rows/columns (`A:.A`) | done; evaluated as `TRIMRANGE(range, code, code)`, adjusted on insert/delete; files store `_xlfn.TRIMRANGE(range,code,code)` (Excel's own file spelling unconfirmed in public docs), `_xlfn._TRO_ALL/_TRO_LEADING/_TRO_TRAILING(...)` read too | | LET, LAMBDA, named LAMBDAs, ISOMITTED, MAP/REDUCE/SCAN/BYROW/BYCOL/MAKEARRAY | done | | Iterative calculation for circular references | done: with Enable Iterative Calculation on (`formulas.calculationOptions` `{iterative, maxIterations, maxChange}`, saved as ``), loops are evaluated again from their previous values (blank = 0) until no cell on a loop changes by Maximum Change or Maximum Iterations is reached; off, cycles give `#CIRC!`. Differences: no Options dialog yet (command only); GridCraft recalculates on open, so a loop that never settles (`=A1+1`) advances again each time the file is opened | @@ -108,6 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Legacy formulas from files (no dynamic-array metadata) evaluate with implicit intersection: cells differing from Excel's cached values 645 → 255 across 40 test workbooks | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From abe3fc3233b717911555a188fcfe93a41777d505 Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:56:25 -0400 Subject: [PATCH 02/13] XLSX: long operator chains analysed in full and unfinished legacy analysis leaves the formula unchanged (never saved as SINGLE); @ of a union keeps its parentheses; IF's condition intersected inside SUMPRODUCT --- crates/xlsx/src/array_formula.rs | 102 +++++++++++++++++++++-------- crates/xlsx/src/fmla.rs | 5 +- crates/xlsx/src/tests/fixtures.rs | 16 +++++ crates/xlsx/src/tests/roundtrip.rs | 52 +++++++++++++++ 4 files changed, 146 insertions(+), 29 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index 254755415b..4cafee34b9 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -58,6 +58,10 @@ enum Ctx { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Param { Value, + /// IF's condition: one value even inside array evaluation. Legacy Excel's IF does not + /// evaluate its condition as an array inside SUMPRODUCT unless the formula is a + /// Ctrl+Shift+Enter array, which this analysis never sees. + Condition, Ref, Array, /// The parameter is evaluated like the call itself (IF's and CHOOSE's results). @@ -94,7 +98,10 @@ pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula if !explicit { return if legacy.inserted { Export::Dynamic } else { Export::Unchanged }; } - if gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } + // The text written is `plain` printed: it must read back as `plain` (the printer writes + // only the parentheses the expression has). + let reparses = gridcraft_formula::parse(&gridcraft_formula::print(&plain)).is_ok_and(|e| e == plain); + if reparses && gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } } /// Rewrites the legacy cell formulas at `cells` (model sheet index, positions) to their @@ -129,15 +136,17 @@ fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions let expr = formula.expr_arc()?; let mut legacy = Legacy::new(wb, at, functions); let out = legacy.formula(expr.as_ref().clone(), sheet); - // Text round trip: the stored expression is exactly what the text parses to. - legacy.inserted.then(|| Formula::new(&gridcraft_formula::print(&out))) + // Text round trip: the stored expression is exactly what the text parses to. An analysis + // that stopped early leaves the formula as it was read. + (legacy.inserted && legacy.certain).then(|| Formula::new(&gridcraft_formula::print(&out))) } -/// Removes every `@` (and the parentheses [`at`] adds). +/// Removes every `@` (and the parentheses [`at`] adds; a union keeps them, as its comma would +/// otherwise separate function arguments or fail to parse). fn strip(e: Expr) -> Expr { e.map(&mut |x| match x { Expr::Unary(UnOp::At, inner) => match *inner { - Expr::Paren(p) if !atomic(&p) => *p, + Expr::Paren(p) if !atomic(&p) && !matches!(*p, Expr::Binary(BinOp::Union, ..)) => *p, other => other, }, other => other, @@ -174,7 +183,7 @@ impl<'a> Legacy<'a> { /// The whole cell formula: a multi-valued result shows its top-left value. fn formula(&mut self, e: Expr, sheet: usize) -> Expr { let (e, kind) = self.expr(e, sheet, Ctx::Value, 0); - if kind == Kind::Array { + if kind == Kind::Array && self.certain { self.inserted = true; at(e) } else { @@ -184,6 +193,7 @@ impl<'a> Legacy<'a> { fn expr(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { // Names can be cyclic, and a short chain of repeated names can expand exponentially. + // Operator chains do not count towards the depth (see [`Legacy::binary`]). if depth >= 64 || self.remaining == 0 { self.certain = false; return (e, Kind::Array); @@ -244,17 +254,7 @@ impl<'a> Legacy<'a> { let (x, kind) = self.expr(*x, sheet, inner(Ctx::Value), depth + 1); (Expr::Unary(op, Box::new(x)), if kind == Kind::Scalar { Kind::Scalar } else { Kind::Array }) } - Expr::Binary(op @ (BinOp::Range | BinOp::Union | BinOp::Intersect), a, b) => { - let (a, _) = self.expr(*a, sheet, inner(Ctx::Ref), depth + 1); - let (b, _) = self.expr(*b, sheet, inner(Ctx::Ref), depth + 1); - (Expr::Binary(op, Box::new(a), Box::new(b)), Kind::Ref) - } - Expr::Binary(op, a, b) => { - let (a, ka) = self.expr(*a, sheet, inner(Ctx::Value), depth + 1); - let (b, kb) = self.expr(*b, sheet, inner(Ctx::Value), depth + 1); - let kind = if ka == Kind::Scalar && kb == Kind::Scalar { Kind::Scalar } else { Kind::Array }; - (Expr::Binary(op, Box::new(a), Box::new(b)), kind) - } + Expr::Binary(..) => self.binary(e, sheet, ctx, depth), Expr::Call(name, args) => self.call(name, args, sheet, ctx, depth + 1), Expr::Invoke(f, args) => { self.certain = false; @@ -301,7 +301,7 @@ impl<'a> Legacy<'a> { for (i, arg) in args.into_iter().enumerate() { let param = param(&name, i, self.functions); let arg_ctx = match param { - Param::Value => Ctx::Value, + Param::Value | Param::Condition => Ctx::Value, Param::Ref | Param::First => Ctx::Ref, Param::Pass => ctx, Param::Array => Ctx::Array, @@ -310,11 +310,11 @@ impl<'a> Legacy<'a> { Ctx::Array } }; - let arg_ctx = if ctx == Ctx::Array { Ctx::Array } else { arg_ctx }; + let arg_ctx = if ctx == Ctx::Array && param != Param::Condition { Ctx::Array } else { arg_ctx }; let (arg, kind) = self.expr(arg, sheet, arg_ctx, depth); // A value parameter given several values evaluates the function once per value. lifted |= match param { - Param::Value => kind == Kind::Array || (kind == Kind::Ref && arg_ctx == Ctx::Array), + Param::Value | Param::Condition => kind == Kind::Array || (kind == Kind::Ref && arg_ctx == Ctx::Array), Param::First => kind != Kind::Scalar, _ => false, }; @@ -389,6 +389,58 @@ impl<'a> Legacy<'a> { (Expr::Call(name, out), kind) } + /// A binary operation. `A1+A2+…+A70` parses as a left-nested chain as deep as it is long, so + /// the chain's left operands are walked iteratively, at the same depth; each operation still + /// costs one node of the budget. + fn binary(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { + let operand = |op: BinOp, node: Ctx| { + if node == Ctx::Array { + Ctx::Array + } else if matches!(op, BinOp::Range | BinOp::Union | BinOp::Intersect) { + Ctx::Ref + } else { + Ctx::Value + } + }; + // (operator, right operand, the operation's context), outermost first. + let mut spine = Vec::new(); + let mut cur = e; + let mut cur_ctx = ctx; + while let Expr::Binary(op, a, b) = cur { + if !spine.is_empty() { + // The caller's `expr` counted the outermost operation. + if self.remaining == 0 { + self.certain = false; + } else { + self.remaining -= 1; + } + } + spine.push((op, *b, cur_ctx)); + cur_ctx = operand(op, cur_ctx); + cur = *a; + } + let (mut acc, mut kind) = self.expr(cur, sheet, cur_ctx, depth); + for (i, (op, b, node_ctx)) in spine.into_iter().enumerate().rev() { + let (b, kb) = self.expr(b, sheet, operand(op, node_ctx), depth); + let node = Expr::Binary(op, Box::new(acc), Box::new(b)); + let k = if matches!(op, BinOp::Range | BinOp::Union | BinOp::Intersect) { + Kind::Ref + } else if kind == Kind::Scalar && kb == Kind::Scalar { + Kind::Scalar + } else { + Kind::Array + }; + // An inner operation is an operand: `expr` would intersect it there. + (acc, kind) = if i > 0 && node_ctx == Ctx::Value && k == Kind::Ref { + self.inserted = true; + (at(node), Kind::Scalar) + } else { + (node, k) + }; + } + (acc, kind) + } + fn let_(&mut self, args: Vec, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { let saved = self.locals.len(); let count = args.len(); @@ -482,13 +534,9 @@ fn user_function(name: &str, functions: FunctionInfo) -> bool { fn param(name: &str, i: usize, functions: FunctionInfo) -> Param { match name { - "IF" | "CHOOSE" => { - if i == 0 { - Param::Value - } else { - Param::Pass - } - } + "IF" if i == 0 => Param::Condition, + "CHOOSE" if i == 0 => Param::Value, + "IF" | "CHOOSE" => Param::Pass, "SUMPRODUCT" | "MMULT" | "MINVERSE" | "MDETERM" | "TRANSPOSE" | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH" => Param::Array, "INDEX" if i == 0 => Param::Array, // LOOKUP's vectors and AGGREGATE's array form evaluate their arguments as arrays. diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index 8ba4b18866..9f6cc1d646 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -80,11 +80,12 @@ fn expr_to_file(e: Expr) -> String { // reference that became `#REF!` (its cell was deleted) as plain `#REF!`. Expr::Unary(gridcraft_formula::UnOp::Spill, r) if matches!(*r, Expr::Error(_)) => *r, Expr::Unary(gridcraft_formula::UnOp::Spill, r) => Expr::Call("_xlfn.ANCHORARRAY".into(), vec![*r]), - // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`, and `@(x)` likewise. + // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`, and `@(x)` likewise, + // except that a union keeps its parentheses (its comma would separate arguments). Expr::Unary(gridcraft_formula::UnOp::At, x) => Expr::Call( "_xlfn.SINGLE".into(), vec![match *x { - Expr::Paren(inner) => *inner, + Expr::Paren(inner) if !matches!(*inner, Expr::Binary(gridcraft_formula::BinOp::Union, ..)) => *inner, other => other, }], ), diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 95d2822184..82974c2ffe 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -645,3 +645,19 @@ fn legacy_formulas_use_the_callers_function_facts() { let (back, _) = crate::read_xlsx_with(&out, library).unwrap(); assert_eq!(text(&back, "B2"), "@MYUDF(A1:A3)"); } + +/// Legacy IF does not evaluate its condition as an array inside SUMPRODUCT (that needs +/// Ctrl+Shift+Enter): the condition is intersected there, while IF's results stay arrays. +#[test] +fn legacy_if_condition_is_intersected_inside_array_functions() { + let body = r#" + 1 + 2 + 3 + SUMPRODUCT(IF(A1:A3>1,1,0))SUMPRODUCT(IF(A1>1,A1:A3,0)) + "#; + let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap(); + let text = |a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + assert_eq!(text("D4"), "SUMPRODUCT(IF(@A1:A3>1,1,0))"); + assert_eq!(text("E4"), "SUMPRODUCT(IF(A1>1,A1:A3,0))"); +} diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index f28bb48f64..f4d833438e 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -913,6 +913,58 @@ fn legacy_and_dynamic_formulas_keep_their_kind() { } } +/// The `` text and `cm` attribute of a cell in a written package's first sheet. +fn written_formula(bytes: &[u8], a: &str) -> (Option, Option) { + let mut pkg = Package::open(bytes).unwrap(); + let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap(); + let c = sheet.child("sheetData").unwrap().kids("row").flat_map(|r| r.kids("c")).find(|c| c.attr("r") == Some(a)).unwrap(); + (c.child("f").map(|f| f.text.clone()), c.attr("cm").map(str::to_string)) +} + +/// A long operator chain is analysed in full (its ranges are intersected), and a legacy formula +/// the analysis cannot finish is kept as written. Saving writes neither as `_xlfn.SINGLE`, which +/// pre-dynamic-array Excel shows as #NAME?. +#[test] +fn long_and_deeply_nested_legacy_formulas_never_gain_single() { + let chain = (1..=70).map(|r| format!("B{r}")).collect::>().join("+"); + let nested = format!("{}A1:A3{}", "ABS(".repeat(70), ")".repeat(70)); + let body = format!( + r#" + 1 + 2{chain} + 3A1:A3+{chain} + {nested} + "# + ); + let (wb, _) = read_xlsx(&super::minimal(&body, &[], "", "")).unwrap(); + let text = |wb: &Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + assert_eq!(text(&wb, "D2"), chain); + assert_eq!(text(&wb, "D3"), format!("@A1:A3+{chain}")); + assert_eq!(text(&wb, "D4"), nested); + let bytes = write_xlsx(&wb).unwrap(); + assert_eq!(written_formula(&bytes, "D2"), (Some(chain.clone()), None)); + assert_eq!(written_formula(&bytes, "D3"), (Some(format!("A1:A3+{chain}")), None)); + assert_eq!(written_formula(&bytes, "D4").0, Some(nested)); +} + +/// `@` of a union keeps the union's parentheses when saved, with or without `_xlfn.SINGLE`: +/// without them the comma separates function arguments or the text does not parse. +#[test] +fn implicit_intersection_of_a_union_keeps_its_parentheses() { + let mut wb = Workbook::new(); + let s = wb.sheet_mut(0).unwrap(); + let formulas = ["@(A1:A2,C1:C2)+1", "SQRT(@(A1:A2,C1:C2))", "@(A1:A2,C1:C2)+A1:A3"]; + for (i, f) in formulas.iter().enumerate() { + s.cells.set(CellRef::new(4 + i as u32, 4), Cell::formula(Formula::new(f))); + } + let bytes = write_xlsx(&wb).unwrap(); + let (back, _) = read_xlsx(&bytes).unwrap(); + for (i, f) in formulas.iter().enumerate() { + let cell = back.sheet(0).unwrap().cell(CellRef::new(4 + i as u32, 4)).and_then(|c| c.formula.as_ref()); + assert_eq!(cell.map(|c| (c.text.as_str(), c.expr().is_some())), Some((*f, true)), "{f}"); + } +} + #[test] fn threaded_comments_write_persons_and_linked_legacy_notes() { let wb = sample(); From 47e883ff67cbe4aa3ee4fd0a40375f74bb8375d2 Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:26:50 -0400 Subject: [PATCH 03/13] XLSX: a legacy union already in parentheses saves back without a second pair (never as SINGLE); a name's definition analysed as an array throughout, inserting no @ --- crates/xlsx/src/array_formula.rs | 54 ++++++++++++++++++++++-------- crates/xlsx/src/tests/roundtrip.rs | 23 +++++++++++++ 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index 4cafee34b9..5d25eed694 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -60,7 +60,8 @@ enum Param { Value, /// IF's condition: one value even inside array evaluation. Legacy Excel's IF does not /// evaluate its condition as an array inside SUMPRODUCT unless the formula is a - /// Ctrl+Shift+Enter array, which this analysis never sees. + /// Ctrl+Shift+Enter array, which this analysis never sees. A name's definition is still + /// evaluated as an array throughout ([`Legacy::kind_of`]). Condition, Ref, Array, @@ -89,7 +90,14 @@ pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula let Some(expr) = formula.expr_arc() else { return Export::Unchanged }; let mut explicit = false; expr.walk(&mut |e| explicit |= matches!(e, Expr::Unary(UnOp::At, _))); - let plain = if explicit { strip(expr.as_ref().clone()) } else { expr.as_ref().clone() }; + let plain = if explicit { + match strip(&expr) { + Some(plain) => plain, + None => return Export::Dynamic, + } + } else { + expr.as_ref().clone() + }; let mut legacy = Legacy::new(wb, at, functions); let read_back = legacy.formula(plain.clone(), sheet); if !legacy.certain { @@ -98,10 +106,7 @@ pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula if !explicit { return if legacy.inserted { Export::Dynamic } else { Export::Unchanged }; } - // The text written is `plain` printed: it must read back as `plain` (the printer writes - // only the parentheses the expression has). - let reparses = gridcraft_formula::parse(&gridcraft_formula::print(&plain)).is_ok_and(|e| e == plain); - if reparses && gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } + if gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } } /// Rewrites the legacy cell formulas at `cells` (model sheet index, positions) to their @@ -141,12 +146,21 @@ fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions (legacy.inserted && legacy.certain).then(|| Formula::new(&gridcraft_formula::print(&out))) } -/// Removes every `@` (and the parentheses [`at`] adds; a union keeps them, as its comma would -/// otherwise separate function arguments or fail to parse). -fn strip(e: Expr) -> Expr { +/// `e` without its `@`, such that its text (the printer writes only the parentheses the +/// expression has) reads back as the same expression. Every `@` goes with the parentheses [`at`] +/// adds, as a legacy formula's reading needs (a union there is always inside the file's own +/// parentheses); when the text would then read differently (an `@` of a union given outside +/// parentheses: its comma would separate function arguments or fail to parse), a union keeps them. +fn strip(e: &Expr) -> Option { + let reads_back = |x: Expr| gridcraft_formula::parse(&gridcraft_formula::print(&x)).is_ok_and(|p| p == x).then_some(x); + reads_back(remove_at(e.clone(), false)).or_else(|| reads_back(remove_at(e.clone(), true))) +} + +/// Removes every `@` and the parentheses [`at`] adds, except a union's when `keep_unions`. +fn remove_at(e: Expr, keep_unions: bool) -> Expr { e.map(&mut |x| match x { Expr::Unary(UnOp::At, inner) => match *inner { - Expr::Paren(p) if !atomic(&p) && !matches!(*p, Expr::Binary(BinOp::Union, ..)) => *p, + Expr::Paren(p) if !atomic(&p) && !(keep_unions && matches!(*p, Expr::Binary(BinOp::Union, ..))) => *p, other => other, }, other => other, @@ -173,11 +187,23 @@ struct Legacy<'a> { inserted: bool, /// The analysis finished and covered only established legacy semantics. certain: bool, + /// Analysing an expression whose rewrite is discarded (see [`Legacy::kind_of`]). + discarded: bool, } impl<'a> Legacy<'a> { fn new(wb: &'a Workbook, at: CellRef, functions: FunctionInfo) -> Self { - Legacy { wb, at, functions, remaining: 4096, locals: Vec::new(), inserted: false, certain: true } + Legacy { wb, at, functions, remaining: 4096, locals: Vec::new(), inserted: false, certain: true, discarded: false } + } + + /// The kind of an expression analysed only for its kind (a name's definition, INDIRECT's + /// text), evaluated as legacy Excel evaluates a name: as an array throughout, IF's condition + /// included. Its rewrite is discarded, so it inserts no `@` into the formula. + fn kind_of(&mut self, e: Expr, sheet: usize, depth: usize) -> Kind { + let outer = (std::mem::replace(&mut self.discarded, true), self.inserted); + let (_, kind) = self.expr(e, sheet, Ctx::Array, depth); + (self.discarded, self.inserted) = outer; + kind } /// The whole cell formula: a multi-valued result shows its top-left value. @@ -276,7 +302,7 @@ impl<'a> Legacy<'a> { let Ok(expr) = gridcraft_formula::parse(def.formula.trim_start_matches('=')) else { return Kind::Array }; // A name's own formula does not see the formula's LET variables. let locals = std::mem::take(&mut self.locals); - let (_, kind) = self.expr(expr, def.scope.unwrap_or(scope), Ctx::Array, depth + 1); + let kind = self.kind_of(expr, def.scope.unwrap_or(scope), depth + 1); self.locals = locals; return kind; } @@ -310,7 +336,7 @@ impl<'a> Legacy<'a> { Ctx::Array } }; - let arg_ctx = if ctx == Ctx::Array && param != Param::Condition { Ctx::Array } else { arg_ctx }; + let arg_ctx = if ctx == Ctx::Array && (param != Param::Condition || self.discarded) { Ctx::Array } else { arg_ctx }; let (arg, kind) = self.expr(arg, sheet, arg_ctx, depth); // A value parameter given several values evaluates the function once per value. lifted |= match param { @@ -338,7 +364,7 @@ impl<'a> Legacy<'a> { "INDIRECT" => match out.first() { Some(Expr::Text(text)) if !matches!(out.get(1), Some(Expr::Bool(false))) => match gridcraft_formula::parse(text) { Ok(e) => { - let (_, kind) = self.expr(e, sheet, Ctx::Array, depth); + let kind = self.kind_of(e, sheet, depth); if kind == Kind::Scalar { Kind::Scalar } else { Kind::Ref } } Err(_) => Kind::Ref, diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index f4d833438e..6a6e6c5e77 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -965,6 +965,29 @@ fn implicit_intersection_of_a_union_keeps_its_parentheses() { } } +/// A legacy formula read from a file saves back exactly as it was read, without `cm` or +/// `_xlfn.SINGLE`: a union already in parentheses where one value is expected, and a name whose +/// definition holds IF of a range (legacy Excel evaluates a name's definition as an array). +#[test] +fn legacy_unions_in_parentheses_and_names_with_if_save_as_read() { + let body = r#" + 14SQRT((A1:A2,C1:C2)) + 29(A1:A2,C1:C2)+1 + 3SUM(Flag)SQRT(Flag) + "#; + let names = r#"IF(Data!$A$1:$A$3>1,1,0)"#; + let (wb, _) = read_xlsx(&super::minimal(body, &[], "", names)).unwrap(); + let text = |a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + let bytes = write_xlsx(&wb).unwrap(); + let cases = [("E1", "SQRT((A1:A2,C1:C2))"), ("E2", "(A1:A2,C1:C2)+1"), ("E3", "SUM(Flag)"), ("F3", "SQRT(Flag)")]; + let wrong: Vec<_> = + cases.iter().map(|(a, f)| (*a, *f, written_formula(&bytes, a))).filter(|(_, f, w)| *w != (Some(f.to_string()), None)).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); + assert_eq!(text("F3"), "@SQRT(Flag)"); + let (xml, _) = sheet1_xml(&bytes); + assert!(!xml.contains("SINGLE") && !xml.contains("cm=") && !xml.contains("t=\"array\""), "{xml}"); +} + #[test] fn threaded_comments_write_persons_and_linked_legacy_notes() { let wb = sample(); From 6bd0af07b715541e14e9ff4c4552db4ce80a8e9e Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 19:07:56 -0400 Subject: [PATCH 04/13] XLSX: drop the unreachable keep-unions retry; an @ of a bare union saves as a dynamic formula --- crates/xlsx/src/array_formula.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index 5d25eed694..fcf9ae485d 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -146,21 +146,20 @@ fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions (legacy.inserted && legacy.certain).then(|| Formula::new(&gridcraft_formula::print(&out))) } -/// `e` without its `@`, such that its text (the printer writes only the parentheses the -/// expression has) reads back as the same expression. Every `@` goes with the parentheses [`at`] -/// adds, as a legacy formula's reading needs (a union there is always inside the file's own -/// parentheses); when the text would then read differently (an `@` of a union given outside -/// parentheses: its comma would separate function arguments or fail to parse), a union keeps them. +/// `e` without its `@`, when its text (the printer writes only the parentheses the expression +/// has) reads back as the same expression. Every `@` goes with the parentheses [`at`] adds, as a +/// legacy formula's reading needs (a union there is always inside the file's own parentheses). +/// An `@` of a bare union has no such text, so its formula is saved as a dynamic one. fn strip(e: &Expr) -> Option { - let reads_back = |x: Expr| gridcraft_formula::parse(&gridcraft_formula::print(&x)).is_ok_and(|p| p == x).then_some(x); - reads_back(remove_at(e.clone(), false)).or_else(|| reads_back(remove_at(e.clone(), true))) + let plain = remove_at(e.clone()); + gridcraft_formula::parse(&gridcraft_formula::print(&plain)).is_ok_and(|p| p == plain).then_some(plain) } -/// Removes every `@` and the parentheses [`at`] adds, except a union's when `keep_unions`. -fn remove_at(e: Expr, keep_unions: bool) -> Expr { +/// Removes every `@` and the parentheses [`at`] adds. +fn remove_at(e: Expr) -> Expr { e.map(&mut |x| match x { Expr::Unary(UnOp::At, inner) => match *inner { - Expr::Paren(p) if !atomic(&p) && !(keep_unions && matches!(*p, Expr::Binary(BinOp::Union, ..))) => *p, + Expr::Paren(p) if !atomic(&p) => *p, other => other, }, other => other, From 16ff3074368d6871d4125f42ee7251c6656c00fb Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:13:19 -0400 Subject: [PATCH 05/13] XLSX: an @ keeps parentheses the reader would not put back (redundant ones, a union's) --- crates/xlsx/src/fmla.rs | 14 +++++++++++--- crates/xlsx/src/tests/roundtrip.rs | 18 +++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index 9f6cc1d646..3772c053ff 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -80,12 +80,13 @@ fn expr_to_file(e: Expr) -> String { // reference that became `#REF!` (its cell was deleted) as plain `#REF!`. Expr::Unary(gridcraft_formula::UnOp::Spill, r) if matches!(*r, Expr::Error(_)) => *r, Expr::Unary(gridcraft_formula::UnOp::Spill, r) => Expr::Call("_xlfn.ANCHORARRAY".into(), vec![*r]), - // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`, and `@(x)` likewise, - // except that a union keeps its parentheses (its comma would separate arguments). + // Nor an `@` operator: Excel writes `@x` as `_xlfn.SINGLE(x)`. The reader puts back the + // parentheses of `@(A1:A3*2)`, `@(-A1:A3)` and the like, so only those are dropped; + // others (a union's, redundant ones) are kept so the text reads back the same. Expr::Unary(gridcraft_formula::UnOp::At, x) => Expr::Call( "_xlfn.SINGLE".into(), vec![match *x { - Expr::Paren(inner) if !matches!(*inner, Expr::Binary(gridcraft_formula::BinOp::Union, ..)) => *inner, + Expr::Paren(inner) if rewrapped_by_single(&inner) => *inner, other => other, }], ), @@ -104,6 +105,13 @@ fn expr_to_file(e: Expr) -> String { gridcraft_formula::print(&e) } +/// The operands whose parentheses the reader adds back to `_xlfn.SINGLE(x)` (see the formula +/// parser): a binary operation other than a union, and a prefix or postfix operator. +fn rewrapped_by_single(e: &Expr) -> bool { + use gridcraft_formula::{BinOp, UnOp}; + matches!(e, Expr::Binary(op, ..) if *op != BinOp::Union) || matches!(e, Expr::Unary(UnOp::Neg | UnOp::Plus | UnOp::Percent, _)) +} + /// `_xlpm.x` → `x` (any case, as the parser upper-cases function names). fn strip_param_prefix(n: String) -> String { match (n.get(..PARAM_PREFIX.len()), n.get(PARAM_PREFIX.len()..)) { diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 6a6e6c5e77..bb2a753b50 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -948,12 +948,24 @@ fn long_and_deeply_nested_legacy_formulas_never_gain_single() { } /// `@` of a union keeps the union's parentheses when saved, with or without `_xlfn.SINGLE`: -/// without them the comma separates function arguments or the text does not parse. +/// without them the comma separates function arguments or the text does not parse. Redundant +/// parentheses under `@` survive too, as only those the reader adds back are dropped. #[test] -fn implicit_intersection_of_a_union_keeps_its_parentheses() { +fn implicit_intersection_keeps_its_parentheses() { let mut wb = Workbook::new(); let s = wb.sheet_mut(0).unwrap(); - let formulas = ["@(A1:A2,C1:C2)+1", "SQRT(@(A1:A2,C1:C2))", "@(A1:A2,C1:C2)+A1:A3"]; + let formulas = [ + "@(A1:A2,C1:C2)+1", + "SQRT(@(A1:A2,C1:C2))", + "@(A1:A2,C1:C2)+A1:A3", + "@((A1:A2,C1:C2))", + "SQRT(@((A1:A2,C1:C2)))", + "@(((A1:A2,C1:C2)))", + "@((A1:A3*2))", + "@(A1:A3)", + "@(A1:A3*2)", + "@(-A1:A3)", + ]; for (i, f) in formulas.iter().enumerate() { s.cells.set(CellRef::new(4 + i as u32, 4), Cell::formula(Formula::new(f))); } From 8f9d58800c01eb63f3a7a0133cad848ca11b8da9 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 08:40:36 -0400 Subject: [PATCH 06/13] XLSX: a redundant @ keeps a legacy formula legacy; IFERROR and IFNA intersected inside SUMPRODUCT; file parentheses and unfinished analyses saved as read An edit could leave an implied @ on a single cell: deleting rows 2:3 under the legacy SQRT(A1:A3), read as SQRT(@A1:A3), gives SQRT(@A1:A1), and a name redefined to one cell does the same to SQRT(@Rng). The writer kept an @ only when re-analysing the formula without it put the same @ back, which it no longer does for one cell, so the formula was saved as SQRT(_xlfn.SINGLE(A1:A1)) with cm, readable only by dynamic-array Excel. The writer now analyses the formula with its own @ in place: an @ is accepted when the analysis implies it at that position or when its operand is a single value there (such an @ changes nothing), and any @ inserted elsewhere or any other @ still makes the formula dynamic. SQRT(@A1:A1) saves as SQRT(A1:A1), SQRT(@A1) as SQRT(A1) and @SUM(A1:A3) as SUM(A1:A3), all without cm; SUMPRODUCT(@SQRT(A1:A3)) stays dynamic because SQRT(A1:A3) is an array there. Legacy Excel intersects IFERROR's and IFNA's arguments inside SUMPRODUCT unless the formula is entered with Ctrl+Shift+Enter, like IF's condition: =SUMPRODUCT(IFERROR(VALUE(C19:C21),0)) returns one row's value or #VALUE!, and the accepted fix is CSE or N(+range) (https://stackoverflow.com/questions/59228707). They now get the same single-value parameter class as IF's condition (Param::Single), so the legacy SUMPRODUCT(IFERROR(A1:A3/A1:A3,0)) reads as SUMPRODUCT(IFERROR(@A1:A3/@A1:A3,0)), and a typed SUMPRODUCT(IFERROR(VALUE(A1:A3),0)), which dynamic-array Excel evaluates as an array, is saved with cm. IF's result arguments are left as arrays: in https://stackoverflow.com/questions/29682328, a non-CSE =SUMPRODUCT(--(B4=IF(NOT($C$4:$C$11),$B$4:$B$11))) in row 4 returns 2 (both "apple" rows of B4:B11 counted, so the result branch was not intersected), 0 in a row where C is TRUE and #VALUE! outside rows 4:11 (the condition was intersected). The reader's @ in front of a whole-formula array result took no extra parentheses when the file already had them, so ({1,2}+1) and {1,2}+1 both read as @({1,2}+1), and the writer dropped the file's parentheses. An operand already in parentheses now gets a second pair, so ({1,2}+1) saves as written. A legacy formula the analysis could not finish (node budget, nesting) was read unchanged, evaluated as a dynamic-array formula and saved with cm, so Excel spilled it. Names were analysed again at every use, so a 399-term name used six times exhausted the 4096-node budget; their kinds are now remembered per formula, and the budget is 16384 nodes. The nesting limit is 128, so Excel's 64 levels of nested functions are analysed. A formula that still exceeds the limits is saved as it was read, without cm. --- crates/xlsx/src/array_formula.rs | 170 +++++++++++++++++++------- crates/xlsx/src/tests/array_export.rs | 16 ++- crates/xlsx/src/tests/fixtures.rs | 11 +- crates/xlsx/src/tests/roundtrip.rs | 71 +++++++++-- docs/decisions.md | 2 +- docs/file-format-parity.md | 2 +- 6 files changed, 203 insertions(+), 69 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index fcf9ae485d..73d4ac7278 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -10,10 +10,12 @@ //! that text, without `@`, and gives every other formula dynamic-array metadata. //! //! A range is harmless in SUM, but not in SQRT or arithmetic: `SUM(A1:A3*B1:B3)` intersects both -//! operands. Legacy array-aware parameters such as SUMPRODUCT's evaluate everything inside as -//! arrays, so nothing there is intersected. This is file-format policy, not a second evaluator: -//! unknown results are never calculated. +//! operands. Legacy array-aware parameters such as SUMPRODUCT's evaluate what is inside as +//! arrays, so nothing there is intersected, except IF's condition and IFERROR's and IFNA's +//! arguments ([`Param::Single`]). This is file-format policy, not a second evaluator: unknown +//! results are never calculated. +use std::collections::HashMap; use std::sync::Arc; use gridcraft_core::CellRef; @@ -58,11 +60,11 @@ enum Ctx { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Param { Value, - /// IF's condition: one value even inside array evaluation. Legacy Excel's IF does not - /// evaluate its condition as an array inside SUMPRODUCT unless the formula is a - /// Ctrl+Shift+Enter array, which this analysis never sees. A name's definition is still + /// One value even inside array evaluation: IF's condition and IFERROR's and IFNA's + /// arguments. Legacy Excel evaluates them as arrays inside SUMPRODUCT only in a + /// Ctrl+Shift+Enter formula, which this analysis never sees. A name's definition is still /// evaluated as an array throughout ([`Legacy::kind_of`]). - Condition, + Single, Ref, Array, /// The parameter is evaluated like the call itself (IF's and CHOOSE's results). @@ -90,23 +92,25 @@ pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula let Some(expr) = formula.expr_arc() else { return Export::Unchanged }; let mut explicit = false; expr.walk(&mut |e| explicit |= matches!(e, Expr::Unary(UnOp::At, _))); - let plain = if explicit { - match strip(&expr) { - Some(plain) => plain, - None => return Export::Dynamic, - } - } else { - expr.as_ref().clone() - }; let mut legacy = Legacy::new(wb, at, functions); - let read_back = legacy.formula(plain.clone(), sheet); - if !legacy.certain { - return Export::Dynamic; - } if !explicit { - return if legacy.inserted { Export::Dynamic } else { Export::Unchanged }; + legacy.formula(expr.as_ref().clone(), sheet); + return if !legacy.certain { + Export::Dynamic + } else if !legacy.complete || legacy.inserted == 0 { + // An analysis that stopped at its limits leaves a legacy formula as it was read; + // saving it keeps it legacy. + Export::Unchanged + } else { + Export::Dynamic + }; } - if gridcraft_formula::print(&read_back) == gridcraft_formula::print(&expr) { Export::Legacy(plain) } else { Export::Dynamic } + let Some(plain) = strip(&expr) else { return Export::Dynamic }; + // The formula is the legacy reading of `plain` when every `@` in it is one the analysis of + // `plain` inserts, or one of a single value, and the analysis inserts no other. + legacy.explicit = true; + legacy.formula(expr.as_ref().clone(), sheet); + if legacy.certain && legacy.complete && !legacy.foreign && legacy.inserted == 0 { Export::Legacy(plain) } else { Export::Dynamic } } /// Rewrites the legacy cell formulas at `cells` (model sheet index, positions) to their @@ -143,7 +147,7 @@ fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions let out = legacy.formula(expr.as_ref().clone(), sheet); // Text round trip: the stored expression is exactly what the text parses to. An analysis // that stopped early leaves the formula as it was read. - (legacy.inserted && legacy.certain).then(|| Formula::new(&gridcraft_formula::print(&out))) + (legacy.inserted > 0 && legacy.certain && legacy.complete).then(|| Formula::new(&gridcraft_formula::print(&out))) } /// `e` without its `@`, when its text (the printer writes only the parentheses the expression @@ -158,75 +162,133 @@ fn strip(e: &Expr) -> Option { /// Removes every `@` and the parentheses [`at`] adds. fn remove_at(e: Expr) -> Expr { e.map(&mut |x| match x { - Expr::Unary(UnOp::At, inner) => match *inner { - Expr::Paren(p) if !atomic(&p) => *p, - other => other, - }, + Expr::Unary(UnOp::At, inner) => unwrap_at(*inner), other => other, }) } -/// `@e`, parenthesized unless `e` prints as one operand. +/// The operand of an `@` without the parentheses [`at`] adds. +fn unwrap_at(e: Expr) -> Expr { + match e { + Expr::Paren(p) if !atomic(&p) => *p, + other => other, + } +} + +/// `@e`, parenthesized unless `e` prints as one operand. An operand already in parentheses (the +/// file's own) gets a second pair, so [`remove_at`] can tell them from the ones added here. fn at(e: Expr) -> Expr { let e = if atomic(&e) { e } else { Expr::Paren(Box::new(e)) }; Expr::Unary(UnOp::At, Box::new(e)) } fn atomic(e: &Expr) -> bool { - matches!(e, Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_) | Expr::Call(..) | Expr::Paren(_) | Expr::Array(_)) + matches!(e, Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_) | Expr::Call(..) | Expr::Array(_)) } +/// Nesting the analysis follows: Excel allows 64 levels of nested functions, and parentheses +/// and names add levels. Operator chains do not count (see [`Legacy::binary`]). +const MAX_DEPTH: usize = 128; + struct Legacy<'a> { wb: &'a Workbook, at: CellRef, functions: FunctionInfo, remaining: usize, locals: Vec<(String, Kind)>, - /// An `@` was inserted. - inserted: bool, - /// The analysis finished and covered only established legacy semantics. + /// Kinds of the names analysed so far, by upper-case name and scope; `None` while a name's + /// definition is being analysed (a cycle). + names: HashMap<(String, usize), Option>, + /// How many `@` were inserted. + inserted: usize, + /// The analysis covered only established legacy semantics. certain: bool, + /// The analysis finished within its nesting and size limits. + complete: bool, + /// Analysing a formula that has its own `@` (see [`Legacy::explicit_at`]). + explicit: bool, + /// An explicit `@` is neither implied by legacy evaluation nor of a single value. + foreign: bool, /// Analysing an expression whose rewrite is discarded (see [`Legacy::kind_of`]). discarded: bool, } impl<'a> Legacy<'a> { fn new(wb: &'a Workbook, at: CellRef, functions: FunctionInfo) -> Self { - Legacy { wb, at, functions, remaining: 4096, locals: Vec::new(), inserted: false, certain: true, discarded: false } + Legacy { + wb, + at, + functions, + remaining: 16384, + locals: Vec::new(), + names: HashMap::new(), + inserted: 0, + certain: true, + complete: true, + explicit: false, + foreign: false, + discarded: false, + } } /// The kind of an expression analysed only for its kind (a name's definition, INDIRECT's /// text), evaluated as legacy Excel evaluates a name: as an array throughout, IF's condition /// included. Its rewrite is discarded, so it inserts no `@` into the formula. fn kind_of(&mut self, e: Expr, sheet: usize, depth: usize) -> Kind { - let outer = (std::mem::replace(&mut self.discarded, true), self.inserted); + let outer = (std::mem::replace(&mut self.discarded, true), std::mem::replace(&mut self.explicit, false), self.inserted); let (_, kind) = self.expr(e, sheet, Ctx::Array, depth); - (self.discarded, self.inserted) = outer; + (self.discarded, self.explicit, self.inserted) = outer; kind } /// The whole cell formula: a multi-valued result shows its top-left value. fn formula(&mut self, e: Expr, sheet: usize) -> Expr { + let e = match e { + Expr::Unary(UnOp::At, x) if self.explicit => return self.explicit_at(*x, sheet, Ctx::Value, 0, true).0, + e => e, + }; let (e, kind) = self.expr(e, sheet, Ctx::Value, 0); if kind == Kind::Array && self.certain { - self.inserted = true; + self.inserted += 1; at(e) } else { e } } + /// An `@` already in the formula, at a position the analysis reads in `ctx`: analysed as its + /// operand alone. The `@` is the one legacy evaluation implies when the analysis puts it back + /// (that insertion is then not counted), or redundant when the operand is a single value; + /// any other `@` makes the formula a dynamic-array one (`foreign`). + fn explicit_at(&mut self, x: Expr, sheet: usize, ctx: Ctx, depth: usize, top: bool) -> (Expr, Kind) { + let operand = unwrap_at(x); + let nested = matches!(operand, Expr::Unary(UnOp::At, _)); + let before = self.inserted; + let (y, kind) = self.expr(operand, sheet, ctx, depth + 1); + if !nested && self.inserted > before && matches!(y, Expr::Unary(UnOp::At, _)) { + self.inserted -= 1; + return (y, Kind::Scalar); + } + if top && kind == Kind::Array { + return (at(y), Kind::Scalar); + } + if kind != Kind::Scalar { + self.foreign = true; + } + (Expr::Unary(UnOp::At, Box::new(y)), Kind::Scalar) + } + fn expr(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { - // Names can be cyclic, and a short chain of repeated names can expand exponentially. - // Operator chains do not count towards the depth (see [`Legacy::binary`]). - if depth >= 64 || self.remaining == 0 { - self.certain = false; + // Names can be cyclic or nest deeply; their kinds are remembered, so repeated names + // cost one analysis each. + if depth >= MAX_DEPTH || self.remaining == 0 { + self.complete = false; return (e, Kind::Array); } self.remaining -= 1; let (e, kind) = self.node(e, sheet, ctx, depth); if ctx == Ctx::Value && kind == Kind::Ref { - self.inserted = true; + self.inserted += 1; (at(e), Kind::Scalar) } else { (e, kind) @@ -266,6 +328,7 @@ impl<'a> Legacy<'a> { let (x, kind) = self.expr(*x, sheet, ctx, depth + 1); (Expr::Paren(Box::new(x)), kind) } + Expr::Unary(UnOp::At, x) if self.explicit => self.explicit_at(*x, sheet, ctx, depth, false), Expr::Unary(UnOp::At, x) => { let (x, _) = self.expr(*x, sheet, inner(Ctx::Ref), depth + 1); (Expr::Unary(UnOp::At, Box::new(x)), Kind::Scalar) @@ -298,11 +361,23 @@ impl<'a> Legacy<'a> { None => (sheet, n), }; if let Some(def) = self.wb.name(bare, scope) { + let key = (bare.to_ascii_uppercase(), scope); + match self.names.get(&key) { + Some(Some(kind)) => return *kind, + Some(None) => { + // A name defined in terms of itself has no legacy value to keep. + self.certain = false; + return Kind::Array; + } + None => {} + } let Ok(expr) = gridcraft_formula::parse(def.formula.trim_start_matches('=')) else { return Kind::Array }; + self.names.insert(key.clone(), None); // A name's own formula does not see the formula's LET variables. let locals = std::mem::take(&mut self.locals); let kind = self.kind_of(expr, def.scope.unwrap_or(scope), depth + 1); self.locals = locals; + self.names.insert(key, Some(kind)); return kind; } if self.wb.table(bare).is_some() { Kind::Ref } else { Kind::Scalar } @@ -326,7 +401,7 @@ impl<'a> Legacy<'a> { for (i, arg) in args.into_iter().enumerate() { let param = param(&name, i, self.functions); let arg_ctx = match param { - Param::Value | Param::Condition => Ctx::Value, + Param::Value | Param::Single => Ctx::Value, Param::Ref | Param::First => Ctx::Ref, Param::Pass => ctx, Param::Array => Ctx::Array, @@ -335,11 +410,11 @@ impl<'a> Legacy<'a> { Ctx::Array } }; - let arg_ctx = if ctx == Ctx::Array && (param != Param::Condition || self.discarded) { Ctx::Array } else { arg_ctx }; + let arg_ctx = if ctx == Ctx::Array && (param != Param::Single || self.discarded) { Ctx::Array } else { arg_ctx }; let (arg, kind) = self.expr(arg, sheet, arg_ctx, depth); // A value parameter given several values evaluates the function once per value. lifted |= match param { - Param::Value | Param::Condition => kind == Kind::Array || (kind == Kind::Ref && arg_ctx == Ctx::Array), + Param::Value | Param::Single => kind == Kind::Array || (kind == Kind::Ref && arg_ctx == Ctx::Array), Param::First => kind != Kind::Scalar, _ => false, }; @@ -356,7 +431,7 @@ impl<'a> Legacy<'a> { Kind::Array } else { // Outside array evaluation, ROW and COLUMN of a range give its first row or column. - self.inserted = true; + self.inserted += 1; return (at(Expr::Call(name, out)), Kind::Scalar); } } @@ -435,7 +510,7 @@ impl<'a> Legacy<'a> { if !spine.is_empty() { // The caller's `expr` counted the outermost operation. if self.remaining == 0 { - self.certain = false; + self.complete = false; } else { self.remaining -= 1; } @@ -457,7 +532,7 @@ impl<'a> Legacy<'a> { }; // An inner operation is an operand: `expr` would intersect it there. (acc, kind) = if i > 0 && node_ctx == Ctx::Value && k == Kind::Ref { - self.inserted = true; + self.inserted += 1; (at(node), Kind::Scalar) } else { (node, k) @@ -559,7 +634,8 @@ fn user_function(name: &str, functions: FunctionInfo) -> bool { fn param(name: &str, i: usize, functions: FunctionInfo) -> Param { match name { - "IF" if i == 0 => Param::Condition, + "IF" if i == 0 => Param::Single, + "IFERROR" | "IFNA" => Param::Single, "CHOOSE" if i == 0 => Param::Value, "IF" | "CHOOSE" => Param::Pass, "SUMPRODUCT" | "MMULT" | "MINVERSE" | "MDETERM" | "TRANSPOSE" | "FREQUENCY" | "LINEST" | "LOGEST" | "TREND" | "GROWTH" => Param::Array, diff --git a/crates/xlsx/src/tests/array_export.rs b/crates/xlsx/src/tests/array_export.rs index 7f5f54ab2c..e1ae5af74c 100644 --- a/crates/xlsx/src/tests/array_export.rs +++ b/crates/xlsx/src/tests/array_export.rs @@ -292,13 +292,21 @@ fn implicit_intersection_metadata_respects_function_argument_context() { ("SUM(A1:A3)", false), ("SUMPRODUCT(A1:A3*B1:B3)", false), ("SUMPRODUCT(SQRT(A1:A3))", false), - // An `@` that legacy Excel implies is dropped (the reader puts it back); any other - // `@` is written as `_xlfn.SINGLE`, which only dynamic-array formulas evaluate. + // An `@` that legacy Excel implies is dropped (the reader puts it back), and so is an + // `@` of one value (`SQRT(@A1:A1)` after deleting rows under `SQRT(@A1:A3)`); any + // other `@` is written as `_xlfn.SINGLE`, which only dynamic-array formulas evaluate. ("SQRT(@A1:A3)", false), ("@A1:A3*2", false), ("@(A1:A3*2)", true), - ("SQRT(@A1)", true), - ("@SUM(A1:A3)", true), + ("SQRT(@A1)", false), + ("SQRT(@A1:A1)", false), + ("@SUM(A1:A3)", false), + ("SUMPRODUCT(@ROW(A1:A3))", true), + ("SUMPRODUCT(@SQRT(A1:A3))", true), + // Legacy Excel intersects IFERROR's and IFNA's arguments inside SUMPRODUCT; dynamic-array + // Excel evaluates them as arrays. + ("SUMPRODUCT(IFERROR(VALUE(A1:A3),0))", true), + ("SUMPRODUCT(IFNA(A1:A3,0))", true), ("SQRT(INDIRECT(\"A1\"))", false), ("SUM(INDIRECT(\"A1:A3\"))", false), ("SQRT(INDIRECT(\"A1:A3\"))", true), diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 82974c2ffe..a8ab790812 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -646,18 +646,21 @@ fn legacy_formulas_use_the_callers_function_facts() { assert_eq!(text(&back, "B2"), "@MYUDF(A1:A3)"); } -/// Legacy IF does not evaluate its condition as an array inside SUMPRODUCT (that needs -/// Ctrl+Shift+Enter): the condition is intersected there, while IF's results stay arrays. +/// Legacy IF does not evaluate its condition as an array inside SUMPRODUCT, nor IFERROR and IFNA +/// their arguments (that needs Ctrl+Shift+Enter): they are intersected there, while IF's results +/// stay arrays. #[test] -fn legacy_if_condition_is_intersected_inside_array_functions() { +fn legacy_if_and_iferror_arguments_are_intersected_inside_array_functions() { let body = r#" 1 - 2 + 2SUMPRODUCT(IFERROR(A1:A3/A1:A3,0))SUMPRODUCT(IFNA(A1:A3,0),A1:A3) 3 SUMPRODUCT(IF(A1:A3>1,1,0))SUMPRODUCT(IF(A1>1,A1:A3,0)) "#; let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap(); let text = |a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + assert_eq!(text("D2"), "SUMPRODUCT(IFERROR(@A1:A3/@A1:A3,0))"); + assert_eq!(text("E2"), "SUMPRODUCT(IFNA(@A1:A3,0),A1:A3)"); assert_eq!(text("D4"), "SUMPRODUCT(IF(@A1:A3>1,1,0))"); assert_eq!(text("E4"), "SUMPRODUCT(IF(A1>1,A1:A3,0))"); } diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index bb2a753b50..d386152a5b 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -921,30 +921,44 @@ fn written_formula(bytes: &[u8], a: &str) -> (Option, Option) { (c.child("f").map(|f| f.text.clone()), c.attr("cm").map(str::to_string)) } -/// A long operator chain is analysed in full (its ranges are intersected), and a legacy formula -/// the analysis cannot finish is kept as written. Saving writes neither as `_xlfn.SINGLE`, which -/// pre-dynamic-array Excel shows as #NAME?. +/// A long operator chain is analysed in full (its ranges are intersected), and so are an +/// Excel-legal 64-deep function nesting and a long name used several times. A legacy formula the +/// analysis cannot finish is kept as written. Saving writes none of them as `_xlfn.SINGLE`, which +/// pre-dynamic-array Excel shows as #NAME?, nor with `cm`, which would make them spill. #[test] fn long_and_deeply_nested_legacy_formulas_never_gain_single() { let chain = (1..=70).map(|r| format!("B{r}")).collect::>().join("+"); - let nested = format!("{}A1:A3{}", "ABS(".repeat(70), ")".repeat(70)); + let nested = |depth: usize, inner: &str| format!("{}{inner}{}", "ABS(".repeat(depth), ")".repeat(depth)); + let big = vec!["Data!$B$1"; 399].join("+"); + let uses = format!("{}A1:A3", "Big+".repeat(6)); let body = format!( r#" 1 2{chain} 3A1:A3+{chain} - {nested} - "# + {} + {uses} + {} + "#, + nested(64, "A1:A3"), + nested(200, "A1:A3"), ); - let (wb, _) = read_xlsx(&super::minimal(&body, &[], "", "")).unwrap(); + let names = format!(r#"{big}"#); + let (wb, _) = read_xlsx(&super::minimal(&body, &[], "", &names)).unwrap(); let text = |wb: &Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); assert_eq!(text(&wb, "D2"), chain); assert_eq!(text(&wb, "D3"), format!("@A1:A3+{chain}")); - assert_eq!(text(&wb, "D4"), nested); + assert_eq!(text(&wb, "D4"), nested(64, "@A1:A3")); + assert_eq!(text(&wb, "D5"), format!("{}@A1:A3", "Big+".repeat(6))); + assert_eq!(text(&wb, "D6"), nested(200, "A1:A3")); let bytes = write_xlsx(&wb).unwrap(); assert_eq!(written_formula(&bytes, "D2"), (Some(chain.clone()), None)); assert_eq!(written_formula(&bytes, "D3"), (Some(format!("A1:A3+{chain}")), None)); - assert_eq!(written_formula(&bytes, "D4").0, Some(nested)); + assert_eq!(written_formula(&bytes, "D4"), (Some(nested(64, "A1:A3")), None)); + assert_eq!(written_formula(&bytes, "D5"), (Some(uses), None)); + assert_eq!(written_formula(&bytes, "D6"), (Some(nested(200, "A1:A3")), None)); + let (xml, _) = sheet1_xml(&bytes); + assert!(!xml.contains("SINGLE") && !xml.contains("t=\"array\""), "{xml}"); } /// `@` of a union keeps the union's parentheses when saved, with or without `_xlfn.SINGLE`: @@ -978,20 +992,30 @@ fn implicit_intersection_keeps_its_parentheses() { } /// A legacy formula read from a file saves back exactly as it was read, without `cm` or -/// `_xlfn.SINGLE`: a union already in parentheses where one value is expected, and a name whose -/// definition holds IF of a range (legacy Excel evaluates a name's definition as an array). +/// `_xlfn.SINGLE`: a union already in parentheses where one value is expected, a name whose +/// definition holds IF of a range (legacy Excel evaluates a name's definition as an array), and a +/// multi-valued result in the file's own parentheses. #[test] fn legacy_unions_in_parentheses_and_names_with_if_save_as_read() { let body = r#" 14SQRT((A1:A2,C1:C2)) 29(A1:A2,C1:C2)+1 3SUM(Flag)SQRT(Flag) + ({1,2}+1){1,2}+1(((MYUDF(A1)*2))) "#; let names = r#"IF(Data!$A$1:$A$3>1,1,0)"#; let (wb, _) = read_xlsx(&super::minimal(body, &[], "", names)).unwrap(); let text = |a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); let bytes = write_xlsx(&wb).unwrap(); - let cases = [("E1", "SQRT((A1:A2,C1:C2))"), ("E2", "(A1:A2,C1:C2)+1"), ("E3", "SUM(Flag)"), ("F3", "SQRT(Flag)")]; + let cases = [ + ("E1", "SQRT((A1:A2,C1:C2))"), + ("E2", "(A1:A2,C1:C2)+1"), + ("E3", "SUM(Flag)"), + ("F3", "SQRT(Flag)"), + ("E4", "({1,2}+1)"), + ("F4", "{1,2}+1"), + ("G4", "(((MYUDF(A1)*2)))"), + ]; let wrong: Vec<_> = cases.iter().map(|(a, f)| (*a, *f, written_formula(&bytes, a))).filter(|(_, f, w)| *w != (Some(f.to_string()), None)).collect(); assert!(wrong.is_empty(), "{wrong:?}"); @@ -1000,6 +1024,29 @@ fn legacy_unions_in_parentheses_and_names_with_if_save_as_read() { assert!(!xml.contains("SINGLE") && !xml.contains("cm=") && !xml.contains("t=\"array\""), "{xml}"); } +/// An implied `@` whose operand an edit has made a single cell (deleting rows under +/// `SQRT(@A1:A3)`, redefining a name to one cell) is redundant, not a dynamic-array `@`: the +/// formula still saves as a legacy one, without `_xlfn.SINGLE` or `cm`. +#[test] +fn implied_intersection_made_redundant_by_an_edit_saves_legacy() { + let body = r#" + SQRT(A1:A3)SQRT(Rng) + "#; + let names = r#"Data!$A$1:$A$3"#; + let (mut wb, _) = read_xlsx(&super::minimal(body, &[], "", names)).unwrap(); + let text = |wb: &Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap(); + assert_eq!(text(&wb, "B5"), "SQRT(@A1:A3)"); + assert_eq!(text(&wb, "C5"), "SQRT(@Rng)"); + // What deleting rows 2:3 leaves, and the name now one cell. + wb.sheet_mut(0).unwrap().cells.set(at("B5"), Cell::formula(Formula::new("SQRT(@A1:A1)"))); + wb.names.iter_mut().find(|n| n.name == "Rng").unwrap().formula = "Data!$A$1".into(); + let bytes = write_xlsx(&wb).unwrap(); + assert_eq!(written_formula(&bytes, "B5"), (Some("SQRT(A1:A1)".into()), None)); + assert_eq!(written_formula(&bytes, "C5"), (Some("SQRT(Rng)".into()), None)); + let (xml, _) = sheet1_xml(&bytes); + assert!(!xml.contains("SINGLE") && !xml.contains("t=\"array\""), "{xml}"); +} + #[test] fn threaded_comments_write_persons_and_linked_legacy_notes() { let wb = sample(); diff --git a/docs/decisions.md b/docs/decisions.md index 58388bf2ea..3cd2c6cd72 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -19,7 +19,7 @@ The exporter inspects the parsed formula without evaluating it. It distinguishes Names are resolved using workbook/sheet scope, and structured references distinguish one table-row cell from a column. Literal `INDIRECT` and `INDEX` arguments permit tighter classification; unresolved reference dimensions are conservatively treated as potentially multiple cells. Name/AST traversal is bounded, with array preservation as the fallback. This is an export classifier, not a claim of exact Excel metadata parity for every function or user-defined function. It stays within the format crate's existing dependencies. -The reader applies the same classification in reverse: a formula without dynamic-array metadata (`cm`) and not entered as a CSE array is a legacy formula, and gets the `@` Excel implies where a range meets a single-value parameter, an operator or the cell result. The writer drops an `@` that legacy Excel would imply and saves that formula without `cm`; any other `@` stays `_xlfn.SINGLE` in a dynamic-array formula. Which names are built-in functions and which parameters take a single value comes from the function library, which the format crate may not depend on: the caller passes a `gridcraft_xlsx::FunctionInfo` (`read_xlsx_with`, `write_xlsx_with`; the engine supplies the library's answers), and `read_xlsx`/`write_xlsx`/`write_xlsx_as` use the crate's own table alone. See Microsoft's [Formula vs. Formula2 documentation](https://learn.microsoft.com/en-us/office/vba/excel/concepts/cells-and-ranges/range-formula-vs-formula2). +The reader applies the same classification in reverse: a formula without dynamic-array metadata (`cm`) and not entered as a CSE array is a legacy formula, and gets the `@` Excel implies where a range meets a single-value parameter, an operator or the cell result. Inside SUMPRODUCT and other array-evaluating parameters, IF's condition and IFERROR's and IFNA's arguments are still intersected, as legacy Excel does without Ctrl+Shift+Enter; IF's results are not. The writer drops an `@` that legacy Excel would imply, or one of a single value (an edit can shrink an implied `@`'s range to one cell), and saves that formula without `cm`; any other `@` stays `_xlfn.SINGLE` in a dynamic-array formula. A legacy formula too large or deeply nested to analyse is read and saved as it is, without `cm`. Which names are built-in functions and which parameters take a single value comes from the function library, which the format crate may not depend on: the caller passes a `gridcraft_xlsx::FunctionInfo` (`read_xlsx_with`, `write_xlsx_with`; the engine supplies the library's answers), and `read_xlsx`/`write_xlsx`/`write_xlsx_as` use the crate's own table alone. See Microsoft's [Formula vs. Formula2 documentation](https://learn.microsoft.com/en-us/office/vba/excel/concepts/cells-and-ranges/range-formula-vs-formula2). ## Static cell pictures diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 43ae0c0016..3b9fb34873 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -22,7 +22,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. Formulas without dynamic-array metadata (`cm`) are legacy formulas and open with Excel's implicit `@`; on save, a formula whose every `@` is implied is written without them and without `cm`, any other formula that legacy Excel would intersect gets dynamic-array metadata (`_xlfn.SINGLE` for an explicit `@`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. Formulas without dynamic-array metadata (`cm`) are legacy formulas and open with Excel's implicit `@`; on save, a formula whose every `@` is implied or of a single value is written without them and without `cm` (so is one too large or deeply nested to analyse), any other formula that legacy Excel would intersect gets dynamic-array metadata (`_xlfn.SINGLE` for an explicit `@`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | From 3ea9245d989dd7d46d3808bd6ba47abb214b5ecf Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 15:00:12 -0500 Subject: [PATCH 07/13] XLS: formulas open as legacy formulas with Excel's implicit @ (#410) Every formula in a .xls (BIFF8) file is a legacy, pre-dynamic-array formula. The import now runs them through the same classification #417 gives legacy XLSX formulas (array_formula::apply_legacy), after the defined names are read, so a range where one value is expected is intersected instead of spilling. `=Data!A1:G1` reads as `@Data!A1:G1`. Shared formulas are classified cell by cell. Ctrl+Shift+Enter arrays stay arrays. A one-cell CSE array now keeps its range (it was dropped, which would have made it legacy), as the XLSX reader does. read_xls_with(bytes, FunctionInfo) is new; read_xls keeps its signature with the default facts, and the engine passes XLSX_FUNCTIONS. The budgeted internal reader is renamed read_xls_budgeted. Saving to .xlsx writes these formulas without cm or _xlfn.SINGLE. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/engine/src/io.rs | 5 +- crates/engine/src/tests.rs | 73 +++++++++++++++++++ crates/xlsx/src/lib.rs | 2 +- crates/xlsx/src/tests/xls_tests.rs | 113 ++++++++++++++++++++++++++++- crates/xlsx/src/xls/mod.rs | 33 +++++++-- docs/file-format-parity.md | 5 +- 7 files changed, 221 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..336c0abe24 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (`.xls` formulas use legacy implicit intersection) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-14 | `.xls` import: formulas open as legacy formulas with Excel's implicit `@`, so a range in a one-cell formula is intersected instead of spilling (`#SPILL!`); Ctrl+Shift+Enter arrays stay arrays and `.xlsx` saves write no `cm` (#410) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | Progress log: `.xls` formulas use legacy implicit intersection (#410) | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index ca5919a005..151cc792cc 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -7,7 +7,7 @@ use gridcraft_model::{Sheet, Workbook}; use crate::{EngineError, Result}; -/// The function library's answers to what the XLSX reader and writer need to know about functions +/// The function library's answers to what the XLSX and XLS readers and the XLSX writer need to know about functions /// (which names are built in, which parameters take a single value). pub const XLSX_FUNCTIONS: gridcraft_xlsx::FunctionInfo = gridcraft_xlsx::FunctionInfo { is_builtin: |name| gridcraft_functions::lookup(name).is_some(), @@ -123,7 +123,8 @@ fn open_plain(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec)> { let kind = FileKind::from_path(name); let sniffed = gridcraft_xlsx::sniff(bytes); if sniffed == gridcraft_xlsx::Format::Xls { - let (wb, report) = gridcraft_xlsx::read_xls(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?; + let (wb, report) = + gridcraft_xlsx::read_xls_with(bytes, XLSX_FUNCTIONS).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?; return Ok((wb, report.warnings)); } if sniffed == gridcraft_xlsx::Format::LegacyBinary { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae499a1895..9fc0fda80d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2524,6 +2524,79 @@ fn xls_import_keeps_formulas_and_never_saves_back_to_xls() { assert!(s.execute("file.saveBytes", json!({"format": "xlsx"})).is_ok()); } +#[test] +fn xls_formulas_calculate_with_legacy_implicit_intersection() { + // Data!A1 = 11, B1:G1 = 1, A2 = 5, A3 = 7. Report!B1:G1 are filled, so a formula in Report!A1 + // that spilled would show #SPILL!. Every cached result is 0, so the values below are GridCraft's. + fn rec(id: u16, payload: &[u8]) -> Vec { + [&id.to_le_bytes()[..], &(payload.len() as u16).to_le_bytes(), payload].concat() + } + let u16s = |v: &[u16]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); + let bof = |dt: u16| rec(0x0809, &[&0x0600u16.to_le_bytes()[..], &dt.to_le_bytes(), &[0; 12]].concat()); + let number = |r: u16, c: u16, n: f64| rec(0x0203, &[&u16s(&[r, c, 0])[..], &n.to_le_bytes()].concat()); + let formula = |r: u16, c: u16, rgce: &[u8]| { + rec(0x0006, &[&u16s(&[r, c, 0])[..], &0f64.to_le_bytes(), &[0; 6], &(rgce.len() as u16).to_le_bytes(), rgce].concat()) + }; + let area3d = |r0: u16, r1: u16, c0: u16, c1: u16| [&[0x3Bu8, 0, 0][..], &u16s(&[r0, r1, c0, c1])].concat(); + let a2a3 = area3d(1, 2, 0, 0); + let mut data = bof(0x0010); + data.extend([number(0, 0, 11.0), number(1, 0, 5.0), number(2, 0, 7.0)].concat()); + (1..7).for_each(|c| data.extend(number(0, c, 1.0))); + data.extend(rec(0x000A, &[])); + let mut report = bof(0x0010); + (1..7).for_each(|c| report.extend(number(0, c, 0.0))); + // A1 = Data!A1:G1; B2 = Data!$A$2:$A$3*10; C2 = SQRT(Data!$A$2:$A$3) (row 2: SQRT(5)); + // H1 = {SUM(Data!$A$2:$A$3*2)}, a one-cell Ctrl+Shift+Enter array. + let cse = [&a2a3[..], &[0x1E, 2, 0, 0x05, 0x22, 1, 4, 0]].concat(); + report.extend(formula(0, 0, &area3d(0, 0, 0xC000, 6 | 0xC000))); + report.extend(formula(1, 1, &[&a2a3[..], &[0x1E, 10, 0, 0x05]].concat())); + report.extend(formula(1, 2, &[&a2a3[..], &[0x21, 20, 0]].concat())); + report.extend(formula(0, 7, &[1, 0, 0, 7, 0])); + report.extend(rec(0x0221, &[&u16s(&[0, 0])[..], &[7, 7], &[0; 6], &(cse.len() as u16).to_le_bytes(), &cse].concat())); + report.extend(rec(0x000A, &[])); + let boundsheet = |pos: u32, name: &str| rec(0x0085, &[&pos.to_le_bytes()[..], &[0, 0, name.len() as u8, 0], name.as_bytes()].concat()); + let globals = |p1: u32, p2: u32| { + [ + bof(0x0005), + boundsheet(p1, "Data"), + boundsheet(p2, "Report"), + rec(0x01AE, &u16s(&[2, 0x0401])), + rec(0x0017, &u16s(&[1, 0, 0, 0])), + rec(0x000A, &[]), + ] + .concat() + }; + let p1 = globals(0, 0).len() as u32; + let stream = [globals(p1, p1 + data.len() as u32), data, report].concat(); + let bytes = gridcraft_xlsx::testing::compound_file(&[("Workbook", &stream)]); + + let mut s = s(); + s.execute("file.open", json!({"name": "legacy.xls", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + s.execute("formulas.calculateNow", json!({})).unwrap(); + let report = |s: &Session, a1: &str| s.doc().unwrap().wb.sheets[1].value(CellRef::parse(a1).unwrap()); + assert_eq!(report(&s, "A1"), Value::Number(11.0)); + assert_eq!(report(&s, "B2"), Value::Number(50.0)); + assert_eq!(report(&s, "C2"), Value::Number(5f64.sqrt())); + assert_eq!(report(&s, "H1"), Value::Number(24.0)); + // Nothing spilled out of A1 or B2. + assert_eq!(report(&s, "B1"), Value::Number(0.0)); + assert_eq!(report(&s, "B3"), Value::Empty); + // Saved as .xlsx, the formulas carry no dynamic-array metadata. + let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + let saved = crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap(); + let (wb, _) = gridcraft_xlsx::read_xlsx(&saved).unwrap(); + let f = |a1: &str| wb.sheets[1].cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.clone()).unwrap(); + assert_eq!(f("A1").text, "@Data!A1:G1"); + assert_eq!((f("H1").text.as_str(), f("H1").array), ("SUM(Data!$A$2:$A$3*2)", gridcraft_core::RangeRef::parse("H1"))); + let mut sheet = String::new(); + std::io::Read::read_to_string( + &mut zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap().by_name("xl/worksheets/sheet2.xml").unwrap(), + &mut sheet, + ) + .unwrap(); + assert!(!sheet.contains("cm=") && !sheet.contains("SINGLE"), "{sheet}"); +} + #[test] fn malformed_xlsb_keeps_the_current_workbook() { let mut s = s(); diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 2eb30c545e..e226d152e9 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -48,7 +48,7 @@ pub use crypto::{DecryptError, check_encryption, decrypt}; pub use csv::{MAX_CSV_BYTES, read_csv, write_csv, write_csv_limited}; pub use ods::read_ods; pub use passthrough::rebase_links; -pub use xls::read_xls; +pub use xls::{read_xls, read_xls_with}; pub use xlsb::read_xlsb; /// Errors from reading or writing files. diff --git a/crates/xlsx/src/tests/xls_tests.rs b/crates/xlsx/src/tests/xls_tests.rs index 91e63c18f7..69abdfd019 100644 --- a/crates/xlsx/src/tests/xls_tests.rs +++ b/crates/xlsx/src/tests/xls_tests.rs @@ -478,8 +478,11 @@ fn sheets_share_one_record_budget() { stream.extend(eof()); let file = compound("Workbook", &stream); // About n × 2,000 records in all: over a 100,000 shared allowance, though each sheet alone fits. - assert!(matches!(crate::xls::read_xls_with(&file, crate::xls::Budget::with_max_records(100_000)), Err(IoError::TooLarge(_)))); - assert!(crate::xls::read_xls_with(&file, crate::xls::Budget::with_max_records(10_000_000)).is_ok()); + assert!(matches!( + crate::xls::read_xls_budgeted(&file, crate::xls::Budget::with_max_records(100_000), crate::FunctionInfo::default()), + Err(IoError::TooLarge(_)) + )); + assert!(crate::xls::read_xls_budgeted(&file, crate::xls::Budget::with_max_records(10_000_000), crate::FunctionInfo::default()).is_ok()); // Two sheets at the same offset are refused outright. let mut dup = bof(0x0005); @@ -594,3 +597,109 @@ fn a_format_shorter_than_its_count_keeps_its_characters() { assert_eq!(fmt("A3"), "0.000"); assert!(report.warnings.iter().any(|w| w.contains("declared length")), "{:?}", report.warnings); } + +/// A workbook whose "Report" sheet holds legacy formulas over ranges of "Data": Data!A1 = 11, +/// B1:G1 = 1, A2 = 5, A3 = 7, and Report!B1:G1 filled, so a formula in Report!A1 that spilled +/// would be blocked. +fn legacy_formulas_book() -> Vec { + let area3d = |r0: u16, r1: u16, c0: u16, c1: u16| cat(&[&[0x3B], &0u16.to_le_bytes(), &u16s(&[r0, r1, c0, c1])]); + let a2a3 = area3d(1, 2, 0, 0); + let sum = |inner: &[u8]| cat(&[inner, &[0x22, 1], &4u16.to_le_bytes()]); + let boundsheet = |pos: u32, name: &str| rec(0x0085, &cat(&[&pos.to_le_bytes(), &[0, 0, name.len() as u8, 0], name.as_bytes()])); + let globals = |p1: u32, p2: u32| { + cat(&[ + &bof(0x0005), + &boundsheet(p1, "Data"), + &boundsheet(p2, "Report"), + &rec(0x01AE, &u16s(&[2, 0x0401])), + &rec(0x0017, &cat(&[&u16s(&[1]), &u16s(&[0, 0, 0])])), + &eof(), + ]) + }; + let number = |r: u16, c: u16, n: f64| rec(0x0203, &cat(&[&cell(r, c, 0), &n.to_le_bytes()])); + let mut data = bof(0x0010); + data.extend(number(0, 0, 11.0)); + for c in 1..7 { + data.extend(number(0, c, 1.0)); + } + data.extend(number(1, 0, 5.0)); + data.extend(number(2, 0, 7.0)); + data.extend(eof()); + let shared = cat(&[&a2a3, &ptg_int(10), &[0x05]]); + let array = cat(&[&a2a3, &ptg_int(2), &[0x05]]); + let single_array = sum(&cat(&[&a2a3, &ptg_int(2), &[0x05]])); + let mut report = bof(0x0010); + for c in 1..7 { + report.extend(number(0, c, 0.0)); + } + report.extend(cat(&[ + // A1 = Data!A1:G1, A2 = +Data!A1:G1 (a title row repeated from another sheet). + &formula(0, 0, num(11.0), &area3d(0, 0, 0xC000, 6 | 0xC000)), + &formula(1, 0, num(11.0), &cat(&[&area3d(0, 0, 0xC000, 6 | 0xC000), &[0x12]])), + // C2:C3 share Data!$A$2:$A$3*10. + &formula(1, 2, num(50.0), &exp(1, 2)), + &rec(0x04BC, &cat(&[&u16s(&[1, 2]), &[2, 2, 0, 2], &(shared.len() as u16).to_le_bytes(), &shared])), + &formula(2, 2, num(70.0), &exp(1, 2)), + // D2:D3 = {Data!$A$2:$A$3*2}, entered with Ctrl+Shift+Enter. + &formula(1, 3, num(10.0), &exp(1, 3)), + &rec(0x0221, &cat(&[&u16s(&[1, 2]), &[3, 3], &[0; 6], &(array.len() as u16).to_le_bytes(), &array])), + &formula(2, 3, num(14.0), &exp(1, 3)), + // H1 = {SUM(Data!$A$2:$A$3*2)}, a one-cell Ctrl+Shift+Enter array. + &formula(0, 7, num(24.0), &exp(0, 7)), + &rec(0x0221, &cat(&[&u16s(&[0, 0]), &[7, 7], &[0; 6], &(single_array.len() as u16).to_le_bytes(), &single_array])), + // H2 = MAX(SUM(Data!$A$2:$A$3/12),0), H3 = SUM(Data!$A$2:$A$3), H4 = SQRT(Data!$A$2:$A$3). + &formula(1, 7, num(5.0 / 12.0), &cat(&[&sum(&cat(&[&a2a3, &ptg_int(12), &[0x06]])), &ptg_int(0), &[0x22, 2], &7u16.to_le_bytes()])), + &formula(2, 7, num(12.0), &sum(&a2a3)), + &formula(3, 7, special(2, 0x0F), &cat(&[&a2a3, &[0x21], &20u16.to_le_bytes()])), + &eof(), + ])); + let p1 = globals(0, 0).len() as u32; + let p2 = p1 + data.len() as u32; + cat(&[&globals(p1, p2), &data, &report]) +} + +#[test] +fn legacy_formulas_read_with_implicit_intersection() { + let bytes = compound("Workbook", &legacy_formulas_book()); + let formula = |wb: &gridcraft_model::Workbook, a1: &str| { + let f = wb.sheets[1].cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.clone()).unwrap(); + (f.text.clone(), f.array) + }; + let range = |a1: &str| RangeRef::parse(a1); + let (wb, _) = read_xls(&bytes).unwrap(); + // Every .xls formula is legacy: a range where one value is expected is intersected. + assert_eq!(formula(&wb, "A1"), ("@Data!A1:G1".into(), None)); + assert_eq!(formula(&wb, "A2"), ("+@Data!A1:G1".into(), None)); + // Shared formulas too, each cell on its own. + assert_eq!(formula(&wb, "C2"), ("@Data!$A$2:$A$3*10".into(), None)); + assert_eq!(formula(&wb, "C3"), ("@Data!$A$2:$A$3*10".into(), None)); + // Ctrl+Shift+Enter arrays, one cell or several, stay arrays and are not intersected. + assert_eq!(formula(&wb, "D2"), ("Data!$A$2:$A$3*2".into(), range("D2:D3"))); + assert_eq!(formula(&wb, "H1"), ("SUM(Data!$A$2:$A$3*2)".into(), range("H1"))); + // An operation inside SUM takes values; SUM of the range itself is left alone. + assert_eq!(formula(&wb, "H2"), ("MAX(SUM(@Data!$A$2:$A$3/12),0)".into(), None)); + assert_eq!(formula(&wb, "H3"), ("SUM(Data!$A$2:$A$3)".into(), None)); + assert_eq!(formula(&wb, "H4"), ("SQRT(@Data!$A$2:$A$3)".into(), None)); + + // The caller's function facts decide: here SQRT takes its argument as a whole. + let library = crate::FunctionInfo { is_builtin: |_| true, is_scalar_arg: |n, _| n != "SQRT" }; + let (custom, _) = crate::read_xls_with(&bytes, library).unwrap(); + assert_eq!(formula(&custom, "H4"), ("SQRT(Data!$A$2:$A$3)".into(), None)); + assert_eq!(formula(&custom, "A1"), ("@Data!A1:G1".into(), None)); + + // Saved as .xlsx, they stay legacy: no dynamic-array metadata, no _xlfn.SINGLE, and they read + // back as they were opened. + let saved = write_xlsx(&wb).unwrap(); + let mut sheet = String::new(); + std::io::Read::read_to_string( + &mut zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap().by_name("xl/worksheets/sheet2.xml").unwrap(), + &mut sheet, + ) + .unwrap(); + assert!(!sheet.contains("cm=") && !sheet.contains("SINGLE"), "{sheet}"); + assert!(sheet.contains("Data!A1:G1") && sheet.contains("MAX(SUM(Data!$A$2:$A$3/12),0)"), "{sheet}"); + let (back, _) = read_xlsx(&saved).unwrap(); + for a1 in ["A1", "A2", "C2", "C3", "D2", "H1", "H2", "H3", "H4"] { + assert_eq!(formula(&back, a1), formula(&wb, a1), "{a1}"); + } +} diff --git a/crates/xlsx/src/xls/mod.rs b/crates/xlsx/src/xls/mod.rs index dde8641e5e..f33bff723b 100644 --- a/crates/xlsx/src/xls/mod.rs +++ b/crates/xlsx/src/xls/mod.rs @@ -8,6 +8,9 @@ //! (mode, iteration, precision as displayed). Everything else (fonts, fills, borders, charts, //! pictures, comments, conditional formats, validation, macros) is skipped with a warning. //! Encrypted workbooks and pre-BIFF8 versions are refused. +//! +//! Every formula in the file is a legacy (pre-dynamic-array) one, so it is read with Excel's +//! implicit `@` (see `array_formula.rs`), like an `.xlsx` formula saved without `cm`. mod formula; mod ftab; @@ -21,7 +24,7 @@ use gridcraft_model::{CalcMode, CalcSettings, Cell, DefinedName, Formula, LineIn use crate::cfb::Compound; use crate::tables::{builtin_format, col_width_to_px, pt_to_px}; -use crate::{IoError, ReadReport}; +use crate::{FunctionInfo, IoError, ReadReport}; use formula::{Links, Mode, SupBook, Unsupported, Xti, cell_error, decode}; use records::{Cursor, Record, Records}; @@ -127,13 +130,20 @@ struct Globals { precision_as_displayed: bool, } -/// Reads an Excel 97-2003 workbook. Inspect the report's warnings for what was skipped. +/// Reads an Excel 97-2003 workbook, with the default [`FunctionInfo`]. Inspect the report's +/// warnings for what was skipped. pub fn read_xls(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { - read_xls_with(bytes, Budget::default()) + read_xls_budgeted(bytes, Budget::default(), FunctionInfo::default()) +} + +/// [`read_xls`] with the function library's facts, which decide where the legacy formulas get +/// Excel's implicit `@`. +pub fn read_xls_with(bytes: &[u8], functions: FunctionInfo) -> Result<(Workbook, ReadReport), IoError> { + read_xls_budgeted(bytes, Budget::default(), functions) } -/// [`read_xls`] with an explicit resource budget. -pub(crate) fn read_xls_with(bytes: &[u8], mut budget: Budget) -> Result<(Workbook, ReadReport), IoError> { +/// [`read_xls_with`] with an explicit resource budget. +pub(crate) fn read_xls_budgeted(bytes: &[u8], mut budget: Budget, functions: FunctionInfo) -> Result<(Workbook, ReadReport), IoError> { let cf = Compound::open(bytes).map_err(invalid)?; let stream = match cf.root_stream("Workbook").map_err(invalid)? { Some(s) => s, @@ -195,6 +205,10 @@ pub(crate) fn read_xls_with(bytes: &[u8], mut budget: Budget) -> Result<(Workboo } wb.calc.precision_as_displayed = g.precision_as_displayed; defined_names(&g, &model_index, &mut wb, &mut report); + // Every .xls formula is a legacy (pre-dynamic-array) one: read with Excel's implicit `@`, like + // an .xlsx formula without `cm`. Ctrl+Shift+Enter arrays are read as they are. + let legacy = wb.sheets.iter().enumerate().map(|(si, s)| (si, legacy_cells(s))).collect(); + crate::array_formula::apply_legacy(&mut wb, legacy, functions); wb.active_sheet = wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0); // The overview comes first. report.warnings.insert( @@ -204,6 +218,11 @@ pub(crate) fn read_xls_with(bytes: &[u8], mut budget: Budget) -> Result<(Workboo Ok((wb, report)) } +/// The cells holding a formula that is not a Ctrl+Shift+Enter array. +fn legacy_cells(sheet: &Sheet) -> Vec { + sheet.cells.iter().filter(|(_, c)| c.formula.as_ref().is_some_and(|f| f.array.is_none())).map(|(at, _)| at).collect() +} + fn bof(rec: &Record<'_>) -> Result<(u16, u16), IoError> { if rec.id != BOF { return Err(invalid("a substream does not start with a BOF record")); @@ -459,7 +478,9 @@ impl SheetState<'_> { self.unsupported("syntax GridCraft can't parse yet"); return; } - f.array = array.filter(|r| !r.is_single()); + // A one-cell Ctrl+Shift+Enter array keeps its range, as when an .xlsx is read: + // it evaluates as an array, not with implicit intersection. + f.array = array; if let Some(cell) = self.sheet.cells.get_mut(pos) { cell.formula = Some(Arc::new(f)); } else { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3b9fb34873..b2f838f624 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (legacy vs dynamic-array formulas: `cm` metadata read and written) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (`.xls` formulas read as legacy formulas with implicit `@`) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -29,7 +29,7 @@ and repair-free opening remain unverified. | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | | `.xlsb` Binary Workbook | R/W | **values only** (#101) | no | Names, visibility, numbers, text, booleans, errors, merges, cached formula results; no formulas, formatting, charts, names | `xlsb_tests.rs` | -| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed). Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | +| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed). Every formula is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | | `.xlt` Excel 97-2003 template | R/W | yes (read as `.xls`) | no | | — | | `.xlam` / `.xla` add-ins | R/W | no | no | VBA; out of scope | — | | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | `.xls` import: every formula is read as a legacy one with Excel's implicit `@` (a title row `=Other!A1:G1` shows its first cell instead of `#SPILL!`), one-cell Ctrl+Shift+Enter arrays stay arrays, and `.xlsx` saves keep them without `cm` (#410) | | 2026-10-13 | minor | Legacy vs dynamic-array formulas: no `cm` reads as legacy (implicit `@` inserted), implied `@` written back without `cm` | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | From aed6e6cae3d3d123fcc0753108b6a6ace02b035b Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Mon, 19 Oct 2026 13:39:10 -0500 Subject: [PATCH 08/13] Share defined-name analysis across formula cells; dedupe parity rows apply_legacy and export built a new Legacy per formula cell, so a defined name was parsed and analysed again for every formula that referred to it. A NameCache, built once per read pass and once per workbook write, now keeps each name's kind, certainty, budget cost and nesting depth. A later formula is charged that cost and depth, so its result is the same as a fresh analysis; incomplete and position-dependent (empty-table structured reference) analyses are not cached, and the cache is capped. Docs: merge the new .xls legacy-formula text into the existing .xls row of file-format-parity.md (keeping the WINDOW2 display options), and drop the old implicit intersection row from function-parity.md. Co-Authored-By: Claude Sonnet 5.5 --- crates/xlsx/src/array_formula.rs | 83 +++++++++++++++++++++++++-- crates/xlsx/src/sheet_write.rs | 2 +- crates/xlsx/src/tests/array_export.rs | 73 +++++++++++++++++++++++ crates/xlsx/src/write.rs | 3 + docs/file-format-parity.md | 3 +- docs/function-parity.md | 1 - 6 files changed, 155 insertions(+), 10 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index 73d4ac7278..32e6ed8524 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -88,11 +88,11 @@ pub(crate) enum Export { Dynamic, } -pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo) -> Export { +pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo, names: &mut NameCache) -> Export { let Some(expr) = formula.expr_arc() else { return Export::Unchanged }; let mut explicit = false; expr.walk(&mut |e| explicit |= matches!(e, Expr::Unary(UnOp::At, _))); - let mut legacy = Legacy::new(wb, at, functions); + let mut legacy = Legacy::new(wb, at, functions, names); if !explicit { legacy.formula(expr.as_ref().clone(), sheet); return if !legacy.certain { @@ -116,12 +116,14 @@ pub(crate) fn export(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula /// Rewrites the legacy cell formulas at `cells` (model sheet index, positions) to their /// dynamic-array reading, with `@` where Excel intersects. Runs once names and tables are loaded. pub(crate) fn apply_legacy(wb: &mut Workbook, cells: Vec<(usize, Vec)>, functions: FunctionInfo) { + // Defined names do not change during the pass: each is analysed once for all the cells. + let mut names = NameCache::default(); for (si, positions) in cells { let Some(sheet) = wb.sheet(si) else { continue }; let mut changed = Vec::new(); for at in positions { let Some(formula) = sheet.cell(at).and_then(|c| c.formula.as_deref()) else { continue }; - if let Some(f) = legacy(wb, si, at, formula, functions) { + if let Some(f) = legacy(wb, si, at, formula, functions, &mut names) { changed.push((at, f)); } } @@ -138,12 +140,12 @@ pub(crate) fn apply_legacy(wb: &mut Workbook, cells: Vec<(usize, Vec)>, } /// The dynamic-array reading of a legacy formula, when it differs. -fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo) -> Option { +fn legacy(wb: &Workbook, sheet: usize, at: CellRef, formula: &Formula, functions: FunctionInfo, names: &mut NameCache) -> Option { if formula.array.is_some() { return None; } let expr = formula.expr_arc()?; - let mut legacy = Legacy::new(wb, at, functions); + let mut legacy = Legacy::new(wb, at, functions, names); let out = legacy.formula(expr.as_ref().clone(), sheet); // Text round trip: the stored expression is exactly what the text parses to. An analysis // that stopped early leaves the formula as it was read. @@ -190,8 +192,40 @@ fn atomic(e: &Expr) -> bool { /// and names add levels. Operator chains do not count (see [`Legacy::binary`]). const MAX_DEPTH: usize = 128; +/// What the analysis of one defined name leaves for a later formula that refers to it. +#[derive(Clone, Copy)] +struct NameInfo { + kind: Kind, + /// The analysis covered only established legacy semantics. + certain: bool, + /// Nodes of the per-formula budget the analysis used. + cost: usize, + /// Nesting below the reference that the analysis reached. + depth: usize, +} + +/// Defined names analysed so far, shared by the formulas of one pass (reading a workbook, or +/// writing one) so that a name is parsed and analysed once, not once per formula that refers +/// to it. Keyed by upper-case name and scope. Only analyses that finished within their limits +/// and did not depend on the formula's own position are kept; a later formula is charged the +/// budget and nesting the analysis used, so its result is the one a fresh analysis gives. +#[derive(Default)] +pub(crate) struct NameCache { + map: HashMap<(String, usize), NameInfo>, + /// How many names were analysed (not found in the cache). + pub(crate) analyses: usize, +} + +/// Names kept at most: the cache is bounded even when a workbook defines a great many. +const MAX_CACHED_NAMES: usize = 65_536; + struct Legacy<'a> { wb: &'a Workbook, + shared: &'a mut NameCache, + /// The analysis read a structured reference without a table name, which depends on `at`. + position_dependent: bool, + /// The deepest nesting reached. + deepest: usize, at: CellRef, functions: FunctionInfo, remaining: usize, @@ -214,9 +248,12 @@ struct Legacy<'a> { } impl<'a> Legacy<'a> { - fn new(wb: &'a Workbook, at: CellRef, functions: FunctionInfo) -> Self { + fn new(wb: &'a Workbook, at: CellRef, functions: FunctionInfo, shared: &'a mut NameCache) -> Self { Legacy { wb, + shared, + position_dependent: false, + deepest: 0, at, functions, remaining: 16384, @@ -281,6 +318,7 @@ impl<'a> Legacy<'a> { fn expr(&mut self, e: Expr, sheet: usize, ctx: Ctx, depth: usize) -> (Expr, Kind) { // Names can be cyclic or nest deeply; their kinds are remembered, so repeated names // cost one analysis each. + self.deepest = self.deepest.max(depth); if depth >= MAX_DEPTH || self.remaining == 0 { self.complete = false; return (e, Kind::Array); @@ -312,6 +350,7 @@ impl<'a> Legacy<'a> { } Expr::Struct(r) => { let table = if r.table.is_empty() { + self.position_dependent = true; self.wb.sheet(sheet).and_then(|s| s.table_at(self.at)) } else { self.wb.table(&r.table).and_then(|(si, ti)| self.wb.sheet(si).and_then(|s| s.tables.get(ti))) @@ -371,12 +410,44 @@ impl<'a> Legacy<'a> { } None => {} } + if let Some(info) = self.shared.map.get(&key).copied() { + // Charged as the analysis was, so the outcome is a fresh analysis's. + let reached = depth.saturating_add(1).saturating_add(info.depth); + self.deepest = self.deepest.max(reached); + self.certain &= info.certain; + if reached >= MAX_DEPTH || info.cost > self.remaining { + self.complete = false; + self.remaining = self.remaining.saturating_sub(info.cost); + } else { + self.remaining -= info.cost; + } + self.names.insert(key, Some(info.kind)); + return info.kind; + } let Ok(expr) = gridcraft_formula::parse(def.formula.trim_start_matches('=')) else { return Kind::Array }; + self.shared.analyses += 1; self.names.insert(key.clone(), None); // A name's own formula does not see the formula's LET variables. let locals = std::mem::take(&mut self.locals); + let before = self.remaining; + let outer = ( + std::mem::replace(&mut self.certain, true), + std::mem::replace(&mut self.complete, true), + std::mem::replace(&mut self.position_dependent, false), + std::mem::replace(&mut self.deepest, 0), + ); let kind = self.kind_of(expr, def.scope.unwrap_or(scope), depth + 1); + let info = + NameInfo { kind, certain: self.certain, cost: before.saturating_sub(self.remaining), depth: self.deepest.saturating_sub(depth + 1) }; + let cacheable = self.complete && !self.position_dependent; + self.certain &= outer.0; + self.complete &= outer.1; + self.position_dependent |= outer.2; + self.deepest = self.deepest.max(outer.3); self.locals = locals; + if cacheable && self.shared.map.len() < MAX_CACHED_NAMES { + self.shared.map.insert(key.clone(), info); + } self.names.insert(key, Some(kind)); return kind; } diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 48c64cd35e..9d8b651196 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -302,7 +302,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( let mut legacy_cell = None; let array = dynamic.get(c).copied().or_else(|| { let f = cell?.formula.as_ref().filter(|f| f.array.is_none())?; - match crate::array_formula::export(wb, si, *c, f, out.functions) { + match crate::array_formula::export(wb, si, *c, f, out.functions, &mut out.names) { crate::array_formula::Export::Unchanged => None, crate::array_formula::Export::Dynamic => Some(RangeRef::cell(*c)), // Every `@` is one Excel implies in a legacy formula: write it without them. diff --git a/crates/xlsx/src/tests/array_export.rs b/crates/xlsx/src/tests/array_export.rs index e1ae5af74c..112e505908 100644 --- a/crates/xlsx/src/tests/array_export.rs +++ b/crates/xlsx/src/tests/array_export.rs @@ -419,3 +419,76 @@ fn implicit_intersection_metadata_distinguishes_table_rows_and_columns() { &[("Data[@Input]*2", false), ("SUM(Data[Input])", false), ("SUM(Data[Input]*2)", true), ("SQRT(Data[Input])", true)], ); } + +/// How `export` saved a formula, as comparable text. +fn export_text(wb: &Workbook, at: CellRef, text: &str, names: &mut crate::array_formula::NameCache) -> String { + use crate::array_formula::{Export, export}; + match export(wb, 0, at, &Formula::new(text), crate::FunctionInfo::default(), names) { + Export::Unchanged => "unchanged".into(), + Export::Dynamic => "dynamic".into(), + Export::Legacy(e) => format!("legacy {}", gridcraft_formula::print(&e)), + } +} + +#[test] +fn defined_names_are_analysed_once_for_many_formulas() { + use crate::array_formula::NameCache; + let mut wb = Workbook::new(); + // A large definition: many operations, ending in a range. + let big = (1..=500).map(|i| format!("Sheet1!$A${i}")).collect::>().join("+"); + for (name, text) in [("Big", format!("({big})*Sheet1!$B$1:$B$3")), ("Rng", "Sheet1!$A$1:$A$3".to_string()), ("Alias", "Rng".to_string())] { + wb.names.push(DefinedName { name: name.into(), scope: None, formula: text, comment: String::new(), hidden: false }); + } + let texts = ["SUM(Big)", "SQRT(Big)", "Big*2", "SQRT(Alias)", "SUM(Alias)", "Alias", "SUM(Rng*2)", "Missing*2"]; + let mut shared = NameCache::default(); + for i in 0..400u32 { + for text in texts { + let at = CellRef::new(i + 10, 5); + let with_shared = export_text(&wb, at, text, &mut shared); + let fresh = export_text(&wb, at, text, &mut NameCache::default()); + assert_eq!(with_shared, fresh, "{text}"); + } + } + assert!(gridcraft_formula::parse(&wb.names[0].formula).is_ok(), "the large name must parse"); + // 3 names, each analysed once for all 3200 formulas (a fresh cache analyses a name per formula). + assert_eq!(shared.analyses, 3); +} + +#[test] +fn shared_name_analysis_keeps_each_formulas_limits_and_position() { + use crate::array_formula::NameCache; + let mut wb = Workbook::new(); + let terms = |n: usize| (1..=n).map(|i| format!("Sheet1!$A${i}")).collect::>().join("+"); + // Twenty names of about a thousand nodes each: a formula using all of them needs more than + // its 16,384-node budget, one using a few does not. + for i in 0..20 { + let text = format!("({})*Sheet1!$B$1:$B$3", terms(500)); + wb.names.push(DefinedName { name: format!("Big_{i}"), scope: None, formula: text, comment: String::new(), hidden: false }); + } + for (name, text) in [ + ("Cyc1", "Cyc2".to_string()), + ("Cyc2", "Cyc1".to_string()), + ("Deep", format!("{}1{}", "(".repeat(100), ")".repeat(100))), + ("Tbl", "Table1[Col]".to_string()), + ] { + wb.names.push(DefinedName { name: name.into(), scope: None, formula: text, comment: String::new(), hidden: false }); + } + assert!(wb.names.iter().all(|n| gridcraft_formula::parse(&n.formula).is_ok()), "every name must parse"); + let uses = |n: usize| (0..n).map(|i| format!("SQRT(Big_{i})")).collect::>().join("+"); + let mut texts: Vec = [1, 5, 10, 15, 17, 20].iter().map(|n| uses(*n)).collect(); + texts.extend(["SQRT(Big_3)", "Cyc1", "SUM(Cyc1)", "SUM(Deep)", "SQRT(Tbl)", "((((((((SQRT(Deep))))))))"].map(String::from)); + // The limit is really reached: a few uses analyse fully, all twenty stop at the budget. + let probe = |n: usize| export_text(&wb, CellRef::new(5, 5), &uses(n), &mut NameCache::default()); + assert_eq!(probe(1), "dynamic"); + assert_eq!(probe(20), "unchanged"); + let mut shared = NameCache::default(); + for round in 0..3 { + for text in &texts { + for at in [CellRef::new(5, 5), CellRef::new(7, 9)] { + let with_shared = export_text(&wb, at, text, &mut shared); + let fresh = export_text(&wb, at, text, &mut NameCache::default()); + assert_eq!(with_shared, fresh, "round {round}: {}", &text[..text.len().min(60)]); + } + } + } +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 6ba8321d8e..710777bfe1 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -128,6 +128,8 @@ pub struct Out { pub kept: crate::passthrough::KeptOut, /// Decides which formulas need dynamic-array metadata. pub functions: FunctionInfo, + /// Defined names analysed for implicit intersection, shared by every formula written. + pub(crate) names: crate::array_formula::NameCache, } impl Out { @@ -214,6 +216,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind, functions: FunctionInfo) -> Res cell_pictures: Default::default(), kept: Default::default(), functions, + names: Default::default(), }; out.default_type("rels", "application/vnd.openxmlformats-package.relationships+xml"); out.default_type("xml", "application/xml"); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 4f7d21c8b6..3815a32d1f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -29,8 +29,7 @@ and repair-free opening remain unverified. | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | | `.xlsb` Binary Workbook | R/W | **values only** (#101) | no | Names, visibility, numbers, text, booleans, errors, merges, cached formula results; no formulas, formatting, charts, names | `xlsb_tests.rs` | -| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | -| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed). Every formula is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | +| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Every formula is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | | `.xlt` Excel 97-2003 template | R/W | yes (read as `.xls`) | no | | — | | `.xlam` / `.xla` add-ins | R/W | no | no | VBA; out of scope | — | | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | diff --git a/docs/function-parity.md b/docs/function-parity.md index b83ad7f7e8..61f8ca19bc 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -77,7 +77,6 @@ PIVOTBY, REGEXTEST…) are all present. | Defined names (workbook and sheet scope), Create from Selection | done | | Dynamic arrays, spill, `#SPILL!`, spill operator `A1#` | done; stale-spill bugs (#133, #139; PRs #148, #157) | | Recalculation after clearing large sparse ranges | every stored cell changed by Clear is reported to recalculation, without a million-coordinate cutoff; removed formula spills are cleared, and removing empty merges still unblocks spills (#1032) | -| Implicit intersection `@`, legacy CSE array formulas | done; legacy array range fill (PR #156) | | Implicit intersection `@`, legacy CSE array formulas | done; legacy array range fill (PR #156). Formulas saved without dynamic-array metadata (pre-dynamic-array Excel, or no `@` needed) open with Excel's implicit `@` inserted where a range meets a single-value parameter, operator or the cell result, and calculate like Excel's cached values (cells differing from Excel's cached value: FormulaEvalTestData 205 → 11, StructuredReferences 2 → 0). T reads a reference's top-left cell | | Trim references `A1:.E10` (trailing), `A1.:E10` (leading), `A1.:.E10` (both), also on whole rows/columns (`A:.A`) | done; evaluated as `TRIMRANGE(range, code, code)`, adjusted on insert/delete; files store `_xlfn.TRIMRANGE(range,code,code)` (Excel's own file spelling unconfirmed in public docs), `_xlfn._TRO_ALL/_TRO_LEADING/_TRO_TRAILING(...)` read too | | LET, LAMBDA, named LAMBDAs, ISOMITTED, MAP/REDUCE/SCAN/BYROW/BYCOL/MAKEARRAY | done | From e32f23f54bb99838285148a3d24a6f7321644ae5 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Mon, 19 Oct 2026 21:03:44 -0500 Subject: [PATCH 09/13] Docs: say the .xls legacy-formula rule excludes Ctrl+Shift+Enter arrays Co-Authored-By: Claude Sonnet 5.5 --- docs/file-format-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3815a32d1f..636a7afe88 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -29,7 +29,7 @@ and repair-free opening remain unverified. | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | | `.xlsb` Binary Workbook | R/W | **values only** (#101) | no | Names, visibility, numbers, text, booleans, errors, merges, cached formula results; no formulas, formatting, charts, names | `xlsb_tests.rs` | -| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Every formula is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | +| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Every formula except a Ctrl+Shift+Enter array is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: fonts, fills, borders, alignment, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs` | | `.xlt` Excel 97-2003 template | R/W | yes (read as `.xls`) | no | | — | | `.xlam` / `.xla` add-ins | R/W | no | no | VBA; out of scope | — | | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | @@ -92,7 +92,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other | | 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped | -| 2026-10-14 | minor | `.xls` import: every formula is read as a legacy one with Excel's implicit `@` (a title row `=Other!A1:G1` shows its first cell instead of `#SPILL!`), one-cell Ctrl+Shift+Enter arrays stay arrays, and `.xlsx` saves keep them without `cm` (#410) | +| 2026-10-14 | minor | `.xls` import: every formula except a Ctrl+Shift+Enter array is read as a legacy one with Excel's implicit `@` (a title row `=Other!A1:G1` shows its first cell instead of `#SPILL!`), one-cell Ctrl+Shift+Enter arrays stay arrays, and `.xlsx` saves keep them without `cm` (#410) | | 2026-10-13 | minor | Legacy vs dynamic-array formulas: no `cm` reads as legacy (implicit `@` inserted), implied `@` written back without `cm` | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | From b3946f8b16ff9d16b0a1d8e579b44f9ee91264ea Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:30:06 -0500 Subject: [PATCH 10/13] Implicit @ on a 2-D range intersects row and column, as Excel does (#410) --- crates/calc/src/eval.rs | 5 +++++ crates/calc/src/tests.rs | 19 ++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4bdb3a30d4..9e3c6be55e 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -519,6 +519,11 @@ impl<'h> Evaluator<'h> { if r.height() == 1 && r.start.col <= self.at.col && self.at.col <= r.end.col { return Some(CellRef::new(r.start.row, self.at.col)); } + // A 2-D range intersects on both the formula's row and column (observed in Excel, on + // another sheet too); one that includes the formula's own cell is a circular reference. + if r.start.row <= self.at.row && self.at.row <= r.end.row && r.start.col <= self.at.col && self.at.col <= r.end.col { + return Some(self.at); + } None } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 44cdf5bf50..bc96380f41 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1885,8 +1885,8 @@ fn offset_extreme_arguments_return_ref() { } /// `@` intersects a reference with the formula's row (a column range) or column (a row range); -/// a 2D range or one the formula does not line up with gives #VALUE!. An array gives its -/// top-left value. Legacy formulas read from files use it where Excel intersects implicitly. +/// a 2D range both (circular when it includes the formula's cell); a range the formula does not +/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly. #[test] fn implicit_intersection_operator() { let mut t = T::new(); @@ -1903,9 +1903,22 @@ fn implicit_intersection_operator() { t.set("D3", "=SUM(@A1:A3)"); assert_eq!(t.num("B2"), 2f64.tanh()); assert_eq!(t.num("B7"), 5f64.tanh()); - for at in ["B3", "B9", "E9"] { + for at in ["B9", "E9"] { assert_eq!(t.get(at), Value::Error(CellError::Value), "{at}"); } + // A 2D range that includes the formula's own cell is a circular reference (Excel shows 0). + assert_eq!(t.get("B3"), Value::Error(CellError::Circ)); + // From another sheet a 2D range intersects on both row and column; outside it is #VALUE!. + t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Other"))); + for (at, input) in [("B2", "=@Sheet1!A1:C3"), ("C1", "=@Sheet1!A1:C3"), ("B9", "=@Sheet1!A1:C3"), ("E2", "=@Sheet1!A1:C3")] { + t.wb.sheet_mut(1).unwrap().cells.set(c(at), Cell::formula(Formula::new(input))); + } + t.calc.recalc_all(&mut t.wb); + let other = |at: &str| t.wb.sheet(1).unwrap().value(c(at)); + assert_eq!(other("B2"), Value::Number(2f64.tanh())); // Sheet1!B2 + assert_eq!(other("C1"), Value::Number(0.0)); + assert_eq!(other("B9"), Value::Error(CellError::Value)); + assert_eq!(other("E2"), Value::Error(CellError::Value)); assert_eq!(t.num("D1"), 7.0); assert_eq!(t.num("D2"), 2.0); assert_eq!(t.num("D3"), 3.0); From cc5c15e1f2fcf07cecb152b4156d6290d301850d Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:55:22 -0500 Subject: [PATCH 11/13] Restore legacy formula export in cell writer --- crates/xlsx/src/sheet_write.rs | 35 +++++++++++----------------------- 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 135fff7378..3eb59ca8a3 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -401,28 +401,6 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o } } s.push('>'); - for &(c, mut cell) in cells { - let ov = overrides.get(&c); - let ex = extra.get(&c); - let mut legacy_cell = None; - let array = dynamic.get(&c).copied().or_else(|| { - // A formula read with its dynamic-array mark keeps it (`cm`, see `read_formula`). - let f = cell?.formula.as_ref().filter(|f| f.array.is_none() && !f.dynamic)?; - match crate::array_formula::export(wb, si, c, f, out.functions, &mut out.names) { - crate::array_formula::Export::Unchanged => None, - crate::array_formula::Export::Dynamic => Some(RangeRef::cell(c)), - // Every `@` is one Excel implies in a legacy formula: write it without them. - crate::array_formula::Export::Legacy(e) => { - legacy_cell = cell.map(|x| Cell { formula: Some(std::sync::Arc::new(Formula::from_expr(e))), ..x.clone() }); - None - } - } - }); - if legacy_cell.is_some() { - cell = legacy_cell.as_ref(); - } - write_cell(&mut s, c, cell, sheet.cell_pictures.get(&c), ov, ex, array.as_ref(), &sid, out); - } // CT_HeaderFooter's element order. for (tag, text) in [ ("oddHeader", &p.header), @@ -635,10 +613,19 @@ fn write_sheet_data(s: &mut String, data: SheetCellData<'_>, sid: &dyn Fn(gridcr for &(cell_ref, cell) in cells { let ov = overrides.get(&cell_ref); let ex = extra.get(&cell_ref); + let mut legacy_cell = None; let array = dynamic.get(&cell_ref).copied().or_else(|| { - let f = cell?.formula.as_ref()?; - (f.array.is_none() && crate::array_formula::needs_array(workbook, index, cell_ref, f)).then_some(RangeRef::cell(cell_ref)) + let f = cell?.formula.as_ref().filter(|f| f.array.is_none() && !f.dynamic)?; + match crate::array_formula::export(workbook, index, cell_ref, f, out.functions, &mut out.names) { + crate::array_formula::Export::Unchanged => None, + crate::array_formula::Export::Dynamic => Some(RangeRef::cell(cell_ref)), + crate::array_formula::Export::Legacy(expr) => { + legacy_cell = cell.map(|x| Cell { formula: Some(std::sync::Arc::new(Formula::from_expr(expr))), ..x.clone() }); + None + } + } }); + let cell = legacy_cell.as_ref().or(cell); write_cell( s, CellWriteInput { From 0a851f47b04763e13bb7bce314e4aebab05302bf Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:45:31 +0100 Subject: [PATCH 12/13] Share a name's analysis only when it replays exactly A cached analysis records every name it read and is used only when the formula can afford its budget and nesting and has read none of those names yet; an analysis that reused a name the formula had already read (or met a cycle) is not cached. This closes the gap CodeRabbit found (a name defined as another name, in either reference order), with a test comparing shared and fresh results for export and for reading. --- crates/xlsx/src/array_formula.rs | 67 ++++++++++++++++++--------- crates/xlsx/src/tests/array_export.rs | 59 +++++++++++++++++++++++ 2 files changed, 103 insertions(+), 23 deletions(-) diff --git a/crates/xlsx/src/array_formula.rs b/crates/xlsx/src/array_formula.rs index 6b765c383a..8041929692 100644 --- a/crates/xlsx/src/array_formula.rs +++ b/crates/xlsx/src/array_formula.rs @@ -231,7 +231,7 @@ fn atomic(e: &Expr) -> bool { const MAX_DEPTH: usize = 256; /// What the analysis of one defined name leaves for a later formula that refers to it. -#[derive(Clone, Copy)] +#[derive(Clone)] struct NameInfo { kind: Kind, /// The definition reached a one-cell reference written as a range. @@ -242,16 +242,24 @@ struct NameInfo { cost: usize, /// Nesting below the reference that the analysis reached. depth: usize, + /// Every name the analysis read, with its result (itself last): a hit records them all, as a + /// fresh analysis does, so a later reference to one of them in the formula costs nothing. + closure: Vec<(NameKey, Kind, bool)>, } +/// A defined name as [`Legacy::names`] keys it: upper-case name, scope, collapsed. +type NameKey = (String, usize, bool); + /// Defined names analysed so far, shared by the formulas of one pass (reading a workbook, or /// writing one) so that a name is parsed and analysed once, not once per formula that refers -/// to it. Keyed like [`Legacy::names`]. Only analyses that finished within their limits, met no -/// cycle and did not depend on the formula's own position are kept; a later formula is charged -/// the budget and nesting the analysis used, so it reaches the same limits a fresh analysis does. +/// to it. Keyed like [`Legacy::names`]. Only analyses that finished within their limits, did not +/// depend on the formula's own position and did not reuse a name the formula had already read +/// (or meet a cycle) are kept. A hit charges the budget and nesting the analysis used and records +/// every name it read, and is taken only when the formula can afford it, so a formula reads the +/// same with the cache as without it. #[derive(Default)] pub(crate) struct NameCache { - map: HashMap<(String, usize, bool), NameInfo>, + map: HashMap, /// How many names were analysed (not found in the cache). pub(crate) analyses: usize, } @@ -265,8 +273,11 @@ struct Legacy<'a> { shared: &'a mut NameCache, /// The analysis read a structured reference without a table name, which depends on `at`. position_dependent: bool, - /// The analysis met a name defined in terms of itself. - cyclic: bool, + /// The analysis reused a name this formula had already read, or met a cycle: its result + /// leaves out what that name cost. + reused: bool, + /// The names read so far in this formula, in order, with their results. + read: Vec<(NameKey, Kind, bool)>, /// The deepest nesting reached. deepest: usize, at: CellRef, @@ -306,7 +317,8 @@ impl<'a> Legacy<'a> { wb, shared, position_dependent: false, - cyclic: false, + reused: false, + read: Vec::new(), deepest: 0, at, functions, @@ -504,28 +516,34 @@ impl<'a> Legacy<'a> { let key = (bare.to_ascii_uppercase(), scope, self.collapsed); match self.names.get(&key) { Some(Some((kind, one_cell_range))) => { + self.reused = true; self.one_cell_range |= *one_cell_range; return *kind; } Some(None) => { // A name defined in terms of itself has no legacy value to keep. self.certain = false; - self.cyclic = true; + self.reused = true; return Kind::Array; } None => {} } - if let Some(info) = self.shared.map.get(&key).copied() { - // Charged as the analysis was, so the formula meets the limits a fresh one does. - let reached = depth.saturating_add(1).saturating_add(info.depth); - self.deepest = self.deepest.max(reached); + let reached = depth.saturating_add(1); + // Taken only when the formula can afford it and has read none of the names it read: + // otherwise the fresh analysis below differs (cut short, or reusing those names). + let hit = self.shared.map.get(&key).filter(|i| { + reached + i.depth < MAX_DEPTH && i.cost <= self.remaining && i.closure.iter().all(|(k, _, _)| !self.names.contains_key(k)) + }); + if let Some(info) = hit { + // Charged and recorded as the analysis was: the formula reads as a fresh one does. + self.deepest = self.deepest.max(reached + info.depth); self.certain &= info.certain; self.one_cell_range |= info.one_cell_range; - if reached >= MAX_DEPTH || info.cost > self.remaining { - self.complete = false; + self.remaining -= info.cost; + for (k, kind, one_cell_range) in &info.closure { + self.names.insert(k.clone(), Some((*kind, *one_cell_range))); } - self.remaining = self.remaining.saturating_sub(info.cost); - self.names.insert(key, Some((info.kind, info.one_cell_range))); + self.read.extend(info.closure.iter().cloned()); return info.kind; } let Ok(expr) = gridcraft_formula::parse_name(def.formula.trim_start_matches('=')) else { return Kind::Array }; @@ -535,31 +553,34 @@ impl<'a> Legacy<'a> { let locals = std::mem::take(&mut self.locals); let seen = std::mem::replace(&mut self.one_cell_range, false); let before = self.remaining; + let first_read = self.read.len(); let outer = ( std::mem::replace(&mut self.certain, true), std::mem::replace(&mut self.complete, true), std::mem::replace(&mut self.position_dependent, false), - std::mem::replace(&mut self.cyclic, false), + std::mem::replace(&mut self.reused, false), std::mem::replace(&mut self.deepest, 0), ); let kind = self.kind_of(expr, def.scope.unwrap_or(scope), depth + 1); let one_cell_range = std::mem::replace(&mut self.one_cell_range, seen); - let info = NameInfo { + self.read.push((key.clone(), kind, one_cell_range)); + let cacheable = self.complete && !self.position_dependent && !self.reused; + let info = cacheable.then(|| NameInfo { kind, one_cell_range, certain: self.certain, cost: before.saturating_sub(self.remaining), depth: self.deepest.saturating_sub(depth + 1), - }; - let cacheable = self.complete && !self.position_dependent && !self.cyclic; + closure: self.read[first_read..].to_vec(), + }); self.certain &= outer.0; self.complete &= outer.1; self.position_dependent |= outer.2; - self.cyclic |= outer.3; + self.reused |= outer.3; self.deepest = self.deepest.max(outer.4); self.one_cell_range |= one_cell_range; self.locals = locals; - if cacheable && self.shared.map.len() < MAX_CACHED_NAMES { + if let Some(info) = info.filter(|_| self.shared.map.len() < MAX_CACHED_NAMES) { self.shared.map.insert(key.clone(), info); } self.names.insert(key, Some((kind, one_cell_range))); diff --git a/crates/xlsx/src/tests/array_export.rs b/crates/xlsx/src/tests/array_export.rs index b9a3ad45fb..9e60f03738 100644 --- a/crates/xlsx/src/tests/array_export.rs +++ b/crates/xlsx/src/tests/array_export.rs @@ -540,6 +540,65 @@ fn shared_name_analysis_keeps_each_formulas_limits_and_position() { } } +/// A name defined as another name reads the same from the shared cache in either order: after +/// the other name (whose cost and uncertainty the formula already paid) and before it (a hit +/// records the other name too, so the formula does not pay for it twice). +#[test] +fn shared_name_analysis_of_names_defined_by_names_matches_fresh_in_both_orders() { + use crate::array_formula::NameCache; + let mut wb = Workbook::new(); + let terms = (1..=500).map(|i| format!("Sheet1!$A${i}")).collect::>().join("+"); + // `Unsure` is outside the established legacy semantics (ISOMITTED), and `Alias` is it by name. + let mut defs = vec![ + ("Unsure".to_string(), "IF(ISOMITTED(Sheet1!$C$1),Sheet1!$A$1:$A$3,Sheet1!$B$1:$B$3)".to_string()), + ("Alias".to_string(), "Unsure".to_string()), + ]; + for i in 0..10 { + defs.push((format!("Big_{i}"), format!("({terms})*Sheet1!$B$1:$B$3"))); + defs.push((format!("Via_{i}"), format!("Big_{i}"))); + } + for (name, formula) in defs { + wb.names.push(DefinedName { name, scope: None, formula, comment: String::new(), hidden: false }); + } + // Ten names of about a thousand nodes, each reached twice: within the budget only if the + // second reference is free. + let both = |first: &str, second: &str| (0..10).map(|i| format!("SQRT({first}_{i})+SQRT({second}_{i})")).collect::>().join("+"); + let orders = [ + ["Unsure+SQRT(Alias)", "SQRT(Alias)+Unsure", "SQRT(Alias)+SQRT(Sheet1!$A$1:$A$3)", "@SQRT(Alias)"].map(String::from).to_vec(), + ["SQRT(Alias)", "SQRT(Alias)+Unsure", "Unsure+SQRT(Alias)", "SQRT(Alias)+SQRT(Sheet1!$A$1:$A$3)", "@SQRT(Alias)"].map(String::from).to_vec(), + vec![both("Big", "Via"), both("Via", "Big"), "SQRT(Via_0)".to_string(), both("Via", "Big")], + vec!["SQRT(Via_0)".to_string(), both("Via", "Big"), both("Big", "Via"), both("Via", "Big")], + ]; + let at = CellRef::new(5, 5); + assert_eq!(export_text(&wb, at, &both("Via", "Big"), &mut NameCache::default()), "dynamic", "fresh fits the budget"); + for texts in orders { + let mut shared = NameCache::default(); + for text in &texts { + let with_shared = export_text(&wb, at, text, &mut shared); + let fresh = export_text(&wb, at, text, &mut NameCache::default()); + assert_eq!(with_shared, fresh, "{}", &text[..text.len().min(60)]); + } + // Reading: one pass over the formulas, one row each, against each formula read alone. + let read = |cells: &[(CellRef, &String)], one_pass: bool| -> Vec { + let mut wb = wb.clone(); + for (c, text) in cells { + Arc::make_mut(&mut wb.sheets[0]).cells.set(*c, Cell::formula(Formula::new(text))); + } + let all: Vec = cells.iter().map(|(c, _)| *c).collect(); + if one_pass { + crate::array_formula::apply_legacy(&mut wb, vec![(0, all.clone())], crate::FunctionInfo::default()); + } else { + for c in &all { + crate::array_formula::apply_legacy(&mut wb, vec![(0, vec![*c])], crate::FunctionInfo::default()); + } + } + all.iter().map(|c| gridcraft_formula::print(&wb.sheets[0].cells.get(*c).unwrap().formula.as_ref().unwrap().expr_arc().unwrap())).collect() + }; + let cells: Vec<(CellRef, &String)> = texts.iter().enumerate().map(|(i, t)| (CellRef::new(i as u32 + 5, 5), t)).collect(); + assert_eq!(read(&cells, true), read(&cells, false)); + } +} + #[test] fn long_flat_chains_are_scalar_formulas() { // `=A1+A2+…` nests one level per operator. Past the scan's depth limit of 64, a plain sum From 4bc7a251c2ff0ce3869defca02267eb594b21fc1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:46:08 +0100 Subject: [PATCH 13/13] Document .xls legacy formulas in the file format parity table --- docs/file-format-parity.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 12597f313b..40942a539b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,7 +92,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | | `.xlsb` Binary Workbook | R/W | **values only** (#101) | no | Names, visibility, numbers, text, booleans, errors, merges, cached formula results; no formulas, formatting, charts, names | `xlsb_tests.rs` | -| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), cell formatting (fonts, solid and pattern fills, borders with diagonals, alignment with rotation, indent, wrap and shrink, locked and hidden, the custom colour palette, the Normal font as the workbook default, user-defined cell styles), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Not read: exact colours beyond the 56-colour palette (XFExt: theme colours and tints show as the palette colour Excel stored next to them), rich-text runs inside a cell, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs`, `xls_style_tests.rs` | +| `.xls` Excel 97-2003 (BIFF8) | R/W | **yes, partial** (#121) | no (Save As `.xlsx`) | Clean-room from [MS-CFB] and [MS-XLS]. Read: worksheets and visibility, shared strings, numbers, text, booleans, errors, formulas (text for the common tokens, shared and array formulas, 3-D refs, names, newer functions called by name) with cached results, number formats (dates display as dates), cell formatting (fonts, solid and pattern fills, borders with diagonals, alignment with rotation, indent, wrap and shrink, locked and hidden, the custom colour palette, the Normal font as the workbook default, user-defined cell styles), 1904 date system, merges, column widths, row heights, defined names, print area and titles, calculation settings (mode, iteration with its maximum iterations and change, precision as displayed), sheet display options (right-to-left, gridlines, headings, zero values, formulas; a truncated WINDOW2 is ignored). Every formula except a Ctrl+Shift+Enter array is a legacy one and opens with Excel's implicit `@`, as an `.xlsx` formula without `cm` does (#410); Ctrl+Shift+Enter arrays, one cell or several, stay arrays, and saving as `.xlsx` writes the formulas without `cm`. Not read: exact colours beyond the 56-colour palette (XFExt: theme colours and tints show as the palette colour Excel stored next to them), rich-text runs inside a cell, charts, pictures, comments, CF, validation, hyperlinks, freeze panes, external links (formula kept as its value). Chart and macro sheets skipped with a warning; encrypted (FILEPASS) and BIFF5 (Excel 5.0/95) files refused with a message. Opens as a new unsaved workbook. Unverified on a real-world corpus | `xls_tests.rs`, `xls_style_tests.rs` | | `.xlt` Excel 97-2003 template | R/W | yes (read as `.xls`) | no | | — | | `.xlam` / `.xla` add-ins | R/W | no | no | VBA; out of scope | — | | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | @@ -161,6 +161,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | `.xls` import: every formula except a Ctrl+Shift+Enter array is read as a legacy one with Excel's implicit `@` (a title row `=Other!A1:G1` shows its first cell instead of `#SPILL!`), one-cell Ctrl+Shift+Enter arrays stay arrays, and `@` of a 2-D range meets the formula's row and column (#410, PR #1367) | | 2026-11-02 | minor | XLSX: buttons, scroll bars and spin buttons read and written (control properties parts, ``, VML `x:ClientData`); other form controls stay with pass-through; a button's command, fixed input or output cell travels in a hidden defined name and comes back only while the file still assigns the button's macro (or none, for a command) | | 2026-11-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) |