From 2a5d9e562af96b7f11d016ecdcda109491acef38 Mon Sep 17 00:00:00 2001 From: Raleigh Dexel <89496124+rdexel@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:26:37 -0800 Subject: [PATCH] formula: a sheet-qualified #REF! keeps the sheet it pointed into Excel writes a reference whose cells were deleted as `Sheet1!#REF!`, shows it that way and renames the sheet there with the others. GridCraft parsed it as a bare `#REF!`, so opening and saving rewrote every such formula and defined name: 249 formulas and 26 names in one 57-sheet databook, with no edit made. `Expr::SheetRefError(SheetSel)` keeps the sheet: it prints back as it was read (quoted like any sheet name), `rename_sheet` renames it, `delete_sheet` collapses it to a bare `#REF!`, and it evaluates to `#REF!`. The .xls reader keeps the sheet of PtgRefErr3d and PtgAreaErr3d when their link still resolves. Co-Authored-By: Claude Opus 5 (1M context) --- crates/calc/src/eval.rs | 2 ++ crates/formula/src/adjust.rs | 35 ++++++++++++++++++++---------- crates/formula/src/ast.rs | 6 +++++ crates/formula/src/parser.rs | 3 ++- crates/formula/src/printer.rs | 6 ++++- crates/formula/src/tests.rs | 24 ++++++++++++++++++++ crates/xlsx/src/fmla.rs | 1 + crates/xlsx/src/tests/roundtrip.rs | 23 ++++++++++++++++++++ crates/xlsx/src/tests/xls_tests.rs | 6 +++++ crates/xlsx/src/xls/formula.rs | 20 +++++++++++++---- 10 files changed, 108 insertions(+), 18 deletions(-) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 7a957f3a4a..4b94afa2b0 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -320,6 +320,8 @@ impl<'h> Evaluator<'h> { Expr::Text(t) => Ev::V(Value::Text(t.clone())), Expr::Bool(b) => Ev::V(Value::Bool(*b)), Expr::Error(x) => err(*x), + // `Sheet1!#REF!` keeps the sheet it pointed into, and is the `#REF!` it prints as. + Expr::SheetRefError(_) => err(CellError::Ref), Expr::Missing => Ev::V(Value::Empty), Expr::Paren(x) => self.eval(x), Expr::Array(rows) => { diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 319474b4ef..62b78b965d 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -246,22 +246,31 @@ fn adjust_ref(r: &Reference, edit: &Edit) -> Option { } } +fn rename_in(sheet: &mut SheetSel, old: &str, new: &str) { + match sheet { + SheetSel::Named(n) if n.eq_ignore_ascii_case(old) => *n = new.to_string(), + SheetSel::Span(a, b) => { + if a.eq_ignore_ascii_case(old) { + *a = new.to_string(); + } + if b.eq_ignore_ascii_case(old) { + *b = new.to_string(); + } + } + _ => {} + } +} + /// Renames sheet references `old` → `new`. pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr { e.map(&mut |x| match x { + // `Sheet1!#REF!` names its sheet like any reference, so it is renamed with them. + Expr::SheetRefError(mut sheet) => { + rename_in(&mut sheet, old, new); + Expr::SheetRefError(sheet) + } Expr::Ref(mut r) => { - match &mut r.sheet { - SheetSel::Named(n) if n.eq_ignore_ascii_case(old) => *n = new.to_string(), - SheetSel::Span(a, b) => { - if a.eq_ignore_ascii_case(old) { - *a = new.to_string(); - } - if b.eq_ignore_ascii_case(old) { - *b = new.to_string(); - } - } - _ => {} - } + rename_in(&mut r.sheet, old, new); Expr::Ref(r) } // Sheet-qualified defined name `Old!MyName` is stored as one string, with the bare sheet name as the parser @@ -279,6 +288,8 @@ pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr { pub fn delete_sheet(e: Expr, name: &str, order: &[String]) -> Expr { let pos = |n: &str| order.iter().position(|o| o.eq_ignore_ascii_case(n)); e.map(&mut |x| match x { + // The sheet a `Sheet1!#REF!` names going away leaves a bare `#REF!`, as for a reference. + Expr::SheetRefError(SheetSel::Named(n)) if n.eq_ignore_ascii_case(name) => Expr::Error(CellError::Ref), Expr::Ref(r) if r.sheet_name().is_some_and(|n| n.eq_ignore_ascii_case(name)) => Expr::Error(CellError::Ref), Expr::Ref(mut r) => { if let SheetSel::Span(a, b) = &r.sheet diff --git a/crates/formula/src/ast.rs b/crates/formula/src/ast.rs index 94756c09f1..487c07b267 100644 --- a/crates/formula/src/ast.rs +++ b/crates/formula/src/ast.rs @@ -197,6 +197,10 @@ pub enum Expr { /// Array constant `{1,2;3,4}` (rows of literal expressions). Array(Vec>), Ref(Reference), + /// `Sheet1!#REF!`: a reference whose cells were deleted, which keeps the sheet it pointed + /// into. Excel writes and shows it that way, and renames the sheet here with the others; it + /// evaluates to `#REF!`. A bare `#REF!` is [`Expr::Error`]. + SheetRefError(SheetSel), /// Defined name, table name or LET/LAMBDA parameter. Name(String), Struct(StructRef), @@ -297,6 +301,7 @@ impl Clone for Expr { Expr::Error(e) => Expr::Error(*e), Expr::Array(rows) => Expr::Array(rows.clone()), Expr::Ref(r) => Expr::Ref(r.clone()), + Expr::SheetRefError(s) => Expr::SheetRefError(s.clone()), Expr::Name(n) => Expr::Name(n.clone()), Expr::Struct(s) => Expr::Struct(s.clone()), Expr::Unary(op, e) => Expr::Unary(*op, e.clone()), @@ -336,6 +341,7 @@ impl PartialEq for Expr { (Expr::Error(a), Expr::Error(b)) => break a == b, (Expr::Array(a), Expr::Array(b)) => break a == b, (Expr::Ref(a), Expr::Ref(b)) => break a == b, + (Expr::SheetRefError(a), Expr::SheetRefError(b)) => break a == b, (Expr::Name(a), Expr::Name(b)) => break a == b, (Expr::Struct(a), Expr::Struct(b)) => break a == b, (Expr::Unary(o1, a), Expr::Unary(o2, b)) => break o1 == o2 && a == b, diff --git a/crates/formula/src/parser.rs b/crates/formula/src/parser.rs index f906c4782e..b5f60e7887 100644 --- a/crates/formula/src/parser.rs +++ b/crates/formula/src/parser.rs @@ -331,7 +331,8 @@ impl Parser { }; match self.next() { Tok::Word(w) => self.reference_from_word(sheet, &w), - Tok::Error(CellError::Ref) => Ok(Expr::Error(CellError::Ref)), + // `Sheet1!#REF!`: the cells are gone but the sheet is still named. + Tok::Error(CellError::Ref) => Ok(Expr::SheetRefError(sheet)), t => Err(self.err(format!("expected a reference after the sheet name, found {}", describe(&t)))), } } diff --git a/crates/formula/src/printer.rs b/crates/formula/src/printer.rs index bddbfebf28..61e7817942 100644 --- a/crates/formula/src/printer.rs +++ b/crates/formula/src/printer.rs @@ -2,7 +2,7 @@ use std::fmt::Write; -use gridcraft_core::{CellRef, number_to_text}; +use gridcraft_core::{CellError, CellRef, number_to_text}; use crate::ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, UnOp}; @@ -239,6 +239,10 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option) { } Expr::Bool(b) => s.push_str(if *b { "TRUE" } else { "FALSE" }), Expr::Error(err) => s.push_str(err.as_str()), + Expr::SheetRefError(sheet) => { + s.push_str(&sheet_prefix(sheet)); + s.push_str(CellError::Ref.as_str()); + } Expr::Array(rows) => { s.push('{'); for (ri, row) in rows.iter().enumerate() { diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index 8b8215455b..e630260402 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -567,3 +567,27 @@ fn column_starting_with_at_round_trips() { assert_eq!(parse(&text).ok(), Some(Expr::Struct(s)), "printed as {text}"); } } + +#[test] +fn sheet_qualified_ref_error_keeps_its_sheet() -> Result<(), Box> { + // Excel writes a reference whose cells were deleted as `Sheet!#REF!`, keeping the sheet it + // pointed into: the formula bar shows `='Data Sheet'!#REF!`, and renaming that sheet renames + // it there too (observed in Excel 365 for Mac). + assert_eq!(rt("'Data Sheet'!#REF!"), "'Data Sheet'!#REF!"); + assert_eq!(rt("Data!#REF!"), "Data!#REF!"); + assert_eq!(rt("'IS Base'!#REF!-E13"), "'IS Base'!#REF!-E13"); + assert_eq!(rt("SUM(Data!#REF!,1)"), "SUM(Data!#REF!,1)"); + assert_eq!(rt("'It''s'!#REF!"), "'It''s'!#REF!"); + // A bare `#REF!` stays bare, and a 3-D span keeps both ends. + assert_eq!(rt("#REF!"), "#REF!"); + assert_eq!(rt("Jan:Dec!#REF!"), "Jan:Dec!#REF!"); + // Renaming the sheet it names renames it here too; deleting that sheet leaves a bare `#REF!`. + assert_eq!(print(&rename_sheet(parse("'Data Sheet'!#REF!")?, "data sheet", "Renamed Tab")), "'Renamed Tab'!#REF!"); + assert_eq!(print(&rename_sheet(parse("Other!#REF!")?, "Data", "Renamed")), "Other!#REF!"); + assert_eq!(print(&crate::adjust::delete_sheet(parse("Data!#REF!+1")?, "Data", &[])), "#REF!+1"); + // Two of them are the same formula only when they name the same sheet. + assert_eq!(parse("Data!#REF!")?, parse("Data!#REF!")?); + assert_ne!(parse("Data!#REF!")?, parse("Other!#REF!")?); + assert_ne!(parse("Data!#REF!")?, parse("#REF!")?); + Ok(()) +} diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index 29dd20870b..16d1458ac5 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -226,6 +226,7 @@ fn unwrap_dummy_functions(e: Expr, known: &dyn Fn(&str) -> bool) -> Option | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) + | Expr::SheetRefError(_) | Expr::Paren(_) | Expr::Array(_) | Expr::Struct(_)), diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 4eb6c3cfe2..605de09b66 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1741,3 +1741,26 @@ fn remove_personal_information_is_kept_and_honoured() { assert_eq!(book.child("workbookPr").and_then(|p| p.attr("filterPrivacy")), None); assert!(String::from_utf8(pkg.read("docProps/core.xml").unwrap().unwrap()).unwrap().contains("Jane Example")); } + +/// Excel writes a reference whose cells were deleted as `Sheet1!#REF!`, in cell formulas and in +/// defined names, and keeps the sheet it pointed into. Reading it as a bare `#REF!` rewrites +/// every such formula on save. +#[test] +fn a_sheet_qualified_ref_error_keeps_its_sheet_through_a_round_trip() { + let mut wb = Workbook::new(); + wb.sheets.push(Arc::new(Sheet::new("Data Sheet"))); + let s = wb.sheet_mut(0).unwrap(); + s.cells.set(at("A1"), Cell::formula(Formula::new("'Data Sheet'!#REF!"))); + s.cells.set(at("A2"), Cell::formula(Formula::new("'Data Sheet'!#REF!-A3"))); + s.cells.set(at("A3"), Cell::formula(Formula::new("#REF!"))); + wb.names.push(DefinedName { name: "Gone".into(), scope: None, formula: "'Data Sheet'!#REF!".into(), comment: String::new(), hidden: false }); + + let (back, rep) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert!(rep.warnings.is_empty(), "{:?}", rep.warnings); + let s = back.sheet(0).unwrap(); + let text = |a: &str| s.cell(at(a)).unwrap().formula.as_ref().unwrap().text.to_string(); + assert_eq!(text("A1"), "'Data Sheet'!#REF!"); + assert_eq!(text("A2"), "'Data Sheet'!#REF!-A3"); + assert_eq!(text("A3"), "#REF!", "a bare #REF! stays bare"); + assert_eq!(back.names.first().expect("the name survived").formula, "'Data Sheet'!#REF!"); +} diff --git a/crates/xlsx/src/tests/xls_tests.rs b/crates/xlsx/src/tests/xls_tests.rs index bd21b49390..4c3baf97cf 100644 --- a/crates/xlsx/src/tests/xls_tests.rs +++ b/crates/xlsx/src/tests/xls_tests.rs @@ -238,6 +238,8 @@ fn sample(date1904: bool) -> Vec { let round = cat(&[&ptg_ref(0, 1), &ptg_int(0), &[0x41], &27u16.to_le_bytes()]); let name_ref = cat(&[&[0x43], &1u32.to_le_bytes(), &ptg_int(2), &[0x05]]); let ref3d = cat(&[&[0x5A], &1u16.to_le_bytes(), &u16s(&[0, 0xC000])]); + // PtgRefErr3d into the same link: a cell deleted on `Data`, which is still there. + let ref_err3d = cat(&[&[0x3C], &1u16.to_le_bytes(), &u16s(&[0, 0])]); let sheet1 = cat(&[ &bof(0x0010), &rec(0x0225, &u16s(&[0, 255])), @@ -259,6 +261,7 @@ fn sample(date1904: bool) -> Vec { &formula(2, 5, num(2.0), &round), &formula(2, 6, num(7.0), &ref3d), &formula(2, 7, special(2, 0x2A), &[0x1C, 0x2A]), + &formula(2, 8, special(2, 0x17), &ref_err3d), &rec(0x0203, &cat(&[&cell(3, 0, 1), &0.0f64.to_le_bytes()])), &rec(0x0203, &cat(&[&cell(3, 1, 2), &0.25f64.to_le_bytes()])), &rec(0x027E, &cat(&[&cell(4, 0, 0), &((1u32 << 2) | 2).to_le_bytes()])), @@ -340,6 +343,9 @@ fn assert_formula_roundtrip(wb: &gridcraft_model::Workbook) { assert_eq!(ftext(wb, "F3").as_deref(), Some("ROUND(B1,0)")); assert_eq!(ftext(wb, "G3").as_deref(), Some("Data!A1")); assert_eq!(v(wb, 0, "H3"), Value::Error(CellError::NA)); + // A cell deleted on a sheet that is still there keeps the sheet (PtgRefErr3d). + assert_eq!(ftext(wb, "I3").as_deref(), Some("Data!#REF!")); + assert_eq!(v(wb, 0, "I3"), Value::Error(CellError::Ref)); // Shared formula: relative offsets resolve per cell. assert_eq!(ftext(wb, "B5").as_deref(), Some("A5*10")); assert_eq!(ftext(wb, "B6").as_deref(), Some("A6*10")); diff --git a/crates/xlsx/src/xls/formula.rs b/crates/xlsx/src/xls/formula.rs index 3de8607077..0bce3ab79b 100644 --- a/crates/xlsx/src/xls/formula.rs +++ b/crates/xlsx/src/xls/formula.rs @@ -204,6 +204,13 @@ fn pop_n(stack: &mut Stack, n: usize, kids: &mut usize) -> Result, Uns } /// Pushes the result of a token one level above the operands it consumed. +fn sheet_ref_error(sheet: Result, Unsupported>) -> Expr { + match sheet { + Ok(Some(sheet)) => Expr::SheetRefError(sheet), + _ => Expr::Error(CellError::Ref), + } +} + fn push(stack: &mut Stack, kids: usize, e: Expr) -> Result<(), Unsupported> { let depth = kids.saturating_add(1); if depth > MAX_DEPTH { @@ -402,13 +409,18 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], base: CellRef, mode: Mode, links: }, )?; } + // PtgRefErr3d / PtgAreaErr3d: a deleted cell or range on a sheet that is still + // there. The sheet is kept (`Sheet1!#REF!`); one in another workbook, or on a sheet + // that is gone too, stays a bare `#REF!`. 0x3C => { - t.take(6)?; - push(&mut stack, kids, Expr::Error(CellError::Ref))?; + let ixti = t.u16()?; + t.take(4)?; + push(&mut stack, kids, sheet_ref_error(links.sheet_sel(ixti)))?; } 0x3D => { - t.take(10)?; - push(&mut stack, kids, Expr::Error(CellError::Ref))?; + let ixti = t.u16()?; + t.take(8)?; + push(&mut stack, kids, sheet_ref_error(links.sheet_sel(ixti)))?; } 0x01 => return Err(Unsupported("nested shared or array formula reference")), 0x02 => return Err(Unsupported("what-if data tables")),