mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-03 22:41:38 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
623061303f | ||
|
|
c05683be93 |
@@ -141,6 +141,11 @@ pub trait Host {
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
range.iter().map(|c| self.cell_value(sheet, c)).collect()
|
||||
}
|
||||
/// Finds the smallest rectangle covering the non-empty cells of a block without reading its
|
||||
/// full grid. The outer `None` leaves the read to `range_values`. `Some(None)` means all blank.
|
||||
fn range_nonempty_bounds(&mut self, _sheet: usize, _range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
None
|
||||
}
|
||||
/// The sheet's used range (`Sheet::used_range`, which walks every stored row). Hosts that
|
||||
/// keep the workbook unchanged while evaluating can remember it.
|
||||
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
|
||||
|
||||
@@ -915,6 +915,70 @@ pub(crate) mod tests {
|
||||
assert!(!index_spills(5_000, 5_000, [].iter()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_references_skip_the_dense_grid_for_sparse_stored_values() {
|
||||
use crate::eval::{Area, Ev, Evaluator};
|
||||
use gridcraft_core::CellError;
|
||||
use gridcraft_model::StyleId;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
sh.set_cell(at("C3"), Cell::value(Value::Number(0.0)));
|
||||
let mut cached = Cell::formula(Formula::new("\"\""));
|
||||
cached.value = Value::text("");
|
||||
sh.set_cell(at("N39999"), cached);
|
||||
sh.set_cell(at("Q40001"), Cell::styled(Value::Empty, StyleId(1)));
|
||||
// These cells keep the sheet's used extent wide and tall without being in the trim range.
|
||||
sh.set_cell(at("Q1"), Cell::value(Value::Number(1.0)));
|
||||
sh.set_cell(at("A40001"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let mut ev = Evaluator::new(&mut host, 0, at("S1"));
|
||||
for (src, expected) in [("B2.:.Q40001", "C3:N39999"), ("TRIMRANGE(B2:Q40001,1,2)", "B3:N40001")] {
|
||||
let expr = gridcraft_formula::parse(src).unwrap();
|
||||
let result = ev.eval(&expr);
|
||||
let area = Area { sheet: 0, range: RangeRef::parse(expected).unwrap() };
|
||||
assert!(matches!(&result, Ev::R(areas) if areas.as_slice() == [area]), "{src}: {result:?}");
|
||||
}
|
||||
let blank = gridcraft_formula::parse("TRIMRANGE(O2:Q40001)").unwrap();
|
||||
assert!(matches!(ev.eval(&blank), Ev::V(Value::Error(CellError::Calc))));
|
||||
assert_eq!(host.materialized_range_cells, 0, "bounds reads must not allocate a dense grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_range_includes_a_spill_from_outside_the_block() {
|
||||
use crate::eval::Evaluator;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
let anchor = (0, at("C1"));
|
||||
let target = at("I1");
|
||||
let source = Formula::new("SEQUENCE(2,5)");
|
||||
let consumer = Formula::new("COLUMNS(TRIMRANGE(C2:G4))");
|
||||
let exprs = [(anchor, source.expr_arc().unwrap()), ((0, target), consumer.expr_arc().unwrap())].into_iter().collect();
|
||||
sh.set_cell(anchor.1, Cell::formula(source));
|
||||
sh.set_cell(target, Cell::formula(consumer));
|
||||
// Extend the read area before the new spill has been committed to the sheet.
|
||||
sh.set_cell(at("H5"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
host.calculate(anchor);
|
||||
host.calculate((0, target));
|
||||
assert_eq!(host.results.get(&(0, target)), Some(&Value::Number(5.0)), "new spill in the current pass");
|
||||
|
||||
Calc::new().recalc_all(&mut wb);
|
||||
let exprs = HashMap::default();
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let consumer = gridcraft_formula::parse("COLUMNS(TRIMRANGE(C2:G4))").unwrap();
|
||||
let result = Evaluator::new(&mut host, 0, target).value(&consumer);
|
||||
assert_eq!(result, Value::Number(5.0), "stored spill from a completed recalculation");
|
||||
}
|
||||
|
||||
/// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already
|
||||
/// spilled on the sheet from the last calculation, as a full recalculation finds them.
|
||||
fn big_python_spill() -> (Workbook, HashMap<Key, Value>) {
|
||||
|
||||
@@ -57,6 +57,9 @@ pub(super) struct PassHost<'a> {
|
||||
/// looks at none of it).
|
||||
#[cfg(test)]
|
||||
pub(super) spill_visits: usize,
|
||||
/// Number of value slots allocated by dense range reads.
|
||||
#[cfg(test)]
|
||||
pub(super) materialized_range_cells: usize,
|
||||
/// The formulas in `cycles`.
|
||||
cycle_seen: HashSet<Key>,
|
||||
/// Iterative calculation: a circular reference reads the cell's previous value instead of
|
||||
@@ -114,6 +117,8 @@ impl<'a> PassHost<'a> {
|
||||
suspensions: 0,
|
||||
#[cfg(test)]
|
||||
spill_visits: 0,
|
||||
#[cfg(test)]
|
||||
materialized_range_cells: 0,
|
||||
cycle_seen: HashSet::default(),
|
||||
iterate: false,
|
||||
prev: HashMap::default(),
|
||||
@@ -238,6 +243,25 @@ fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &m
|
||||
}
|
||||
|
||||
impl PassHost<'_> {
|
||||
fn range_has_spill(&mut self, sheet: usize, range: RangeRef) -> bool {
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
if !arrays.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return false };
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would
|
||||
/// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is
|
||||
/// calculated from here, then the suspended ones again (reading the results kept so far).
|
||||
@@ -609,6 +633,10 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
let (h, w) = (range.height() as usize, range.width() as usize);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.materialized_range_cells += h * w;
|
||||
}
|
||||
let mut out = vec![Value::Empty; h * w];
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return out };
|
||||
// Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go
|
||||
@@ -698,18 +726,7 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
// Spilled values sit between the stored cells (and the formulas just calculated may have
|
||||
// produced some): leave such blocks to `range_values`.
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
if !arrays.is_empty() || stored {
|
||||
if self.range_has_spill(sheet, range) {
|
||||
return false;
|
||||
}
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
@@ -720,6 +737,32 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
if self.iterate || self.range_has_spill(sheet, range) {
|
||||
return None;
|
||||
}
|
||||
let sh = self.wb.sheet(sheet)?;
|
||||
// When fewer calculations are in play than cells to inspect, check their coordinates
|
||||
// first. A formula near the bottom of a dense range would otherwise cost two walks.
|
||||
let pass_cells = self.pending.len() + self.results.len();
|
||||
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
|
||||
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
|
||||
return None;
|
||||
}
|
||||
let mut bounds: Option<RangeRef> = None;
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
// With no pending or computed results in the block, formula and Python readers
|
||||
// see the stored values as well. Otherwise leave their evaluation to range_values.
|
||||
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
|
||||
return None;
|
||||
}
|
||||
if !cell.value.is_empty() {
|
||||
let cell_range = RangeRef::cell(c);
|
||||
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
|
||||
}
|
||||
}
|
||||
Some(bounds)
|
||||
}
|
||||
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
|
||||
// Constants can't change during a pass, so a block's result stays valid for it. Spills
|
||||
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
|
||||
|
||||
@@ -2497,6 +2497,21 @@ fn blank_lookup_values_match_excel_windows_observation() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_blank_lookup_argument_is_numeric_zero() {
|
||||
// #4044: `XMATCH(, array)` writes a blank argument, which Excel reads as numeric zero. Only a
|
||||
// reference to a blank cell (B1 here) is a blank lookup value.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=XMATCH(,{0,1,3})");
|
||||
t.set("A2", "=XMATCH(B1,{0,1,3})");
|
||||
t.set("A3", "=XLOOKUP(,{0,1,3},{10,20,30})");
|
||||
t.set("A4", "=XLOOKUP(B1,{0,1,3},{10,20,30},\"none\")");
|
||||
assert_eq!(t.get("A1"), Value::Number(1.0));
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::NA));
|
||||
assert_eq!(t.get("A3"), Value::Number(10.0));
|
||||
assert_eq!(t.get("A4"), Value::from("none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_width_is_the_column_width_dialog_value_rounded() {
|
||||
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
|
||||
|
||||
@@ -95,8 +95,15 @@ impl Evaluator<'_> {
|
||||
if (h as u64) * (w as u64) > MAX_CELLS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
|
||||
let ((r0, r1), (c0, c1)) = if let Some(nonempty) = self.host.range_nonempty_bounds(a.sheet, part) {
|
||||
let nonempty = nonempty.ok_or(CellError::Calc)?;
|
||||
let row = |c: CellRef| (c.row - part.start.row) as usize;
|
||||
let col = |c: CellRef| (c.col - part.start.col) as usize;
|
||||
((row(nonempty.start), row(nonempty.end)), (col(nonempty.start), col(nonempty.end)))
|
||||
} else {
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
bounds(&values, w).ok_or(CellError::Calc)?
|
||||
};
|
||||
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
|
||||
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
|
||||
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
|
||||
|
||||
@@ -23,6 +23,19 @@ fn needle(args: &[Arg], i: usize) -> R<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup value of XLOOKUP and XMATCH. Unlike the older lookups, a reference to a blank cell is
|
||||
/// blank rather than numeric zero: it matches a blank entry and nothing else (#4044). A written
|
||||
/// blank argument (`XMATCH(, array)`) still becomes zero, as MATCH does.
|
||||
fn xneedle(args: &[Arg], i: usize) -> R<Value> {
|
||||
let a = arg(args, i)?;
|
||||
match a.value.scalar() {
|
||||
Value::Error(e) => Err(e),
|
||||
Value::Empty if a.from_ref || a.blank_value => Ok(Value::Empty),
|
||||
Value::Empty => Ok(Value::Number(0.0)),
|
||||
v => Ok(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// Order of two values for the approximate and binary searches: [`compare`], except that numbers
|
||||
/// compare exactly. Excel's `=` treats numbers equal to 15 significant digits as equal, but its
|
||||
/// lookups don't. Observed in Excel 365 with A1 holding
|
||||
@@ -233,6 +246,12 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
if search_mode.abs() == 2 {
|
||||
let desc = search_mode == -2;
|
||||
// A blank needle only matches a blank entry. The coercing comparison would read it as
|
||||
// numeric zero, so the exact result stands even when it finds nothing: the approximate
|
||||
// probes must not fall through to a zero (#4044).
|
||||
if matches!(x, Value::Empty) {
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
}
|
||||
if match_mode == 2 {
|
||||
// Wildcards are not supported with binary search: Excel falls back to exact.
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
@@ -292,13 +311,20 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
|
||||
fn bsearch_exact(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
|
||||
if matches!(x, Value::Empty) {
|
||||
// A blank needle only matches a blank entry. The coercing comparison below would read it
|
||||
// as numeric zero, so handle it here: blanks sort last in both directions, so the first
|
||||
// blank entry is the only possible exact match.
|
||||
let p = hay.partition_point(|v| !matches!(v, Value::Empty));
|
||||
return matches!(hay.get(p)?, Value::Empty).then_some(p);
|
||||
}
|
||||
let p = bsearch_first(x, hay, desc)?;
|
||||
let v = hay.get(p)?;
|
||||
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
|
||||
}
|
||||
|
||||
fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -344,7 +370,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
}
|
||||
|
||||
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -567,6 +593,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
mod tests {
|
||||
use gridcraft_core::{CellError, Value};
|
||||
|
||||
use crate::Arg;
|
||||
use crate::util::testutil::*;
|
||||
|
||||
fn table() -> Value {
|
||||
@@ -759,6 +786,49 @@ mod tests {
|
||||
assert_eq!(rows_of(&r), vec![vec![nv(3.0), nv(1.0)]]);
|
||||
}
|
||||
|
||||
/// A reference to a blank cell is a blank lookup value, not numeric zero, for XMATCH and
|
||||
/// XLOOKUP: it finds a blank entry and misses numbers. MATCH keeps Excel's zero coercion (#4044).
|
||||
#[test]
|
||||
fn xmatch_and_xlookup_treat_a_blank_reference_as_blank() {
|
||||
let numbers = || av(row(&[0.0, 1.0, 3.0]));
|
||||
let blank = || Arg::reference(Value::Empty);
|
||||
is_err(ev("XMATCH", vec![blank(), numbers()]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), rf(arr(vec![vec![Value::Empty], vec![nv(2.0)]]))]), 1.0);
|
||||
let keys = || rf(col(&[0.0, 1.0, 3.0]));
|
||||
let values = || av(col(&[10.0, 20.0, 30.0]));
|
||||
close(ev("XLOOKUP", vec![blank(), keys(), values(), n(999.0), n(0.0)]), 999.0);
|
||||
// Binary exact search (search mode 2 ascending, -2 descending) does not coerce the blank
|
||||
// needle to zero either: {0} has no blank entry, {0;blank} has one last.
|
||||
let zero = || rf(col(&[0.0]));
|
||||
let zero_then_blank = || rf(arr(vec![vec![nv(0.0)], vec![Value::Empty]]));
|
||||
let just_blank = || rf(arr(vec![vec![Value::Empty]]));
|
||||
for mode in [2.0, -2.0] {
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(0.0), n(mode)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(0.0), n(mode)]), 2.0);
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(0.0), n(mode)]), 1.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 999.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 10.0);
|
||||
// The approximate binary modes (-1 next smaller, 1 next larger) still take a present
|
||||
// exact blank before their fallback, in both search directions.
|
||||
for mm in [-1.0, 1.0] {
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(mm), n(mode)]), 1.0);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(mm), n(mode)]), 2.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 10.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero_then_blank(), av(col(&[10.0, 20.0])), n(999.0), n(mm), n(mode)]), 20.0);
|
||||
// Without a blank entry the approximate probes must not read the blank as zero.
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(mm), n(mode)]), CellError::NA);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 999.0);
|
||||
}
|
||||
}
|
||||
// Controls: numeric zero is still a key, and a written blank stays zero.
|
||||
close(ev("XMATCH", vec![n(0.0), numbers()]), 1.0);
|
||||
close(ev("XLOOKUP", vec![n(0.0), keys(), values(), n(999.0), n(0.0)]), 10.0);
|
||||
is_err(ev("XMATCH", vec![n(0.0), just_blank(), n(0.0), n(2.0)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![empty(), zero(), n(0.0), n(2.0)]), 1.0);
|
||||
close(ev("MATCH", vec![blank(), numbers(), n(0.0)]), 1.0);
|
||||
close(ev("XMATCH", vec![empty(), numbers()]), 1.0);
|
||||
}
|
||||
|
||||
/// Lookups compare numbers exactly, unlike `=` (15 significant digits). Observed in Excel 365.
|
||||
#[test]
|
||||
fn lookups_compare_numbers_exactly() {
|
||||
|
||||
Reference in New Issue
Block a user