diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4972623fc..f55b929ee 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -260,12 +260,7 @@ impl<'h> Evaluator<'h> { } // A reference keeps its size, so the array has its shape and its blanks count // (`=A1:A10`, `SUMPRODUCT(--(A1:A10=""))`). - let cells = u64::from(a.range.height()) * u64::from(a.range.width()); - // `A:A`, `1:1` and `A2:A1048576` run to the edge of the sheet: they stand for "the rest of - // the column", not for a block of a chosen size. - let to_edge = a.range.end.row == MAX_ROWS - 1 || a.range.end.col == MAX_COLS - 1; - let full_size = cells <= FULL_SIZE_CELLS || (!to_edge && cells <= FULL_SIZE_BOUNDED_CELLS); - let range = if full_size { a.range } else { self.trim(a) }; + let range = self.read_range(a); let (h, w) = (range.height() as usize, range.width() as usize); if (h as u64) * (w as u64) > MAX_CELLS { return Value::Error(CellError::Num); @@ -274,6 +269,17 @@ impl<'h> Evaluator<'h> { Array::new(h, w, data).map(Value::from).unwrap_or(Value::Error(CellError::Value)) } + /// The block that reading `a` gives: `a` itself, or when it is large (or runs to the sheet's + /// edge) the part inside the sheet's used range. + pub(crate) fn read_range(&mut self, a: &Area) -> RangeRef { + let cells = u64::from(a.range.height()) * u64::from(a.range.width()); + // `A:A`, `1:1` and `A2:A1048576` run to the edge of the sheet: they stand for "the rest of + // the column", not for a block of a chosen size. + let to_edge = a.range.end.row == MAX_ROWS - 1 || a.range.end.col == MAX_COLS - 1; + let full_size = cells <= FULL_SIZE_CELLS || (!to_edge && cells <= FULL_SIZE_BOUNDED_CELLS); + if full_size { a.range } else { self.trim(a) } + } + /// Trims the bottom/right of an area to the sheet's used range (keeps the top-left so /// positions stay right). pub fn trim(&mut self, a: &Area) -> RangeRef { diff --git a/crates/calc/src/eval/reference_fns.rs b/crates/calc/src/eval/reference_fns.rs index 4f5154c2d..425d5ff89 100644 --- a/crates/calc/src/eval/reference_fns.rs +++ b/crates/calc/src/eval/reference_fns.rs @@ -118,11 +118,29 @@ impl<'h> Evaluator<'h> { for c in 0..w { let pos = (num(&Some(ra.get_broadcast(r, c))), num(&Some(ca.get_broadcast(r, c)))); let v = match pos { + // A position that picks several cells is #CALC!. That is decided from the + // shape: reading the block first, for every position, let a short formula + // read one large range over and over only to discard it. + (Ok(row), Ok(col)) if index_picks_several_values(&src, row, col, two) => Value::Error(CellError::Calc), (Ok(row), Ok(col)) => { let one = self.index_one(src.clone(), row, col, area_n, two); - match self.deref(one) { - Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc), - v => v.scalar(), + let cells = match &one { + Ev::R(areas) => match areas.as_slice() { + [a] => self.area_cells(a), + _ => 0, + }, + _ => 0, + }; + if cells > MAX_CELLS { + // As reading it would answer. + Value::Error(CellError::Num) + } else if cells > 1 { + Value::Error(CellError::Calc) + } else { + match self.deref(one) { + Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc), + v => v.scalar(), + } } } (Err(e), _) | (_, Err(e)) => Value::Error(e), @@ -139,6 +157,16 @@ impl<'h> Evaluator<'h> { self.index_one(src, row, col, area_n, two) } + /// Cells that reading `a` gives: its own size, or for a large block the part inside the + /// sheet's used range (what [`Evaluator::area_value`] reads). + fn area_cells(&mut self, a: &Area) -> u64 { + if a.range.is_single() { + return 1; + } + let r = self.read_range(a); + u64::from(r.height()) * u64::from(r.width()) + } + /// INDEX for one row and column position (0 = the whole column or row). fn index_one(&mut self, src: Ev, row: i64, col: i64, area_n: i64, two_args: bool) -> Ev { if row < 0 || col < 0 { @@ -407,3 +435,71 @@ impl<'h> Evaluator<'h> { Ev::V(gridcraft_functions::aggregate_values(func, &values)) } } + +/// Whether INDEX on an array picks a whole row or column of several values at position +/// (`row`, `col`), which the array-of-positions form answers with #CALC!. +fn index_picks_several_values(src: &Ev, row: i64, col: i64, two_args: bool) -> bool { + let Ev::V(Value::Array(arr)) = src else { return false }; + let (row, col) = if two_args && arr.rows == 1 { (1, row) } else { (row, col) }; + if row < 0 || col < 0 || row as u64 > arr.rows as u64 || col as u64 > arr.cols as u64 { + return false; + } + (row == 0 && arr.rows > 1) || (col == 0 && arr.cols > 1) +} + +#[cfg(test)] +mod tests { + use super::super::Host; + use super::*; + use gridcraft_model::Workbook; + + /// A sheet of blanks that counts the blocks it is asked for. + struct Counting { + wb: Workbook, + cells_read: usize, + } + impl Host for Counting { + fn workbook(&self) -> &Workbook { + &self.wb + } + fn cell_value(&mut self, _sheet: usize, _c: CellRef) -> Value { + Value::Empty + } + fn now_serial(&self) -> f64 { + 0.0 + } + fn random(&mut self) -> f64 { + 0.0 + } + fn range_values(&mut self, _sheet: usize, range: RangeRef) -> Vec { + self.cells_read += range.count() as usize; + vec![Value::Empty; range.count() as usize] + } + } + + fn eval(src: &str) -> (Value, usize) { + let mut host = Counting { wb: Workbook::default(), cells_read: 0 }; + let mut ev = Evaluator::new(&mut host, 0, CellRef::new(0, 0)); + let v = ev.value(&gridcraft_formula::parser::parse(src).unwrap_or_else(|e| panic!("{e}"))); + (v, host.cells_read) + } + + fn all_calc(v: &Value, n: usize) -> bool { + matches!(v, Value::Array(a) if a.data.len() == n && a.data.iter().all(|x| *x == Value::Error(CellError::Calc))) + } + + #[test] + fn index_positions_that_pick_several_cells_are_calc_without_reading_them() { + // Each zero row position picks the whole of A1:A50000: #CALC!, decided from the shape. It + // used to read the 50,000 cells once per position before discarding them. + let (v, read) = eval("=INDEX(A1:A50000,{0,0,0,0},1)"); + assert!(all_calc(&v, 4), "{v:?}"); + assert_eq!(read, 0); + // The same for an array source: a whole column of a 3x3 array. + let (v, _) = eval("=INDEX({1,2,3;4,5,6;7,8,9},{0,0},2)"); + assert!(all_calc(&v, 2), "{v:?}"); + // Single cells are still read. + let (v, _) = eval("=INDEX({1,2,3;4,5,6;7,8,9},{1,3},2)"); + assert!(matches!(&v, Value::Array(a) if a.data == vec![Value::number(2.0), Value::number(8.0)]), "{v:?}"); + } +}