Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/calc/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1201,6 +1201,9 @@ impl<'h> Evaluator<'h> {
return err(CellError::Value);
}
let skip_hidden = matches!(options, 1 | 3 | 5 | 7);
// SUBTOTAL leaves out rows a filter hides whatever the function number (Microsoft's
// SUBTOTAL documentation); 101-111 also leave out rows hidden by hand.
let skip_filtered = name == "SUBTOTAL";
let skip_errors = matches!(options, 2 | 3 | 6 | 7);
let skip_nested = options <= 3;
let mut values = Vec::new();
Expand All @@ -1218,7 +1221,8 @@ impl<'h> Evaluator<'h> {
let (hidden, nested) = {
let wb = self.host.workbook();
let s = wb.sheet(a.sheet);
let hidden = skip_hidden && s.is_some_and(|s| s.is_row_hidden(c.row));
let hidden =
s.is_some_and(|s| if skip_hidden { s.is_row_hidden(c.row) } else { skip_filtered && s.is_row_filtered(c.row) });
let nested = skip_nested
&& s.and_then(|s| s.cell(c)).and_then(|cell| cell.formula.as_ref()).is_some_and(|f| {
let u = f.text.to_ascii_uppercase();
Expand Down
47 changes: 47 additions & 0 deletions crates/calc/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ fn arrays_do_not_spill_in_tables() {
first_col: false,
last_col: false,
filter_button: false,
filter: vec![],
});
t.set("C4", "=SEQUENCE(2)");
t.set("E1", "=SEQUENCE(4)");
Expand Down Expand Up @@ -385,6 +386,52 @@ fn subtotal_skips_hidden() {
assert_eq!(t.num("B2"), 6.0);
}

/// SUBTOTAL leaves out rows a filter hides for every function number, while 1-11 keep rows
/// hidden by hand (as in ConditionalFormattingSamples.xlsx, where `SUBTOTAL(9,Table69[Sales])`
/// under a filtered table adds only the visible rows).
#[test]
fn subtotal_skips_filtered_rows() {
use gridcraft_model::{AutoFilter, FilterCriterion, LineInfo};
let mut t = T::new();
for (i, v) in [1, 2, 4, 8, 16, 32].iter().enumerate() {
t.set(&format!("A{}", i + 2), &v.to_string());
t.set(&format!("C{}", i + 2), &v.to_string());
}
let crit = || vec![(0, FilterCriterion::Custom { a: (">".into(), "1".into()), b: None, and: false })];
let sh = t.wb.sheet_mut(0).unwrap();
sh.tables.push(gridcraft_model::Table {
id: 1,
name: "Sales".into(),
range: gridcraft_core::RangeRef::parse("A1:A7").unwrap(),
header_row: true,
totals_row: false,
columns: vec![gridcraft_model::TableColumn { name: "Amount".into(), totals: Default::default(), totals_label: None, formula: None }],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: true,
filter: crit(),
});
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
for row in [2, 4, 8] {
sh.rows.insert(row, LineInfo { hidden: true, ..Default::default() });
}
t.set("A9", "64");
t.set("E1", "=SUBTOTAL(9,Sales[Amount])");
t.set("E2", "=SUBTOTAL(109,Sales[Amount])");
t.set("E3", "=SUBTOTAL(9,C2:C7)");
t.set("E4", "=SUBTOTAL(9,A2:A9)");
t.set("E5", "=SUBTOTAL(109,A2:A9)");
t.set("E6", "=SUBTOTAL(2,A2:A7)");
t.set("E7", "=AGGREGATE(9,4,A2:A7)");
for (at, want) in [("E1", 53.0), ("E2", 53.0), ("E3", 53.0), ("E4", 117.0), ("E5", 53.0), ("E6", 4.0), ("E7", 63.0)] {
assert_eq!(t.num(at), want, "{at}");
}
}

#[test]
fn recalc_all_after_load() {
let mut t = T::new();
Expand Down
5 changes: 5 additions & 0 deletions crates/engine/src/cmd/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,9 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
let sh = cx.sheet_mut(sheet)?;
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
t.filter_button = !t.filter_button;
if !t.filter_button {
t.filter.clear();
}
}
Ok(Json::Null)
});
Expand Down Expand Up @@ -596,6 +599,8 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
},
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
// Icons are not evaluated here: the row keeps its current visibility.
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
};
if !ok {
visible = false;
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/forecast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
first_col: false,
last_col: false,
filter_button: true,
filter: vec![],
});
let q = gridcraft_formula::quote_sheet(&sheet_name);
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
Expand Down
8 changes: 7 additions & 1 deletion crates/engine/src/cmd/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
first_col: false,
last_col: false,
filter_button: true,
filter: vec![],
});
cx.structural = true;
Ok(json!({"table": name, "range": r.a1()}))
Expand Down Expand Up @@ -355,7 +356,12 @@ fn table_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
"bandedCols" => t.banded_cols = on.unwrap_or(!t.banded_cols),
"firstCol" => t.first_col = on.unwrap_or(!t.first_col),
"lastCol" => t.last_col = on.unwrap_or(!t.last_col),
"header" => t.filter_button = on.unwrap_or(!t.filter_button),
"header" => {
t.filter_button = on.unwrap_or(!t.filter_button);
if !t.filter_button {
t.filter.clear();
}
}
_ => {}
}
Ok(Json::Null)
Expand Down
173 changes: 141 additions & 32 deletions crates/functions/src/lookup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,43 +33,77 @@ fn find_exact(x: &Value, hay: &[Value], wild: bool, reverse: bool) -> Option<usi
if reverse { hay.iter().rposition(|v| lookup_equal(x, v, wild)) } else { hay.iter().position(|v| lookup_equal(x, v, wild)) }
}

/// Binary search over the entries of the needle's type, assuming they are sorted ascending
/// (`desc = false`) or descending. Returns the position of the last entry that is `<= x`
/// (ascending) or `>= x` (descending), like Excel's approximate match.
/// Approximate match of VLOOKUP, HLOOKUP, LOOKUP and MATCH: the position of the largest entry
/// `<= x` in data sorted ascending (`desc = false`), or of the smallest entry `>= x` in data
/// sorted descending. Like Excel this is a bisection over the whole vector, so on unsorted data
/// it answers what Excel answers rather than a linear "best" entry:
/// - the probe is the middle entry of the remaining window; a probe whose type differs from the
/// needle (text vs number vs logical, blanks, errors) is replaced by the nearest entry of the
/// needle's type below it in the window; when there is none the window moves up past it, so
/// entries of other types are skipped (`LOOKUP(9.9E+307, range)` finds the last number);
/// - a probe equal to the needle ends the search at once (the run of equal entries that follows
/// it is taken, so sorted duplicates give the last one).
///
/// Observed in Excel: `VLOOKUP(534, {"INTEGRAL";0;1;2;534;9999999999;-9999999999}, …)` finds 534,
/// `HLOOKUP("STRING", {"INTEGRAL","DOUBLE","BLANK","STRING","REF","AREA (rows)",<blank>}, …)`
/// finds "STRING" and `LOOKUP("DOUBLE", {"DOUBLE","BLANK","STRING","REF","AREA (rows)"}, …)`
/// finds "DOUBLE". Work is linear in the vector length at worst.
fn bsearch_last(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
let idx: Vec<usize> = hay.iter().enumerate().filter(|(_, v)| same_type(x, v)).map(|(i, _)| i).collect();
let (mut lo, mut hi) = (0usize, idx.len());
// Find the first filtered position where the "passes" predicate fails.
while lo < hi {
let mut hi = hay.len().checked_sub(1)?;
let mut lo = 0usize;
let mut best = None;
while lo <= hi {
let mid = lo + (hi - lo) / 2;
let v = idx.get(mid).and_then(|&i| hay.get(i))?;
let o = compare(v, x);
let ok = if desc { o != Ordering::Less } else { o != Ordering::Greater };
if ok {
let Some(j) = (lo..=mid).rev().find(|&j| hay.get(j).is_some_and(|v| same_type(x, v))) else {
lo = mid + 1;
} else {
hi = mid;
}
}
if lo == 0 { None } else { idx.get(lo - 1).copied() }
}

/// Binary search returning the first entry `>= x` (ascending) or `<= x` (descending).
fn bsearch_first(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
let idx: Vec<usize> = hay.iter().enumerate().filter(|(_, v)| same_type(x, v)).map(|(i, _)| i).collect();
let (mut lo, mut hi) = (0usize, idx.len());
while lo < hi {
let mid = lo + (hi - lo) / 2;
let v = idx.get(mid).and_then(|&i| hay.get(i))?;
continue;
};
let v = hay.get(j)?;
let o = compare(v, x);
if o == Ordering::Equal {
let mut k = j;
while hay.get(k + 1).is_some_and(|w| same_type(x, w) && compare(w, x) == Ordering::Equal) {
k += 1;
}
return Some(k);
}
let before = if desc { o == Ordering::Greater } else { o == Ordering::Less };
if before {
best = Some(j);
lo = mid + 1;
} else if j == 0 {
break;
} else {
hi = mid;
hi = j - 1;
}
}
idx.get(lo).copied()
best
}

/// Order of an entry relative to the needle for XLOOKUP / XMATCH binary search (search mode ±2):
/// Excel's sort order over all types (numbers < text < logicals < errors), reversed for
/// descending data, with blanks always last like a sort leaves them. Unlike the legacy
/// approximate match no entry is skipped (observed: `XLOOKUP(46523, {9700;"xyz";"xyz";160726;
/// 204100;510300}, …, 0, 1, 2)` returns the row of the first "xyz").
fn binary_order(v: &Value, x: &Value, desc: bool) -> Ordering {
match v {
Value::Empty => Ordering::Greater,
_ if desc => compare(v, x).reverse(),
_ => compare(v, x),
}
}

/// Binary search for the first entry not ordered before the needle (`>= x` ascending, `<= x`
/// descending).
fn bsearch_first(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
let p = hay.partition_point(|v| binary_order(v, x, desc) == Ordering::Less);
(p < hay.len()).then_some(p)
}

/// Binary search for the last entry not ordered after the needle (`<= x` ascending, `>= x`
/// descending).
fn bsearch_upto(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
hay.partition_point(|v| binary_order(v, x, desc) != Ordering::Greater).checked_sub(1)
}

/// A 1-D view of an array (row or column), `None` when it is 2-D.
Expand Down Expand Up @@ -199,12 +233,13 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
if desc {
bsearch_first(x, hay, true)
} else {
bsearch_last(x, hay, false)
bsearch_upto(x, hay, false)
}
}
// Next larger: first >= x (ascending) / last >= x (descending).
_ => {
if desc {
bsearch_last(x, hay, true)
bsearch_upto(x, hay, true)
} else {
bsearch_first(x, hay, false)
}
Expand Down Expand Up @@ -248,7 +283,7 @@ 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> {
let p = bsearch_first(x, hay, desc)?;
let v = hay.get(p)?;
if compare(v, x) == Ordering::Equal { Some(p) } else { None }
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
}

fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
Expand Down Expand Up @@ -378,9 +413,16 @@ fn transpose(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
}
}

/// Sheet text for ADDRESS, quoted when it needs to be. A `[Book]Sheet` prefix is judged by its
/// parts (Microsoft's ADDRESS examples: `"[Book1]Sheet1"` stays bare, `"EXCEL SHEET"` becomes
/// `'EXCEL SHEET'`).
fn quote_sheet(s: &str) -> String {
let plain =
!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.') && !s.chars().next().is_some_and(|c| c.is_ascii_digit());
let word = |p: &str| p.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.');
let bare_sheet = |p: &str| !p.is_empty() && word(p) && !p.chars().next().is_some_and(|c| c.is_ascii_digit());
let plain = match s.strip_prefix('[').and_then(|r| r.split_once(']')) {
Some((book, sheet)) => !book.is_empty() && word(book) && bare_sheet(sheet),
None => bare_sheet(s),
};
if plain { s.to_string() } else { format!("'{}'", s.replace('\'', "''")) }
}

Expand Down Expand Up @@ -574,6 +616,45 @@ mod tests {
close(ev("LOOKUP", vec![t("zz"), av(mixed), av(row(&[1.0, 2.0, 3.0, 4.0]))]), 4.0);
}

/// Approximate matches over unsorted, mixed-type data as observed in Excel
/// (FormulaEvalTestData rows "Vlookup", "Hlookup", "Lookup"): Excel bisects the whole
/// vector and stops at an equal entry, so answers differ from a "best entry" scan.
#[test]
fn approximate_match_follows_bisection() {
// B6:H12 of the test data: header row, then one row per data kind.
let data = arr(vec![
vec![tv("INTEGRAL"), tv("DOUBLE"), tv("BLANK"), tv("STRING"), tv("REF"), tv("AREA (rows)"), Value::Empty],
vec![nv(0.0), nv(0.0), Value::Empty, tv(""), nv(0.0), nv(1.0), nv(2.0)],
vec![nv(1.0), nv(0.00001), Value::Empty, tv("nospaces"), nv(1.0), nv(1.001), nv(2.999)],
vec![nv(2.0), nv(1.1), Value::Empty, tv("sp ace s"), nv(9999999999.0), nv(2.3456), nv(3.4567)],
vec![nv(534.0), nv(1.00001), Value::Empty, tv("endsWithSpace "), nv(0.00001), tv("alphanum"), nv(3.0)],
vec![nv(9999999999.0), nv(2.99999), Value::Empty, tv(" beginsWithSpace"), nv(0.0), tv("blanksIncl"), Value::Empty],
vec![nv(-9999999999.0), nv(999999.99999), Value::Empty, tv("non-numeric"), tv("sp ace s"), tv("E8"), nv(545.0)],
]);
close(ev("VLOOKUP", vec![n(534.0), rf(data.clone()), n(2.0)]), 1.00001);
is_text(ev("VLOOKUP", vec![n(534.0), rf(data.clone()), n(4.0)]), "endsWithSpace ");
is_text(ev("VLOOKUP", vec![n(534.0), rf(data.clone()), n(4.0), b(true)]), "endsWithSpace ");
is_text(ev("HLOOKUP", vec![t("STRING"), rf(data.clone()), n(6.0), b(true)]), " beginsWithSpace");
let keys = arr(vec![vec![tv("DOUBLE"), tv("BLANK"), tv("STRING"), tv("REF"), tv("AREA (rows)")]]);
let results = arr(vec![vec![nv(1.1), Value::Empty, tv("sp ace s"), nv(9999999999.0), nv(2.3456)]]);
close(ev("LOOKUP", vec![t("DOUBLE"), rf(keys), rf(results)]), 1.1);
let b6_b15 = col(&[0.0, 1.0, 2.0, 534.0, 9999999999.0, -9999999999.0, -534.0, -2.0, -1.0]);
let mut keys = vec![tv("INTEGRAL")];
keys.extend(rows_of(&b6_b15).into_iter().flatten());
let words = ["STRING", "", "nospaces", "sp ace s", "endsWithSpace ", " beginsWithSpace", "non-numeric", "0", "0.000001", "1"];
let e_col = arr(words.iter().map(|w| vec![tv(w)]).collect());
is_text(ev("LOOKUP", vec![n(534.0), rf(arr(keys.into_iter().map(|k| vec![k]).collect())), rf(e_col)]), "endsWithSpace ");
// Sorted duplicates give the last one; descending data with MATCH -1 too.
close(ev("MATCH", vec![n(2.0), av(row(&[1.0, 2.0, 2.0, 2.0, 3.0])), n(1.0)]), 4.0);
close(ev("MATCH", vec![n(20.0), av(row(&[40.0, 20.0, 20.0, 10.0])), n(-1.0)]), 3.0);
// Only text and blanks: no number to find.
is_err(ev("MATCH", vec![n(5.0), av(arr(vec![vec![tv("a"), Value::Empty, tv("b")]]))]), CellError::NA);
// A long run of trailing blanks (whole-column lookups) still finds the last number.
let mut tall = vec![vec![nv(1.0)], vec![nv(2.0)], vec![nv(3.0)]];
tall.extend((0..10_000).map(|_| vec![Value::Empty]));
close(ev("MATCH", vec![n(9.0), rf(arr(tall))]), 3.0);
}

#[test]
fn match_fn() {
let v = col(&[10.0, 20.0, 30.0, 40.0]);
Expand Down Expand Up @@ -632,6 +713,23 @@ mod tests {
is_err(ev("XLOOKUP", vec![n(2.0), rf(table()), rf(vals)]), CellError::Value);
}

/// XLOOKUP binary search (search mode ±2). Observed in Excel (xlookup.xlsx, Sheet2): next
/// larger over ascending data with text mixed in (0.22) and over descending data (0.24); the
/// bisection compares across types in sort order (numbers < text) instead of skipping text.
/// The other modes follow from the same order.
#[test]
fn xlookup_binary_search_observed() {
let rates = col(&[0.1, 0.22, 0.24, 0.32, 0.35, 0.37]);
let incomes = arr(vec![vec![nv(9700.0)], vec![tv("xyz")], vec![tv("xyz")], vec![nv(160726.0)], vec![nv(204100.0)], vec![nv(510300.0)]]);
close(ev("XLOOKUP", vec![n(46523.0), rf(incomes.clone()), rf(rates.clone()), n(0.0), n(1.0), n(2.0)]), 0.22);
close(ev("XLOOKUP", vec![n(46523.0), rf(incomes), rf(rates), n(0.0), n(-1.0), n(2.0)]), 0.1);
let desc_incomes = col(&[510300.0, 204100.0, 160726.0, 84200.0, 39475.0, 9700.0]);
let desc_rates = col(&[0.37, 0.35, 0.32, 0.24, 0.22, 0.1]);
close(ev("XLOOKUP", vec![n(46523.0), rf(desc_incomes.clone()), rf(desc_rates.clone()), n(0.0), n(1.0), n(-2.0)]), 0.24);
close(ev("XLOOKUP", vec![n(46523.0), rf(desc_incomes.clone()), rf(desc_rates.clone()), n(0.0), n(-1.0), n(-2.0)]), 0.22);
close(ev("XLOOKUP", vec![n(84200.0), rf(desc_incomes), rf(desc_rates), n(0.0), n(0.0), n(-2.0)]), 0.24);
}

fn table_rows3() -> Value {
arr(vec![vec![nv(1.0), tv("one"), nv(10.0)], vec![nv(2.0), tv("two"), nv(20.0)], vec![nv(3.0), tv("three"), nv(30.0)]])
}
Expand Down Expand Up @@ -682,6 +780,17 @@ mod tests {
is_text(ev("ADDRESS", vec![n(2.0), n(3.0), n(4.0), b(false)]), "R[2]C[3]");
is_text(ev("ADDRESS", vec![n(1.0), n(1.0), n(1.0), b(true), t("Sheet1")]), "Sheet1!$A$1");
is_text(ev("ADDRESS", vec![n(1.0), n(1.0), n(1.0), b(true), t("My Sheet")]), "'My Sheet'!$A$1");
// Observed in Excel (FormulaEvalTestData) and Microsoft's ADDRESS examples; the last
// case follows from the quoting rule for sheet names.
let cases: [(f64, f64, f64, bool, &str, &str); 4] = [
(2.0, 3.0, 3.0, true, "[Book1]Sheet1", "[Book1]Sheet1!$C2"),
(2.0, 3.0, 1.0, false, "[Book1]Sheet1", "[Book1]Sheet1!R2C3"),
(2.0, 3.0, 1.0, false, "EXCEL SHEET", "'EXCEL SHEET'!R2C3"),
(1.0, 1.0, 1.0, true, "[My Book]Sheet1", "'[My Book]Sheet1'!$A$1"),
];
for (r, c, abs, a1, sheet, want) in cases {
is_text(ev("ADDRESS", vec![n(r), n(c), n(abs), b(a1), t(sheet)]), want);
}
is_text(ev("ADDRESS", vec![n(1048576.0), n(16384.0)]), "$XFD$1048576");
is_err(ev("ADDRESS", vec![n(0.0), n(1.0)]), CellError::Value);
is_err(ev("ADDRESS", vec![n(1.0), n(16385.0)]), CellError::Value);
Expand Down
Loading