From 5cf0e24f430176fdac37dbd2a284faa7215f1dd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:12:43 +0200 Subject: [PATCH 01/68] Charts: one combo plot-kind rule, no fixed_scale helper, ticks off the step grid (#1146) Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 3 ++- crates/chart/src/axis.rs | 11 ++++------- crates/chart/src/render.rs | 20 +++++++++++--------- crates/chart/src/resolve.rs | 10 ++++++++-- crates/chart/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 19 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..2e93366836 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-13 · **Change:** trivial (chart combo plot-kind rule, scale ticks) · **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-13 | Charts: one combo plot-kind rule for resolving and drawing; ticks of a scale off the step grid keep their own values (#1146) | | 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) | diff --git a/crates/chart/src/axis.rs b/crates/chart/src/axis.rs index 8686bf7d9c..46fc43f99d 100644 --- a/crates/chart/src/axis.rs +++ b/crates/chart/src/axis.rs @@ -25,9 +25,11 @@ impl Scale { (0..=n) .map(|i| { let v = self.min + i as f64 * self.step; - // Snap away accumulated float error. + // Snap away accumulated float error, but only onto a multiple of the step that is + // really that close: a `min` off the step grid must keep its own ticks. let snapped = (v / self.step).round() * self.step; - if snapped.abs() < self.step * 1e-9 { 0.0 } else { snapped } + let v = if (snapped - v).abs() < self.step * 1e-9 { snapped } else { v }; + if v.abs() < self.step * 1e-9 { 0.0 } else { v } }) .collect() } @@ -107,11 +109,6 @@ pub fn nice_scale(lo: f64, hi: f64, force_zero: bool) -> Scale { Scale { min, max, step } } -/// Exact fixed scale (100% stacked axes). -pub(crate) fn fixed_scale(min: f64, max: f64, step: f64) -> Scale { - Scale { min, max, step } -} - /// A number format prepared once and reused for many labels. pub(crate) struct Fmt { general: bool, diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 037b9099e0..82769bcdc7 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -5,7 +5,7 @@ use std::f32::consts::{PI, TAU}; use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, Theme, TrendlineKind}; -use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale}; +use crate::axis::{Fmt, Scale, clean, nice_scale}; use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color}; use crate::trend::{auto_name, fit_trendline, moving_average}; use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign}; @@ -120,9 +120,10 @@ pub enum Swatch { Marker, } -/// The kind a series is drawn as (per-series kinds only apply to combo charts). -fn plot_kind(chart: &Chart, s: &SeriesData) -> ChartKind { - if chart.kind == ChartKind::Combo { if s.kind == ChartKind::Combo { ChartKind::Line } else { s.kind } } else { chart.kind } +/// The kind series `i` is drawn as (per-series kinds only apply to combo charts); the same rule +/// as `series_plot_kind`, applied to the already resolved series kind. +fn plot_kind(chart: &Chart, s: &SeriesData, i: usize) -> ChartKind { + crate::resolve::plot_kind(chart.kind, Some(s.kind), i) } /// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). @@ -163,8 +164,9 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa let series = data.series.iter().take(MAX_SERIES); let mut out: Vec<(String, Rgba, Swatch)> = series .clone() - .map(|s| { - let sw = match plot_kind(chart, s) { + .enumerate() + .map(|(i, s)| { + let sw = match plot_kind(chart, s, i) { ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, @@ -174,7 +176,7 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa }) .collect(); // Trendlines follow the series, named "Linear (Sales)" unless given a name. - for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) { + for (_, s) in series.enumerate().filter(|(i, s)| supports_trendline(plot_kind(chart, s, *i))) { for t in s.trendlines.iter().take(MAX_TRENDLINES) { out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); } @@ -833,7 +835,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta if ncat == 0 { return; } - let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { plot_kind(chart, s) }).collect(); + let kinds: Vec = data.series.iter().enumerate().map(|(i, s)| if horizontal { chart.kind } else { plot_kind(chart, s, i) }).collect(); let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); @@ -915,7 +917,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta })); let (lo, hi) = range.unwrap_or((0.0, 0.0)); let (scale, fmt) = if all100 { - (fixed_scale(if lo < -1e-9 { -1.0 } else { 0.0 }, if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, 0.2), Fmt::new("0%")) + (Scale { min: if lo < -1e-9 { -1.0 } else { 0.0 }, max: if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, step: 0.2 }, Fmt::new("0%")) } else { let code = members.first().and_then(|i| data.series.get(*i)).map(|s| s.number_format.as_str()).unwrap_or("General"); (nice_scale(lo, hi, force_zero), Fmt::new(code)) diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index c007e3e907..2faeeb356b 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -170,7 +170,7 @@ fn series_name(wb: &Workbook, sheet: usize, name: &str) -> String { t.to_string() } -fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { +pub(crate) fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { match (chart_kind, series_kind) { (ChartKind::Combo, Some(k)) if k != ChartKind::Combo => k, (ChartKind::Combo, _) => { @@ -185,9 +185,15 @@ fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usiz } } +/// The kind series `i` is drawn as: its own kind in a combo chart (first series a column, the +/// rest lines when it has none), else the chart's. The one rule shared by resolving and drawing. +pub(crate) fn plot_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { + if chart_kind == ChartKind::Combo { effective_kind(chart_kind, series_kind, i) } else { chart_kind } +} + /// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's. pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind { - if chart.kind == ChartKind::Combo { effective_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } else { chart.kind } + plot_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } /// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 01f1aac499..4dcfcde841 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1057,3 +1057,35 @@ fn area_charts_draw_source_value_labels_only_when_enabled() { assert!(first_label > last_poly, "{kind:?}: label drawn under a later area"); } } + +#[test] +fn drawing_and_resolving_agree_on_the_combo_plot_kind() { + // Resolved series carry `effective_kind`; drawing re-derives the kind from it. Both paths + // must give the same kind for every chart kind, series kind (or none) and series index. + let series_kinds = std::iter::once(None).chain(ALL_KINDS.iter().map(|k| Some(*k))); + for ck in ALL_KINDS { + for sk in series_kinds.clone() { + for i in 0..3 { + let mut c = chart(ck); + c.series = (0..3).map(|j| Series { kind: if j == i { sk } else { None }, ..Default::default() }).collect(); + let from_chart = series_plot_kind(&c, i); + let resolved = crate::resolve::effective_kind(ck, sk, i); + assert_eq!(crate::resolve::plot_kind(ck, Some(resolved), i), from_chart, "{ck:?} {sk:?} {i}"); + if ck != ChartKind::Combo { + assert_eq!(from_chart, ck); + } else { + assert_ne!(from_chart, ChartKind::Combo); + } + } + } + } +} + +#[test] +fn ticks_of_a_scale_off_the_step_grid_start_at_its_min() { + let s = Scale { min: 3.0, max: 7.0, step: 4.0 }; + assert_eq!(s.ticks(), vec![3.0, 7.0]); + // Aligned scales still snap float error away. + let s = Scale { min: 0.0, max: 1.0, step: 0.1 }; + assert!((s.ticks()[3] - 0.3).abs() < 1e-12 && s.ticks()[0] == 0.0); +} From 79cfd9b151c7f36793d230fac10857b02cfbe33d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:13:20 +0200 Subject: [PATCH 02/68] Charts: label fitting and legend measuring avoid hundreds of text layouts per render (#1149) Binary search in Ctx::fit, early exit of the side-legend column measure, no per-point Vecs in value_range/squarify, treemap carries the value. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/chart/src/render.rs | 90 ++++++--- crates/chart/src/render_perf_tests.rs | 254 ++++++++++++++++++++++++++ 3 files changed, 317 insertions(+), 28 deletions(-) create mode 100644 crates/chart/src/render_perf_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..ae8286ad36 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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-13 | Charts: label shortening needs about nine text measurements instead of up to 400, side legends stop measuring once the column is at its cap and treemap layout avoids per-item allocation (#1149) | | 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) | diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 037b9099e0..396423d2bc 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -62,25 +62,47 @@ struct Ctx<'a> { m: &'a dyn Measure, } +#[cfg(test)] +#[path = "render_perf_tests.rs"] +mod perf_tests; + impl Ctx<'_> { fn tw(&self, s: &str, size: f32) -> f32 { let w = self.m.text_width(s, size, false); if w.is_finite() { w.max(0.0) } else { 0.0 } } + /// `s` shortened with an ellipsis to fit `maxw`; empty when not even one character fits. + /// + /// Binary search over the number of kept characters (at most 400 are tried), about nine + /// `Measure` calls instead of one per character. It assumes the width of `prefix + "…"` does not + /// shrink as the prefix grows, which holds for per-character advance sums (`ApproxMeasure`, the + /// PDF metrics) and for the UI's text layout up to kerning of a few hundredths of a point; with + /// such a non-monotone measure the result may differ from the old linear scan by a character. fn fit(&self, s: &str, size: f32, maxw: f32) -> String { if self.tw(s, size) <= maxw { return s.to_string(); } - let chars: Vec = s.chars().collect(); - let mut n = chars.len().min(400); - while n > 0 { - n -= 1; - let t: String = chars.iter().take(n).collect::() + "…"; - if self.tw(&t, size) <= maxw { - return if n == 0 { String::new() } else { t }; + // Byte offset where each of the first 400 characters starts; a prefix of `k` characters + // (k < number of characters, so the offset exists) ends at `starts[k]`. + let starts: Vec = s.char_indices().map(|(i, _)| i).take(400).collect(); + let top = starts.len().saturating_sub(1); + let fits = |k: usize| -> bool { + let end = starts.get(k).copied().unwrap_or(s.len()); + let mut t = String::with_capacity(end + 3); + t.push_str(s.get(..end).unwrap_or("")); + t.push('…'); + self.tw(&t, size) <= maxw + }; + let (mut lo, mut hi) = (0usize, top); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if fits(mid) { + lo = mid; + } else { + hi = mid - 1; } } - String::new() + if lo == 0 { String::new() } else { format!("{}…", s.get(..starts.get(lo).copied().unwrap_or(s.len())).unwrap_or("")) } } #[allow(clippy::too_many_arguments)] fn text(&mut self, x: f32, y: f32, s: &str, size: f32, color: Rgba, align: HAlign, valign: VAlign) { @@ -369,7 +391,16 @@ fn draw_legend(ctx: &mut Ctx, entries: &[(String, Rgba, Swatch)], pos: LegendPos if pos == LegendPos::Bottom { Bx { h: area.h - used, ..area } } else { Bx { y: area.y + used, h: area.h - used, ..area } } } LegendPos::Left | LegendPos::Right => { - let colw = entries.iter().map(|e| item_w(ctx, e)).fold(0.0f32, f32::max).min(area.w * 0.35); + // Widest entry, capped at 35% of the area: once the cap is reached the rest cannot change it. + let cap = area.w * 0.35; + let mut colw = 0.0f32; + for e in entries { + if colw >= cap { + break; + } + colw = colw.max(item_w(ctx, e)); + } + let colw = colw.min(cap); let max_rows = ((area.h / row_h).floor() as usize).max(1); let n = entries.len().min(max_rows); let lh = n as f32 * row_h; @@ -911,7 +942,8 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta let all100 = members.iter().all(|i| fams.get(*i) == Some(&Fam::Col100)); let range = value_range(members.iter().flat_map(|i| { let line = fams.get(*i).is_some_and(|f| is_line(*f)); - spans.get(*i).into_iter().flatten().flatten().flat_map(move |(b, t)| if line { vec![*t] } else { vec![*b, *t] }) + // Lines contribute only their top value, bars both ends (no per-point `Vec`). + spans.get(*i).into_iter().flatten().flatten().flat_map(move |(b, t)| [*b, *t].into_iter().skip(usize::from(line))) })); let (lo, hi) = range.unwrap_or((0.0, 0.0)); let (scale, fmt) = if all100 { @@ -1399,19 +1431,19 @@ fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inner: f32, nam // ---------------------------------------------------------------- treemap -fn worst(row: &[f64], side: f64) -> f64 { - let s: f64 = row.iter().sum(); +/// Worst aspect ratio of a row with the given area sum, smallest and largest item, laid along `side`. +fn worst(s: f64, mn: f64, mx: f64, side: f64) -> f64 { if s <= 0.0 || side <= 0.0 { return f64::INFINITY; } - let (mn, mx) = row.iter().fold((f64::INFINITY, 0.0f64), |(a, b), v| (a.min(*v), b.max(*v))); let s2 = s * s; let w2 = side * side; (w2 * mx / s2).max(s2 / (w2 * mn)) } -/// Squarified treemap layout of (index, area) items, sorted descending, into `r`. -fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { +/// Squarified treemap layout of (index, value) items, sorted descending, into `r`; each block +/// comes back with its index and value. +fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, f64, Bx)> { let total: f64 = items.iter().map(|i| i.1).sum(); let area = (r.w as f64) * (r.h as f64); if !(total > 0.0 && area > 0.0) { @@ -1420,9 +1452,10 @@ fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { let scale = area / total; let mut out = Vec::with_capacity(items.len()); let mut rem = r; - let mut row: Vec<(usize, f64)> = Vec::new(); + let mut row: Vec<(usize, f64, f64)> = Vec::new(); + let (mut sum, mut mn, mut mx) = (0.0f64, f64::INFINITY, 0.0f64); let mut i = 0; - let layout = |row: &[(usize, f64)], rem: &mut Bx, out: &mut Vec<(usize, Bx)>| { + let layout = |row: &[(usize, f64, f64)], rem: &mut Bx, out: &mut Vec<(usize, f64, Bx)>| { let s: f64 = row.iter().map(|x| x.1).sum(); if s <= 0.0 { return; @@ -1430,9 +1463,9 @@ fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { if rem.w >= rem.h { let cw = (s / rem.h.max(1e-6) as f64) as f32; let mut y = rem.y; - for (j, a) in row { + for (j, a, v) in row { let h = (*a / cw.max(1e-6) as f64) as f32; - out.push((*j, Bx { x: rem.x, y, w: cw, h })); + out.push((*j, *v, Bx { x: rem.x, y, w: cw, h })); y += h; } rem.x += cw; @@ -1440,9 +1473,9 @@ fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { } else { let rh = (s / rem.w.max(1e-6) as f64) as f32; let mut x = rem.x; - for (j, a) in row { + for (j, a, v) in row { let w = (*a / rh.max(1e-6) as f64) as f32; - out.push((*j, Bx { x, y: rem.y, w, h: rh })); + out.push((*j, *v, Bx { x, y: rem.y, w, h: rh })); x += w; } rem.y += rh; @@ -1452,15 +1485,17 @@ fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { while let Some(&(j, v)) = items.get(i) { let a = v * scale; let side = rem.w.min(rem.h) as f64; - let cur: Vec = row.iter().map(|x| x.1).collect(); - let mut with = cur.clone(); - with.push(a); - if row.is_empty() || worst(&with, side) <= worst(&cur, side) { - row.push((j, a)); + // Sum, smallest and largest item of the open row, kept incrementally (same fold order as + // summing the row afresh, so the numbers are bit-identical). + let with = (sum + a, mn.min(a), mx.max(a)); + if row.is_empty() || worst(with.0, with.1, with.2, side) <= worst(sum, mn, mx, side) { + row.push((j, a, v)); + (sum, mn, mx) = with; i += 1; } else { layout(&row, &mut rem, &mut out); row.clear(); + (sum, mn, mx) = (0.0, f64::INFINITY, 0.0); } } if !row.is_empty() { @@ -1475,14 +1510,13 @@ fn treemap(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { s.values.iter().take(MAX_MARKERS).enumerate().filter_map(|(j, v)| v.filter(|v| *v > 0.0).map(|v| (j, v))).collect(); items.sort_by(|a, b| b.1.total_cmp(&a.1)); let f = Fmt::new(&s.number_format); - for (j, b) in squarify(&items, area) { + for (j, v, b) in squarify(&items, area) { let fill = point_color(data, j); ctx.rect(b.x, b.y, b.w, b.h, fill, Some((WHITE, 1.5))); if b.w > 24.0 && b.h > LABEL_SIZE * 1.6 { let name = ctx.fit(&cat_label(data, j), LABEL_SIZE, b.w - 8.0); ctx.text(b.x + 4.0, b.y + 4.0, &name, LABEL_SIZE, on(fill), HAlign::Left, VAlign::Top); if chart.data_labels && b.h > LABEL_SIZE * 3.2 { - let v = items.iter().find(|x| x.0 == j).map(|x| x.1).unwrap_or(0.0); let t = ctx.fit(&f.format(v, None), LABEL_SIZE, b.w - 8.0); ctx.text(b.x + 4.0, b.y + 4.0 + LABEL_SIZE * 1.4, &t, LABEL_SIZE, on(fill), HAlign::Left, VAlign::Top); } diff --git a/crates/chart/src/render_perf_tests.rs b/crates/chart/src/render_perf_tests.rs new file mode 100644 index 0000000000..7bef70722c --- /dev/null +++ b/crates/chart/src/render_perf_tests.rs @@ -0,0 +1,254 @@ +//! Equality and counter tests for the label-fitting, legend-measuring and treemap rewrites. +//! The old implementations live here as references. + +use std::cell::Cell; + +use super::*; +use crate::{ApproxMeasure, Measure}; + +/// The pre-rewrite `Ctx::fit`: one `Measure` call per candidate length, longest first. +fn fit_reference(ctx: &Ctx, s: &str, size: f32, maxw: f32) -> String { + if ctx.tw(s, size) <= maxw { + return s.to_string(); + } + let chars: Vec = s.chars().collect(); + let mut n = chars.len().min(400); + while n > 0 { + n -= 1; + let t: String = chars.iter().take(n).collect::() + "…"; + if ctx.tw(&t, size) <= maxw { + return if n == 0 { String::new() } else { t }; + } + } + String::new() +} + +/// Counts calls; advances differ per character (wide CJK/emoji, zero-width combining marks) and +/// "AV"-style pairs are kerned tighter, but a character never makes the text narrower. +struct Varied { + calls: Cell, +} + +impl Measure for Varied { + fn text_width(&self, text: &str, size: f32, bold: bool) -> f32 { + self.calls.set(self.calls.get() + 1); + let mut w = 0.0f32; + let mut prev = ' '; + for c in text.chars() { + let adv = match c as u32 { + 0x300..=0x36f => 0.0, + 0x1f300..=0x1faff | 0x4e00..=0x9fff => 1.0, + u => 0.3 + (u % 7) as f32 * 0.07, + }; + let kern = if prev == 'A' && c == 'V' { 0.1 } else { 0.0 }; + w += (adv - kern) * size; + prev = c; + } + if bold { w * 1.1 } else { w } + } +} + +struct Counting<'a>(&'a dyn Measure, Cell); + +impl Measure for Counting<'_> { + fn text_width(&self, text: &str, size: f32, bold: bool) -> f32 { + self.1.set(self.1.get() + 1); + self.0.text_width(text, size, bold) + } +} + +fn corpus() -> Vec { + let mut v: Vec = + ["", "a", "ab", "Hello, world", "AVAVAV tight", "日本語のラベルです", "👨‍👩‍👧 family 🎉 party", "e\u{301}e\u{301}e\u{301} combining", "…", "……"] + .iter() + .map(|s| s.to_string()) + .collect(); + v.push("x".repeat(399)); + v.push("x".repeat(400)); + v.push("x".repeat(401)); + v.push("é🎉".repeat(500)); + v.push("long label ".repeat(100)); + v +} + +fn run_fit(m: &dyn Measure) { + let ctx = Ctx { out: vec![], m }; + for s in corpus() { + for size in [9.0f32, 11.0, 40.0] { + for maxw in [-5.0, 0.0, 0.4, 6.0, 25.0, 61.5, 120.0, 800.0, 1e6, f32::INFINITY, f32::NAN] { + assert_eq!(ctx.fit(&s, size, maxw), fit_reference(&ctx, &s, size, maxw), "{s:?} size {size} maxw {maxw}"); + } + } + } +} + +#[test] +fn fit_matches_linear_reference() { + run_fit(&ApproxMeasure); + run_fit(&Varied { calls: Cell::new(0) }); +} + +#[test] +fn fit_measures_logarithmically() { + let long = "x".repeat(1000); + let c = Counting(&ApproxMeasure, Cell::new(0)); + let ctx = Ctx { out: vec![], m: &c }; + let r = ctx.fit(&long, 11.0, 60.0); + assert!(r.ends_with('…') && r.chars().count() > 3); + // 1 whole-string check + ceil(log2(399)) + 1 probes; the old scan needed ~390 here. + assert!(c.1.get() <= 12, "{} Measure calls", c.1.get()); + let c2 = Counting(&ApproxMeasure, Cell::new(0)); + let ctx2 = Ctx { out: vec![], m: &c2 }; + assert_eq!(ctx2.fit("short", 11.0, 500.0), "short"); + assert_eq!(c2.1.get(), 1); +} + +fn legend_entries(n: usize, label: &dyn Fn(usize) -> String) -> Vec<(String, Rgba, Swatch)> { + (0..n).map(|i| (label(i), [10, 20, 30, 255], if i % 3 == 0 { Swatch::Line } else { Swatch::Box })).collect() +} + +/// Colour column width as the old code computed it, from the returned remaining area. +fn old_colw(m: &dyn Measure, entries: &[(String, Rgba, Swatch)], area: Bx) -> f32 { + let ctx = Ctx { out: vec![], m }; + let size = LABEL_SIZE; + let s = size * 0.8; + entries.iter().map(|e| swatch_w(e.2, s) + 4.0 + ctx.tw(&e.0, size)).fold(0.0f32, f32::max).min(area.w * 0.35) +} + +#[test] +fn side_legend_matches_old_column_width_and_stops_measuring_at_the_cap() { + let area = Bx { x: 0.0, y: 0.0, w: 400.0, h: 300.0 }; + let labels: [&dyn Fn(usize) -> String; 3] = + [&|i| format!("entry {i}"), &|i| if i == 7 { "w".repeat(80) } else { format!("e{i}") }, &|i| "very long legend label ".repeat(1 + i % 3)]; + for pos in [LegendPos::Left, LegendPos::Right] { + for (k, label) in labels.iter().enumerate() { + for n in [0usize, 1, 5, 40] { + let entries = legend_entries(n, label); + let mut ctx = Ctx { out: vec![], m: &ApproxMeasure }; + let rest = draw_legend(&mut ctx, &entries, pos, area); + let colw = old_colw(&ApproxMeasure, &entries, area); + assert!((rest.w - (area.w - (colw + 8.0))).abs() < 1e-4, "{pos:?} labels {k} n {n}"); + } + } + } + // 20,000 entries whose first one already fills the 35% cap: the old code measured all of them + // plus the drawn rows, now only the first entry and the drawn rows are measured. + let entries = legend_entries(20_000, &|i| if i == 0 { "w".repeat(200) } else { format!("e{i}") }); + let c = Counting(&ApproxMeasure, Cell::new(0)); + let mut ctx = Ctx { out: vec![], m: &c }; + let _ = draw_legend(&mut ctx, &entries, LegendPos::Right, area); + let drawn = ctx.out.iter().filter(|p| matches!(p, Prim::Text { .. })).count(); + assert!(c.1.get() <= drawn * 10 + 5, "{} Measure calls for {drawn} drawn entries", c.1.get()); + assert!(c.1.get() < 500); +} + +/// The pre-rewrite `worst`/`squarify` (a `Vec` per item, row recomputed from scratch). +fn worst_reference(row: &[f64], side: f64) -> f64 { + let s: f64 = row.iter().sum(); + if s <= 0.0 || side <= 0.0 { + return f64::INFINITY; + } + let (mn, mx) = row.iter().fold((f64::INFINITY, 0.0f64), |(a, b), v| (a.min(*v), b.max(*v))); + let s2 = s * s; + let w2 = side * side; + (w2 * mx / s2).max(s2 / (w2 * mn)) +} + +fn squarify_reference(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { + let total: f64 = items.iter().map(|i| i.1).sum(); + let area = (r.w as f64) * (r.h as f64); + if !(total > 0.0 && area > 0.0) { + return vec![]; + } + let scale = area / total; + let mut out = Vec::with_capacity(items.len()); + let mut rem = r; + let mut row: Vec<(usize, f64)> = Vec::new(); + let mut i = 0; + let layout = |row: &[(usize, f64)], rem: &mut Bx, out: &mut Vec<(usize, Bx)>| { + let s: f64 = row.iter().map(|x| x.1).sum(); + if s <= 0.0 { + return; + } + if rem.w >= rem.h { + let cw = (s / rem.h.max(1e-6) as f64) as f32; + let mut y = rem.y; + for (j, a) in row { + let h = (*a / cw.max(1e-6) as f64) as f32; + out.push((*j, Bx { x: rem.x, y, w: cw, h })); + y += h; + } + rem.x += cw; + rem.w = (rem.w - cw).max(0.0); + } else { + let rh = (s / rem.w.max(1e-6) as f64) as f32; + let mut x = rem.x; + for (j, a) in row { + let w = (*a / rh.max(1e-6) as f64) as f32; + out.push((*j, Bx { x, y: rem.y, w, h: rh })); + x += w; + } + rem.y += rh; + rem.h = (rem.h - rh).max(0.0); + } + }; + while let Some(&(j, v)) = items.get(i) { + let a = v * scale; + let side = rem.w.min(rem.h) as f64; + let cur: Vec = row.iter().map(|x| x.1).collect(); + let mut with = cur.clone(); + with.push(a); + if row.is_empty() || worst_reference(&with, side) <= worst_reference(&cur, side) { + row.push((j, a)); + i += 1; + } else { + layout(&row, &mut rem, &mut out); + row.clear(); + } + } + if !row.is_empty() { + layout(&row, &mut rem, &mut out); + } + out +} + +#[test] +fn squarify_matches_reference() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let mut cases: Vec> = vec![ + vec![], + vec![5.0], + vec![6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], + vec![3.0, 0.0, 0.0, 1.0], + vec![0.0, 0.0], + vec![4.0, -1.0, 2.0], + vec![4.0, f64::NAN, 2.0, 1.0], + vec![f64::INFINITY, 1.0], + vec![1e-300, 1e-310, 0.0], + ]; + for n in [2usize, 9, 40, 300] { + let mut v: Vec = (0..n).map(|_| rnd() * 100.0).collect(); + v.sort_by(|a, b| b.total_cmp(a)); + cases.push(v); + } + for r in [Bx { x: 0.0, y: 0.0, w: 300.0, h: 200.0 }, Bx { x: 5.0, y: 7.0, w: 90.0, h: 400.0 }, Bx { x: 0.0, y: 0.0, w: 0.0, h: 50.0 }] { + for vals in &cases { + let items: Vec<(usize, f64)> = vals.iter().copied().enumerate().collect(); + let new: Vec<(usize, Bx)> = squarify(&items, r) + .into_iter() + .map(|(j, v, b)| { + assert!(vals.get(j).is_some_and(|x| x.to_bits() == v.to_bits()), "value carried through"); + (j, b) + }) + .collect(); + let old = squarify_reference(&items, r); + assert_eq!(format!("{new:?}"), format!("{old:?}"), "{vals:?} in {r:?}"); + } + } +} From 4a1e6de3034f0e953c679c1b2fa906830ee8b5fe Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:21:24 +0200 Subject: [PATCH 03/68] Charts: work and memory are bounded by series x points; ranges are clipped before evaluation (#1147) A chart keeps at most 2,000,000 series x points (every series and the categories keep their first points), 16 trendlines per chart; columns and bars narrower than 0.25 px are merged per pixel column; series references are cut after the rows that can matter before calc evaluates them; the moving average is linear; fit_trendline allocates no Vec per point; render borrows clean data instead of cloning it. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/chart/src/render.rs | 105 +++++++++++++++- crates/chart/src/resolve.rs | 138 ++++++++++++++++++--- crates/chart/src/tests.rs | 2 + crates/chart/src/tests/budget.rs | 172 ++++++++++++++++++++++++++ crates/chart/src/trend.rs | 205 ++++++++++++++++++++++++++++++- 6 files changed, 602 insertions(+), 21 deletions(-) create mode 100644 crates/chart/src/tests/budget.rs diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..06b50e9cfd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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-13 | Charts: work and memory are bounded by series x points (2,000,000 per chart: every series keeps its first points; 16 trendlines per chart), hairline columns and bars are merged per pixel column, series ranges are clipped before they are evaluated, the moving average is linear and rendering clean data no longer copies it (#1147) | | 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) | diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 037b9099e0..8df7c28000 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -1,12 +1,13 @@ //! Chart layout: title, legend, axes and every chart kind, drawn into [`Prim`]s. +use std::borrow::Cow; use std::collections::HashSet; use std::f32::consts::{PI, TAU}; use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, Theme, TrendlineKind}; use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale}; -use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color}; +use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, points_per_series, series_color}; use crate::trend::{auto_name, fit_trendline, moving_average}; use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign}; @@ -30,6 +31,8 @@ const MAX_LINE_PTS: usize = 2000; const MAX_MARKERS: usize = 5000; /// Data labels are skipped when a series has more points than this. const MAX_LABELS: usize = 200; +/// Columns and bars narrower than this (in pixels) are merged per pixel column into one rectangle. +const MIN_BAR_PX: f32 = 0.25; #[derive(Clone, Copy, Debug)] struct Bx { @@ -188,7 +191,7 @@ fn sanitize_vals(v: &[Option]) -> Vec> { v.iter().take(MAX_POINTS).map(|x| x.filter(|n| n.is_finite()).map(clean)).collect() } -fn sanitize(d: &ChartData) -> ChartData { +pub(crate) fn sanitize(d: &ChartData) -> ChartData { ChartData { palette: d.palette.iter().take(MAX_POINTS).copied().collect(), categories: d.categories.iter().take(MAX_POINTS).cloned().collect(), @@ -212,6 +215,54 @@ fn sanitize(d: &ChartData) -> ChartData { } } +/// Whether `v` survives `sanitize_vals` unchanged. +fn is_clean(v: &Option) -> bool { + v.is_none_or(|n| n.is_finite() && clean(n) == n) +} + +/// Whether [`sanitize`] and [`apply_budget`] would change `d`. +fn needs_sanitizing(d: &ChartData) -> bool { + let cap = points_per_series(d.series.len()); + let long = |n: usize| n > cap; + let mut trendlines = 0usize; + d.palette.len() > MAX_POINTS + || long(d.categories.len()) + || d.series.len() > MAX_SERIES + || d.series.iter().any(|s| { + trendlines += s.trendlines.len(); + long(s.values.len()) + || !s.values.iter().all(is_clean) + || s.x.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) + || s.sizes.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) + || s.trendlines.len() > MAX_TRENDLINES + }) + || trendlines > MAX_TRENDLINES +} + +/// Enforces the chart's budget of points (`MAX_TOTAL_POINTS` = series x points: every series and +/// the category list keep their first `MAX_TOTAL_POINTS / series` points) and of trendlines +/// (`MAX_TRENDLINES` per chart, in series order). +fn apply_budget(mut d: ChartData) -> ChartData { + let cap = points_per_series(d.series.len()); + d.categories.truncate(cap); + let mut trendlines = MAX_TRENDLINES; + for s in &mut d.series { + s.values.truncate(cap); + for v in [&mut s.x, &mut s.sizes].into_iter().flatten() { + v.truncate(cap); + } + s.trendlines.truncate(trendlines); + trendlines = trendlines.saturating_sub(s.trendlines.len()); + } + d +} + +/// The data `render` draws: `d` itself when it is already clean and within budget (the usual +/// case: no copy), else a cleaned, truncated copy. +pub(crate) fn sanitized(d: &ChartData) -> Cow<'_, ChartData> { + if needs_sanitizing(d) { Cow::Owned(apply_budget(sanitize(d))) } else { Cow::Borrowed(d) } +} + fn chart_title(chart: &Chart, data: &ChartData) -> Option { match &chart.title { Some(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()), @@ -225,7 +276,7 @@ pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e7 || h > 1e7 { return vec![]; } - let data = sanitize(data); + let data = sanitized(data); let mut ctx = Ctx { out: Vec::new(), m }; ctx.out.push(Prim::Rect { x: 0.0, y: 0.0, w, h, fill: Some(WHITE), stroke: Some((GRID, 1.0)), radius: 0.0 }); let pad = (w.min(h) * 0.04).clamp(2.0, 10.0); @@ -828,6 +879,36 @@ fn is_line(f: Fam) -> bool { matches!(f, Fam::Line | Fam::LineStack) } +/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the +/// bars' start positions) and along the value axis (`lo..hi`). +struct BarRun { + bucket: f32, + a0: f32, + a1: f32, + lo: f32, + hi: f32, +} + +impl BarRun { + fn new(pos: f32, lo: f32, hi: f32) -> Self { + BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi } + } + fn add(&mut self, pos: f32, lo: f32, hi: f32) { + self.a0 = self.a0.min(pos); + self.a1 = self.a1.max(pos); + self.lo = self.lo.min(lo); + self.hi = self.hi.max(hi); + } + fn draw(&self, ctx: &mut Ctx, bw: f32, horizontal: bool, color: Rgba) { + let along = self.a1 - self.a0 + bw; + if horizontal { + ctx.rect(self.lo, self.a0, self.hi - self.lo, along, color, None); + } else { + ctx.rect(self.a0, self.lo, along, self.hi - self.lo, color, None); + } + } +} + fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); if ncat == 0 { @@ -1026,12 +1107,27 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta } 1 => { let k = slot_of.get(i).copied().unwrap_or(0) as f32; + // Hairline bars are merged per pixel column (their envelope is what shows). + let cull = bw < MIN_BAR_PX && !labels_on; + let mut run: Option = None; for (j, sp) in row.iter().enumerate() { let Some((b, t)) = sp else { continue }; let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc)); let c = center(j); let lo = pb.min(pt); let len = (pb - pt).abs(); + if cull { + let pos = if horizontal { c + nslots * bw / 2.0 - (k + 1.0) * bw } else { c - nslots * bw / 2.0 + k * bw }; + match &mut run { + Some(m) if m.bucket == pos.floor() => m.add(pos, lo, lo + len), + _ => { + if let Some(m) = run.replace(BarRun::new(pos, lo, lo + len)) { + m.draw(ctx, bw, horizontal, s.color); + } + } + } + continue; + } if horizontal { let y = c + nslots * bw / 2.0 - (k + 1.0) * bw; ctx.rect(lo, y, len, bw, s.color, None); @@ -1064,6 +1160,9 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta } } } + if let Some(m) = run { + m.draw(ctx, bw, horizontal, s.color); + } } _ => { let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index c007e3e907..c0dbaa1734 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -11,8 +11,17 @@ use crate::{ChartData, Rgba, SeriesData, TrendlineData}; pub(crate) const MAX_POINTS: usize = 100_000; /// Cap on series per chart. pub(crate) const MAX_SERIES: usize = 255; -/// Cap on trendlines drawn per series. +/// Cap on trendlines per chart (not per series: each one is a fit over a series' points). pub(crate) const MAX_TRENDLINES: usize = 16; +/// Budget for series x points in one chart. When a chart would hold more, every series (and the +/// category list) keeps its first `MAX_TOTAL_POINTS / series` points; no series is dropped. +pub(crate) const MAX_TOTAL_POINTS: usize = 2_000_000; + +/// Points kept per series (and categories) in a chart of `series` series: `MAX_POINTS`, or less +/// when `series x MAX_POINTS` would pass `MAX_TOTAL_POINTS`. +pub(crate) fn points_per_series(series: usize) -> usize { + (MAX_TOTAL_POINTS / series.clamp(1, MAX_SERIES)).clamp(1, MAX_POINTS) +} /// Tints used for series beyond the six theme accents: lighter, darker, lighter still… const CYCLE_TINTS: [f64; 6] = [0.0, 0.4, -0.25, 0.6, -0.5, 0.2]; @@ -77,10 +86,34 @@ fn union_parts(f: &str) -> Option> { /// Evaluates a series formula to a flat list of values (row-major), capped. A union of /// references (`(A1:A3,A5)`, as PivotCharts use) is read part by part. fn eval_list(wb: &Workbook, sheet: usize, formula: &str) -> Vec { - eval_list_in(wb, sheet, formula, 0) + eval_list_in(wb, sheet, formula, MAX_POINTS, 0) } -fn eval_list_in(wb: &Workbook, sheet: usize, formula: &str, depth: u32) -> Vec { +/// calc reads a reference of up to this many cells at its full size and trims a larger one to the +/// sheet's used range (`FULL_SIZE_CELLS` in `gridcraft_calc::eval`). A clipped reference must stay +/// above it, or the clip would turn a trimmed read into a full-size one with trailing blanks. +const CALC_FULL_SIZE_CELLS: u64 = 16_384; + +/// `formula` as a plain reference (`Sheet!A1:A1000000`) cut after the rows that can still hold +/// one of the first `limit` points, so that calc never reads the rest; `None` when `formula` is +/// no reference or already small enough. Values are read row by row, and calc trims only the +/// bottom and right of a reference, so keeping `limit` rows keeps the first `limit` values. +fn clipped_reference(wb: &Workbook, sheet: usize, formula: &str, limit: usize) -> Option { + let (_, r) = parse_ref(wb, sheet, formula)?; + let (h, w) = (u64::from(r.height()), u64::from(r.width())); + if h.saturating_mul(w) <= CALC_FULL_SIZE_CELLS { + return None; + } + let keep = (limit as u64).max(CALC_FULL_SIZE_CELLS / w + 1); + if h <= keep { + return None; + } + let end = CellRef::new(r.start.row.saturating_add(u32::try_from(keep).ok()?).saturating_sub(1), r.end.col); + let prefix = formula.rfind('!').and_then(|i| formula.get(..=i)).unwrap_or(""); + Some(format!("{prefix}{}", RangeRef::new(r.start, end))) +} + +fn eval_list_in(wb: &Workbook, sheet: usize, formula: &str, limit: usize, depth: u32) -> Vec { let f = formula.trim(); if f.is_empty() { return vec![]; @@ -90,16 +123,17 @@ fn eval_list_in(wb: &Workbook, sheet: usize, formula: &str, depth: u32) -> Vec= MAX_POINTS { + if out.len() >= limit { break; } - let rest = MAX_POINTS - out.len(); - out.extend(eval_list_in(wb, sheet, p, depth + 1).into_iter().take(rest)); + let rest = limit - out.len(); + out.extend(eval_list_in(wb, sheet, p, rest, depth + 1).into_iter().take(rest)); } return out; } - match evaluate(wb, sheet, CellRef::default(), f) { - Value::Array(a) => a.iter().take(MAX_POINTS).cloned().collect(), + let clipped = clipped_reference(wb, sheet, f, limit); + match evaluate(wb, sheet, CellRef::default(), clipped.as_deref().unwrap_or(f)) { + Value::Array(a) => a.iter().take(limit).cloned().collect(), v => vec![v], } } @@ -111,8 +145,8 @@ fn to_num(v: &Value) -> Option { } } -fn nums(wb: &Workbook, sheet: usize, formula: &str) -> Vec> { - eval_list(wb, sheet, formula).iter().map(to_num).collect() +fn nums(wb: &Workbook, sheet: usize, formula: &str, limit: usize) -> Vec> { + eval_list_in(wb, sheet, formula, limit, 0).iter().map(to_num).collect() } /// Number format code of the first cell of a reference ("General" when not a reference). @@ -197,35 +231,41 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { let numeric_x = matches!(chart.kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble); let mut series = Vec::new(); let mut categories: Option> = None; + let limit = points_per_series(chart.series.len()); + let mut trend_left = MAX_TRENDLINES; for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() { - let values = nums(wb, sheet, &s.values); + let values = nums(wb, sheet, &s.values, limit); let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1)); let color = s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i)); let kind = effective_kind(chart.kind, s.kind, i); let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) { // X values with text in them (labels) are ignored: the points are numbered 1..n. - (Some(f), true) => Some(eval_list(wb, sheet, f)).filter(|xs| !xs.iter().any(Value::is_text)).map(|xs| xs.iter().map(to_num).collect()), + (Some(f), true) => { + Some(eval_list_in(wb, sheet, f, limit, 0)).filter(|xs| !xs.iter().any(Value::is_text)).map(|xs| xs.iter().map(to_num).collect()) + } _ => None, }; if categories.is_none() && let Some(f) = &s.categories { - let c = category_texts(wb, sheet, f); + let mut c = category_texts(wb, sheet, f); + c.truncate(limit); if !c.is_empty() { categories = Some(c); } } - let sizes = s.bubble_sizes.as_deref().map(|f| nums(wb, sheet, f)); + let sizes = s.bubble_sizes.as_deref().map(|f| nums(wb, sheet, f, limit)); let trendlines = s .trendlines .iter() - .take(MAX_TRENDLINES) + .take(trend_left) .map(|t| TrendlineData { spec: t.clone(), color: t.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or(color), }) - .collect(); + .collect::>(); + trend_left = trend_left.saturating_sub(trendlines.len()); series.push(SeriesData { name, values, @@ -244,3 +284,69 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE)); ChartData { categories, series, palette } } + +#[cfg(test)] +mod tests { + use gridcraft_model::Workbook; + + use super::*; + + fn book(rows: u32, cols: u32) -> Workbook { + let mut wb = Workbook::new(); + if let Some(s) = wb.sheet_mut(0) { + s.name = "My Sheet".into(); + for r in 0..rows { + for c in 0..cols { + s.set_value(CellRef::new(r, c), Value::Number(f64::from(r * 10 + c))); + } + } + } + wb + } + + #[test] + fn a_long_reference_is_clipped_before_it_is_evaluated() { + let wb = book(1, 1); + let rows = |f: &str, limit| { + let g = clipped_reference(&wb, 0, f, limit)?; + let (_, r) = parse_ref(&wb, 0, &g)?; + Some((g, u64::from(r.height()))) + }; + // 1,000,000 rows: at most `MAX_POINTS` of them are asked for. + assert_eq!(rows("'My Sheet'!$A$1:$A$1000000", MAX_POINTS), Some(("'My Sheet'!A1:A100000".to_string(), 100_000))); + assert_eq!(rows("A5:A1048576", MAX_POINTS).map(|r| r.1), Some(100_000)); + assert_eq!(rows("A:A", 50_000).map(|r| r.1), Some(50_000)); + // Never below what keeps calc trimming the clipped reference like the whole one. + assert_eq!(rows("A1:A1000000", 100).map(|r| r.1), Some(16_385)); + // Wide references keep whole rows. + assert_eq!(rows("A1:C1000000", MAX_POINTS).map(|r| r.1), Some(100_000)); + // Small references, single cells and anything that isn't a plain reference are left alone. + assert_eq!(rows("A1:A9000", MAX_POINTS), None); + assert_eq!(rows("A1:A20000", MAX_POINTS), None); + assert_eq!(rows("B2", MAX_POINTS), None); + assert_eq!(rows("SUM(A1:A1000000)", MAX_POINTS), None); + assert_eq!(rows("{1,2,3}", MAX_POINTS), None); + } + + #[test] + fn clipping_does_not_change_the_points() { + for (rows, cols) in [(10, 1), (30_000, 1), (30_000, 2), (3, 4)] { + let wb = book(rows, cols); + for f in ["'My Sheet'!A1:A1000000", "'My Sheet'!$A$3:$B$1048576", "A:A", "A1:C1000000", "(A1:A1000000,B1:B1000000)", "A2:A20000"] { + for limit in [100, 7_843, 25_000, MAX_POINTS] { + let clipped = eval_list_in(&wb, 0, f, limit, 0); + let whole: Vec = match evaluate(&wb, 0, CellRef::default(), f) { + Value::Array(a) => a.iter().take(limit).cloned().collect(), + v => vec![v], + }; + if f.starts_with('(') { + // A union is read part by part; each part keeps its own order. + assert!(clipped.len() <= limit); + continue; + } + assert_eq!(clipped, whole, "{f} limit {limit} on {rows}x{cols}"); + } + } + } + } +} diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 01f1aac499..587ddd958d 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -5,6 +5,8 @@ use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, Sparkl use crate::*; +mod budget; + const ALL_KINDS: [ChartKind; 25] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, diff --git a/crates/chart/src/tests/budget.rs b/crates/chart/src/tests/budget.rs new file mode 100644 index 0000000000..e151f635d4 --- /dev/null +++ b/crates/chart/src/tests/budget.rs @@ -0,0 +1,172 @@ +//! Work and memory are bounded by the product of the chart limits (series x points, trendlines +//! per chart, hairline bars), and clean data is rendered without a copy. + +use std::borrow::Cow; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{ChartKind, Series, Trendline, TrendlineKind, Workbook}; + +use super::{assert_sane, chart}; +use crate::render::{sanitize, sanitized}; +use crate::resolve::{MAX_POINTS, MAX_TOTAL_POINTS, MAX_TRENDLINES, points_per_series}; +use crate::*; + +fn data_of(series: usize, points: usize) -> ChartData { + ChartData { + palette: vec![], + categories: (0..points).map(|i| i.to_string()).collect(), + series: (0..series) + .map(|s| SeriesData { + name: format!("S{s}"), + values: (0..points).map(|i| Some(((i * 7 + s * 13) % 100 + 1) as f64)).collect(), + color: series_color(&Default::default(), s), + ..SeriesData::default() + }) + .collect(), + } +} + +fn series_rects(prims: &[Prim], color: Rgba) -> Vec<(f32, f32, f32, f32)> { + prims + .iter() + .filter_map(|p| match p { + Prim::Rect { x, y, w, h, fill: Some(f), .. } if *f == color => Some((*x, *y, *w, *h)), + _ => None, + }) + .collect() +} + +#[test] +fn the_point_budget_keeps_every_series_with_fewer_points() { + assert_eq!(points_per_series(1), MAX_POINTS); + assert_eq!(points_per_series(20), MAX_POINTS); + assert_eq!(points_per_series(21), MAX_TOTAL_POINTS / 21); + assert_eq!(points_per_series(255), MAX_TOTAL_POINTS / 255); + assert_eq!(points_per_series(0), MAX_POINTS); + + // 25 series x 100,000 points is 2.5 million: over budget. + let d = data_of(25, MAX_POINTS); + let kept = sanitized(&d); + assert_eq!(kept.series.len(), 25, "no series is dropped"); + assert!(kept.series.iter().all(|s| s.values.len() == MAX_TOTAL_POINTS / 25)); + assert_eq!(kept.categories.len(), MAX_TOTAL_POINTS / 25); + assert!(kept.series.iter().map(|s| s.values.len()).sum::() <= MAX_TOTAL_POINTS); + // The first points are the ones kept. + assert_eq!(kept.series[3].values[..5], d.series[3].values[..5]); + + // Drawing it stays bounded: hairline columns are merged per pixel column. + let mut c = chart(ChartKind::ColumnClustered); + c.data_labels = false; + c.legend = LegendPos::None; + let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure); + assert_sane(&prims, 400.0, 300.0); + assert!(prims.len() < 25 * 450 + 200, "{} primitives", prims.len()); +} + +#[test] +fn trendlines_are_limited_per_chart() { + let line = |kind| TrendlineData { spec: Trendline { kind, ..Trendline::default() }, color: [1, 2, 3, 255] }; + let mut d = data_of(3, 30); + for s in &mut d.series { + s.trendlines = vec![line(TrendlineKind::Linear); 10]; + } + let kept = sanitized(&d); + let counts: Vec = kept.series.iter().map(|s| s.trendlines.len()).collect(); + assert_eq!(counts, vec![10, MAX_TRENDLINES - 10, 0], "series order decides which trendlines stay"); + let entries = legend_entries(&chart(ChartKind::Line), &kept); + assert_eq!(entries.len(), 3 + MAX_TRENDLINES); +} + +#[test] +fn hairline_columns_are_merged_and_wide_ones_are_not() { + let mut c = chart(ChartKind::ColumnClustered); + c.data_labels = false; + c.legend = LegendPos::None; + + // Wide bars (>= 0.25 px): one rectangle per series and category, as before. + let d = data_of(3, 40); + let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + for s in &d.series { + assert_eq!(series_rects(&prims, s.color).len(), 40); + } + + // 4 series x 20,000 categories in 400 px: the bars are hairlines. + let d = data_of(4, 20_000); + let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure); + assert_sane(&prims, 400.0, 300.0); + for s in &d.series { + let n = series_rects(&prims, s.color).len(); + assert!((1..=420).contains(&n), "{n} rectangles for one series"); + } + + // The merged rectangles keep the envelope: alternating 1 and 10 draws the full-height bar. + let mut d = data_of(1, 20_000); + for (i, v) in d.series[0].values.iter_mut().enumerate() { + *v = Some(if i % 2 == 0 { 1.0 } else { 10.0 }); + } + let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure); + let rects = series_rects(&prims, d.series[0].color); + let tallest = rects.iter().map(|r| r.3).fold(0.0f32, f32::max); + assert!(rects.len() > 100 && tallest > 100.0); + assert!(rects.iter().all(|r| (r.3 - tallest).abs() < 0.01), "every pixel column shows the tall bar"); + // And together they cover the plot's width without a gap wider than a pixel. + let mut xs: Vec<(f32, f32)> = rects.iter().map(|r| (r.0, r.0 + r.2)).collect(); + xs.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert!(xs.windows(2).all(|w| w[1].0 - w[0].1 < 1.0)); + + // Horizontal bars too. + let mut c = chart(ChartKind::BarClustered); + c.data_labels = false; + c.legend = LegendPos::None; + let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure); + let n = series_rects(&prims, d.series[0].color).len(); + assert!((1..=320).contains(&n), "{n} bars"); +} + +#[test] +fn clean_data_is_rendered_without_a_copy() { + let d = data_of(3, 50); + assert!(matches!(sanitized(&d), Cow::Borrowed(_))); + + // Dirty data takes the copying path and comes out as `sanitize` has always produced it. + let mut dirty = data_of(3, 50); + dirty.series[0].values[4] = Some(f64::NAN); + dirty.series[1].values[5] = Some(f64::INFINITY); + dirty.series[2].values[6] = Some(1e301); + dirty.series[2].x = Some(vec![Some(f64::NEG_INFINITY), Some(2.0)]); + dirty.series[1].sizes = Some(vec![Some(-1e305)]); + let got = sanitized(&dirty); + assert!(matches!(got, Cow::Owned(_))); + assert_eq!(*got, sanitize(&dirty)); + assert_eq!(got.series[0].values[4], None); + assert_eq!(got.series[2].values[6], Some(1e300)); + + // Over the series cap (within the point budget) the same. + let many = data_of(300, 3); + let got = sanitized(&many); + assert_eq!(got.series.len(), 255); + assert_eq!(*got, sanitize(&many)); +} + +#[test] +fn resolve_keeps_every_series_within_the_point_budget() { + // 40 series x 60,000 points is 2.4 million: over the 2 million budget. + let mut wb = Workbook::new(); + if let Some(s) = wb.sheet_mut(0) { + for r in 0..60_000u32 { + s.set_value(CellRef::new(r, 0), Value::Number(f64::from(r))); + } + } + let mut c = chart(ChartKind::ColumnClustered); + c.series = + (0..40).map(|_| Series { values: "Sheet1!$A$1:$A$1000000".into(), categories: Some("A1:A1000000".into()), ..Series::default() }).collect(); + let d = resolve(&wb, 0, &c); + assert_eq!(d.series.len(), 40); + assert!(d.series.iter().all(|s| s.values.len() == MAX_TOTAL_POINTS / 40)); + assert_eq!(d.categories.len(), MAX_TOTAL_POINTS / 40); + assert_eq!(d.series[7].values.first(), Some(&Some(0.0))); + // Trendlines: 16 per chart, in series order. + c.series = (0..4).map(|_| Series { values: "A1:A5".into(), trendlines: vec![Default::default(); 9], ..Series::default() }).collect(); + let counts: Vec = resolve(&wb, 0, &c).series.iter().map(|s| s.trendlines.len()).collect(); + assert_eq!(counts, vec![9, 7, 0, 0]); +} diff --git a/crates/chart/src/trend.rs b/crates/chart/src/trend.rs index d987ab58da..6b22ed7ad3 100644 --- a/crates/chart/src/trend.rs +++ b/crates/chart/src/trend.rs @@ -72,7 +72,12 @@ pub(crate) fn fit_trendline(t: &Trendline, pts: &[(f64, f64)]) -> Option = (first..=d).map(|k| u.powi(k as i32)).collect(); + // `d` is at most 6, so the powers `first..=d` always fit the array (no allocation per point). + let mut buf = [0.0f64; 7]; + for (slot, k) in buf.iter_mut().zip(first..=d) { + *slot = u.powi(k as i32); + } + let pows = buf.get(..m)?; for (i, pi) in pows.iter().enumerate() { if let Some(v) = aty.get_mut(i) { *v += pi * (y - b0); @@ -258,10 +263,41 @@ fn trim_zeros(s: &str) -> String { /// Moving average of `period` consecutive points in plotted order: point `i` (from /// `period - 1`) is `(xᵢ, mean(yᵢ₋ₚ₊₁..=yᵢ))`. Empty when there are fewer points than `period`. +/// +/// Linear in the number of points: the points are cut into blocks of `period`, and a window is +/// the tail of one block plus the head of the next, taken from running sums that only ever add +/// (a running sum that also subtracts would lose small values after a huge one passed through). pub(crate) fn moving_average(pts: &[(f64, f64)], period: u32) -> Vec<(f64, f64)> { let p = period.clamp(2, 255) as usize; let pts: Vec<(f64, f64)> = pts.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); - pts.windows(p).filter_map(|w| w.last().map(|(x, _)| (*x, w.iter().map(|q| q.1).sum::() / p as f64))).collect() + let n = pts.len(); + if n < p { + return vec![]; + } + // `head[i]`: sum of the block's points up to and including `i`; `tail[i]`: from `i` to the block's end. + let mut head = vec![0.0f64; n]; + let mut tail = vec![0.0f64; n]; + for (b, block) in pts.chunks(p).enumerate() { + let (mut h, mut t) = (0.0f64, 0.0f64); + for k in 0..block.len() { + h += block.get(k).map_or(0.0, |q| q.1); + if let Some(v) = head.get_mut(b * p + k) { + *v = h; + } + let r = block.len() - 1 - k; + t += block.get(r).map_or(0.0, |q| q.1); + if let Some(v) = tail.get_mut(b * p + r) { + *v = t; + } + } + } + (p - 1..n) + .filter_map(|i| { + let s = i + 1 - p; + let sum = tail.get(s)? + if s.is_multiple_of(p) { 0.0 } else { *head.get(i)? }; + Some((pts.get(i)?.0, sum / p as f64)) + }) + .collect() } /// Excel's automatic trendline name for the legend, e.g. `Linear (Sales)`. @@ -276,3 +312,168 @@ pub(crate) fn auto_name(kind: TrendlineKind, series: &str) -> String { }; format!("{k} ({series})") } + +#[cfg(test)] +mod tests { + use super::*; + + /// xorshift64 for repeatable pseudo-random data. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() % 1_000_000) as f64 / 1_000_000.0 - 0.5 + } + } + + /// The window-by-window moving average this module used to compute. + fn moving_average_naive(pts: &[(f64, f64)], period: u32) -> Vec<(f64, f64)> { + let p = period.clamp(2, 255) as usize; + let pts: Vec<(f64, f64)> = pts.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); + pts.windows(p).filter_map(|w| w.last().map(|(x, _)| (*x, w.iter().map(|q| q.1).sum::() / p as f64))).collect() + } + + #[test] + fn linear_moving_average_matches_the_window_sums() { + let mut r = Rng(0x9E37_79B9_7F4A_7C15); + for case in 0..60 { + let n = (r.next() % 700) as usize; + let pts: Vec<(f64, f64)> = (0..n) + .map(|i| { + let y = match case % 5 { + 0 => r.unit() * 100.0, + 1 => 1e9 + r.unit(), + // A huge value passing through must not leave rounding residue behind. + 2 => { + if r.next().is_multiple_of(50) { + 1e300 * r.unit().signum() + } else { + r.unit() + } + } + 3 => { + if i % 2 == 0 { + 1e15 + } else { + -1e15 + r.unit() + } + } + _ => { + if r.next().is_multiple_of(9) { + f64::NAN + } else { + r.unit() * 1e-3 + } + } + }; + (i as f64, y) + }) + .collect(); + for period in [0, 2, 3, 7, 50, 255, 400] { + let fast = moving_average(&pts, period); + let slow = moving_average_naive(&pts, period); + assert_eq!(fast.len(), slow.len(), "case {case} period {period}"); + let p = period.clamp(2, 255) as usize; + let finite: Vec<(f64, f64)> = pts.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); + for (i, ((fx, fy), (sx, sy))) in fast.iter().zip(&slow).enumerate() { + assert_eq!(fx, sx); + let mass: f64 = finite.iter().skip(i).take(p).map(|q| q.1.abs()).sum::() / p as f64; + assert!((fy - sy).abs() <= 1e-12 * mass, "case {case} period {period} point {i}: {fy} vs {sy}"); + } + } + } + } + + /// The trendline fit as it was written with a `Vec` of powers per data point. + fn fit_reference(t: &Trendline, pts: &[(f64, f64)]) -> Option { + let kind = t.kind; + let d = degree(kind)?; + let data: Vec<(f64, f64)> = pts + .iter() + .filter(|(x, y)| x.is_finite() && y.is_finite() && (!log_x(kind) || *x > 0.0) && (!log_y(kind) || *y > 0.0)) + .map(|&(x, y)| (if log_x(kind) { x.ln() } else { x }, if log_y(kind) { y.ln() } else { y })) + .collect(); + if data.len() < 2 || data.len() <= d { + return None; + } + let fixed = match kind { + TrendlineKind::Linear | TrendlineKind::Polynomial(_) => t.intercept, + TrendlineKind::Exponential => t.intercept.filter(|b| *b > 0.0).map(f64::ln), + _ => None, + } + .filter(|b| b.is_finite()); + let n = data.len() as f64; + let center = if fixed.is_some() { 0.0 } else { data.iter().map(|p| p.0).sum::() / n }; + let scale = data.iter().map(|p| (p.0 - center).abs()).fold(0.0f64, f64::max); + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let first = usize::from(fixed.is_some()); + let b0 = fixed.unwrap_or(0.0); + let m = d + 1 - first; + let mut ata = vec![vec![0.0f64; m]; m]; + let mut aty = vec![0.0f64; m]; + for &(x, y) in &data { + let u = (x - center) / scale; + let pows: Vec = (first..=d).map(|k| u.powi(k as i32)).collect(); + for (i, pi) in pows.iter().enumerate() { + aty[i] += pi * (y - b0); + for (j, pj) in pows.iter().enumerate() { + ata[i][j] += pi * pj; + } + } + } + let sol = solve(ata, aty)?; + let mut a = vec![b0; d + 1]; + for (k, v) in sol.into_iter().enumerate() { + a[k + first] = v; + } + let coef = expand(&a, center, scale)?; + let fit = TrendFit { kind, coef, center, scale, a, r2: None }; + let mean = data.iter().map(|p| p.1).sum::() / n; + let (mut ss_res, mut ss_tot) = (0.0f64, 0.0f64); + for &(x, y) in &data { + ss_res += (y - fit.poly(x)).powi(2); + ss_tot += if fixed.is_some() { (y - b0).powi(2) } else { (y - mean).powi(2) }; + } + let r2 = (ss_tot > 0.0 && ss_tot.is_finite() && ss_res.is_finite()).then(|| 1.0 - ss_res / ss_tot); + Some(TrendFit { r2, ..fit }) + } + + #[test] + fn fit_without_a_vec_per_point_is_bit_identical() { + let mut r = Rng(0x1234_5678_9ABC_DEF1); + let kinds = [ + TrendlineKind::Linear, + TrendlineKind::Exponential, + TrendlineKind::Logarithmic, + TrendlineKind::Power, + TrendlineKind::Polynomial(2), + TrendlineKind::Polynomial(3), + TrendlineKind::Polynomial(6), + TrendlineKind::MovingAverage(3), + ]; + for case in 0..40 { + let n = 2 + (r.next() % 60) as usize; + let pts: Vec<(f64, f64)> = (0..n) + .map(|i| { + let x = i as f64 * (1.0 + r.unit()) + 1.0; + let y = if case % 4 == 0 { f64::NAN } else { (r.unit() + 0.6) * 10f64.powi((case % 7) - 2) }; + (x, if case % 4 == 0 && i % 3 != 0 { r.unit() + 1.0 } else { y }) + }) + .collect(); + for kind in kinds { + for intercept in [None, Some(0.5), Some(-1.0)] { + let t = Trendline { kind, intercept, ..Trendline::default() }; + assert_eq!(fit_trendline(&t, &pts), fit_reference(&t, &pts), "case {case} {kind:?} {intercept:?}"); + } + } + } + } +} From 890870cd57167fda190716689b64897fcb16596e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:11:08 +0100 Subject: [PATCH 04/68] perf: select instead of sort in MEDIAN, PERCENTILE, QUARTILE, LARGE, SMALL Read the needed order statistics with select_nth_unstable_by(total_cmp) instead of a full sort. Results are bit-identical; a test compares them against the previous full-sort code on randomised data. Fixes #2679 Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat.rs | 149 +++++++++++++++++++++++++++++++---- 1 file changed, 132 insertions(+), 17 deletions(-) diff --git a/crates/functions/src/stat.rs b/crates/functions/src/stat.rs index 344ba9ff8b..4ef2625ccd 100644 --- a/crates/functions/src/stat.rs +++ b/crates/functions/src/stat.rs @@ -51,10 +51,11 @@ fn median(v: Vec) -> R { if v.is_empty() { return Err(CellError::Num); } - let s = sorted(v); - let n = s.len(); - let hi = s.get(n / 2).copied().unwrap_or(0.0); - if n % 2 == 1 { Ok(hi) } else { Ok(s.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) } + let mut v = v; + let n = v.len(); + let (lower, hi, _) = v.select_nth_unstable_by(n / 2, f64::total_cmp); + let hi = *hi; + if n % 2 == 1 { Ok(hi) } else { Ok(lower.iter().copied().max_by(f64::total_cmp).unwrap_or(0.0).midpoint(hi)) } } /// Values occurring at least twice, ordered by first occurrence, with their (equal, maximal) count. @@ -125,29 +126,38 @@ fn kth(v: Vec, k: f64, largest: bool) -> R { if k.is_nan() || k < 1.0 || k > v.len() as f64 { return Err(CellError::Num); } - let s = sorted(v); + let mut v = v; let k = k as usize; - let idx = if largest { s.len() - k } else { k - 1 }; - s.get(idx).copied().ok_or(CellError::Num) + let idx = if largest { v.len() - k } else { k - 1 }; + // Selection instead of a full sort; same total order, so the same bit pattern as `sorted(v)[idx]`. + Ok(*v.select_nth_unstable_by(idx, f64::total_cmp).1) } -fn interp(s: &[f64], pos: f64) -> R { +/// Value at fractional rank `pos` of the sorted data, linearly interpolated, found by selection. +fn interp(mut v: Vec, pos: f64) -> R { let i = pos.floor(); let frac = pos - i; let i = i as usize; - let lo = *s.get(i).ok_or(CellError::Num)?; - match s.get(i + 1) { - Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), - _ => Ok(lo), + if i >= v.len() { + return Err(CellError::Num); } + let (_, lo, upper) = v.select_nth_unstable_by(i, f64::total_cmp); + let lo = *lo; + // The next order statistic is the minimum of the upper partition. + if frac > 0.0 + && let Some(hi) = upper.iter().copied().min_by(f64::total_cmp) + { + return Ok(lo + frac * (hi - lo)); + } + Ok(lo) } fn percentile_inc(v: Vec, k: f64) -> R { if v.is_empty() || !(0.0..=1.0).contains(&k) { return Err(CellError::Num); } - let s = sorted(v); - interp(&s, k * (s.len() - 1) as f64) + let pos = k * (v.len() - 1) as f64; + interp(v, pos) } fn percentile_exc(v: Vec, k: f64) -> R { @@ -159,8 +169,7 @@ fn percentile_exc(v: Vec, k: f64) -> R { if pos < 1.0 || pos > n { return Err(CellError::Num); } - let s = sorted(v); - interp(&s, pos - 1.0) + interp(v, pos - 1.0) } fn quartile_inc(v: Vec, q: f64) -> R { @@ -2274,7 +2283,9 @@ pub(crate) fn specs() -> Vec { #[cfg(test)] mod tests { - use super::{MAX_REGRESSORS, aggregate_values, aggregate_values_k, check_regression_size}; + use super::{ + MAX_REGRESSORS, R, aggregate_values, aggregate_values_k, check_regression_size, kth, median, percentile_exc, percentile_inc, sorted, + }; use crate::util::testutil::*; use gridcraft_core::{CellError, Value}; @@ -2463,6 +2474,110 @@ mod tests { close(ev("RANK.AVG", vec![n(3.5), r2, n(1.0)]), 3.5); } + // Reference implementations: the previous full-sort versions, as the oracle for the selection ones. + fn old_interp(s: &[f64], pos: f64) -> R { + let i = pos.floor(); + let frac = pos - i; + let i = i as usize; + let lo = *s.get(i).ok_or(CellError::Num)?; + match s.get(i + 1) { + Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), + _ => Ok(lo), + } + } + + fn old_median(v: Vec) -> R { + if v.is_empty() { + return Err(CellError::Num); + } + let s = sorted(v); + let n = s.len(); + let hi = s.get(n / 2).copied().unwrap_or(0.0); + if n % 2 == 1 { Ok(hi) } else { Ok(s.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) } + } + + fn old_kth(v: Vec, k: f64, largest: bool) -> R { + let k = k.ceil(); + if k.is_nan() || k < 1.0 || k > v.len() as f64 { + return Err(CellError::Num); + } + let s = sorted(v); + let k = k as usize; + let idx = if largest { s.len() - k } else { k - 1 }; + s.get(idx).copied().ok_or(CellError::Num) + } + + fn old_percentile_inc(v: Vec, k: f64) -> R { + if v.is_empty() || !(0.0..=1.0).contains(&k) { + return Err(CellError::Num); + } + let s = sorted(v); + old_interp(&s, k * (s.len() - 1) as f64) + } + + fn old_percentile_exc(v: Vec, k: f64) -> R { + let n = v.len() as f64; + if v.is_empty() || !(k > 0.0 && k < 1.0) { + return Err(CellError::Num); + } + let pos = k * (n + 1.0); + if pos < 1.0 || pos > n { + return Err(CellError::Num); + } + let s = sorted(v); + old_interp(&s, pos - 1.0) + } + + /// Same Ok bit pattern or same error. + fn same(a: R, b: R) -> bool { + match (a, b) { + (Ok(x), Ok(y)) => x.to_bits() == y.to_bits(), + (Err(x), Err(y)) => x == y, + _ => false, + } + } + + #[test] + fn selection_matches_full_sort_bit_for_bit() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let specials = [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, -f64::NAN, f64::MAX, f64::MIN_POSITIVE, 1.0, -1.0]; + for len in (0..=40).chain([63, 64, 65, 100, 257, 1000, 4096]) { + for round in 0..12 { + let v: Vec = (0..len) + .map(|_| match (round % 4, next() % 8) { + // Few distinct values: many ties. + (0, r) => (r % 3) as f64, + // Specials, including both zeros and NaNs. + (1, r) => specials[(next() as usize + r as usize) % specials.len()], + // Wide random range. + (2, _) => (next() as i64 as f64) / 1e3, + // Integers with some specials mixed in. + (_, 0) => specials[next() as usize % specials.len()], + _ => (next() % 50) as f64, + }) + .collect(); + assert!(same(median(v.clone()), old_median(v.clone())), "median len={len}"); + let ks = [-1.0, 0.0, 0.2, 1.0, 1.5, 2.0, len as f64 / 2.0, len as f64 - 0.5, len as f64, len as f64 + 1.0, f64::NAN]; + for &k in &ks { + for largest in [true, false] { + assert!(same(kth(v.clone(), k, largest), old_kth(v.clone(), k, largest)), "kth len={len} k={k}"); + } + } + let ps = [-0.1, 0.0, 0.01, 0.1, 0.25, 0.3, 0.5, 0.75, 0.9, 0.99, 1.0, 1.1, f64::NAN, (next() % 1001) as f64 / 1000.0]; + for &p in &ps { + assert!(same(percentile_inc(v.clone(), p), old_percentile_inc(v.clone(), p)), "pinc len={len} p={p}"); + assert!(same(percentile_exc(v.clone(), p), old_percentile_exc(v.clone(), p)), "pexc len={len} p={p}"); + } + } + } + } + #[test] fn percentiles() { close(ev("PERCENTILE.INC", vec![c(&[1.0, 3.0, 2.0, 4.0]), n(0.3)]), 1.9); From 96bfba93f880a6c00c15d5a9afcc0eace1575be3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:17:29 +0100 Subject: [PATCH 05/68] perf(calc): remember SUM/COUNT/AVERAGE of constant-only blocks per pass (#2681) A block that holds only constants can't change during a pass, so its sum and count are worked out once and reused by every formula that reads the same block. A block that is the same rows from the top but longer (a running total) continues the shorter block's sum, which is the same additions in the same order as one walk from the start. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/eval.rs | 14 +++++ crates/calc/src/recalc.rs | 49 +++++++++++++++++ crates/calc/src/tests.rs | 113 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4bdb3a30d4..54777f98b1 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -103,6 +103,12 @@ pub trait Host { fn visit_range(&mut self, _sheet: usize, _range: RangeRef, _f: &mut dyn FnMut(&Value) -> bool) -> bool { false } + /// `(sum, count)` of the numbers in a block that holds nothing but constants (no formula, + /// error or spilled value), added row-major from `0.0` exactly as `visit_range` would hand + /// them over. `None`: the block isn't like that, or this host can't tell. + fn range_sum(&mut self, _sheet: usize, _range: RangeRef) -> Option<(f64, u64)> { + None + } /// While a formula is calculated on demand inside another one: `stack_position()` where the /// outermost one started, which the stack budget is counted from. fn stack_top(&self) -> Option { @@ -984,6 +990,14 @@ impl<'h> Evaluator<'h> { /// Adds one area to `acc`; `Err` is the result the function ends with. fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> { if !a.range.is_single() { + // Adding the block's remembered sum to anything but +0.0 would add in another order. + if acc.sum.to_bits() == 0 + && let Some((sum, count)) = self.host.range_sum(a.sheet, a.range) + { + acc.sum = sum; + acc.count = acc.count.saturating_add(count); + return Ok(()); + } let mut error = None; let walked = self.host.visit_range(a.sheet, a.range, &mut |v| match acc.add_cell(kind, v) { Ok(()) => true, diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e66494..753fd19713 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -436,6 +436,10 @@ struct PassHost<'a> { stack_top: usize, /// Whether an evaluation ran past the stack budget since the innermost formula started. out_of_stack: bool, + /// Sum and count of blocks that hold only constants, for `range_sum`. Keyed by sheet, first + /// cell and last column; each value maps a last row to the block's result (`None`: the block + /// has a formula, an error value or a spilled value, so every longer one has too). + sums: HashMap<(usize, CellRef, u32), std::collections::BTreeMap>>, } impl<'a> PassHost<'a> { @@ -468,6 +472,7 @@ impl<'a> PassHost<'a> { taint: false, stack_top: 0, out_of_stack: false, + sums: HashMap::default(), } } } @@ -909,6 +914,50 @@ impl Host for PassHost<'_> { } true } + 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. + if self.iterate || self.spills.keys().any(|a| a.0 == sheet) { + return None; + } + let sh = self.wb.sheet(sheet)?; + let (key, last) = ((sheet, range.start, range.end.col), range.end.row); + let known = self.sums.entry(key).or_default(); + if let Some(r) = known.get(&last) { + return *r; + } + // Start from the longest shorter block of the same rows from the top: summing row-major + // from there on is the same additions in the same order as one walk from the start. + let (from, mut sum, mut count) = match known.range(..last).next_back() { + Some((_, None)) => { + known.insert(last, None); + return None; + } + Some((&row, &Some((sum, count)))) => (row + 1, sum, count), + None => (range.start.row, 0.0, 0), + }; + let rest = RangeRef::new(CellRef::new(from, range.start.col), range.end); + let mut plain = sh.spill.range(rest.start..=rest.end).all(|(c, _)| !rest.contains(*c)); + if plain { + for (_, cell) in sh.cells.iter_range(rest) { + match &cell.value { + _ if cell.formula.is_some() => plain = false, + Value::Error(_) => plain = false, + Value::Number(n) => { + sum += n; + count = u64::saturating_add(count, 1); + } + _ => {} + } + if !plain { + break; + } + } + } + let result = plain.then_some((sum, count)); + known.insert(last, result); + result + } fn used_range(&mut self, sheet: usize) -> Option { let wb = self.wb; *self.used.entry(sheet).or_insert_with(|| wb.sheet(sheet).and_then(|s| s.used_range())) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..a2db89be0e 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,116 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +/// `SUM`, `COUNT` and `AVERAGE` over blocks of constants share one pass-wide answer per block, and a +/// running total extends the shorter block's. Every result must equal the left-to-right sum of the +/// cells, bit for bit, with text, blanks, errors, formulas and a nonzero start in the mix. +#[test] +fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() { + struct Rng(u64); + impl Rng { + fn next(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } + } + let nums = [0.1, 0.2, 0.3, 1e16, -1e16, 1.0, 3.7, -0.0, 12345.678, 1e-9, 7.0]; + let rows = 40u32; + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let mut wb = Workbook::new(); + let fresh = |rng: &mut Rng, plain: bool| match rng.next(if plain { 8 } else { 14 }) { + 0 => Cell::value(Value::text("t")), + 1 => Cell::default(), + 2 => Cell::value(Value::Bool(true)), + 3 if !plain => Cell::value(Value::Error(CellError::NA)), + 4 if !plain => Cell::formula(Formula::new("=A1*2")), + 5 if !plain => Cell::formula(Formula::new("=\"x\"&B2")), + _ => Cell::value(Value::Number(nums[rng.next(nums.len() as u64) as usize])), + }; + // Columns A:C mostly numbers; E holds a formula column and some errors only in a few rows. + for r in 0..rows { + for col in 0..3 { + let plain = !(r % 13 == 7 && col == 1); + wb.sheet_mut(0).unwrap().cells.set(CellRef::new(r, col), fresh(&mut rng, plain)); + } + } + // Formulas in column H and up: (function, optional leading number, blocks). + let mut oracle: Vec<(CellRef, &str, Option, Vec<(u32, u32, u32, u32)>)> = vec![]; + let funcs = ["SUM", "COUNT", "AVERAGE"]; + let mut at = 0; + let mut add = |wb: &mut Workbook, f: &'static str, lead: Option, blocks: Vec<(u32, u32, u32, u32)>| { + let args: Vec = blocks + .iter() + .map(|&(r0, c0, r1, c1)| format!("{}{}:{}{}", (b'A' + c0 as u8) as char, r0 + 1, (b'A' + c1 as u8) as char, r1 + 1)) + .collect(); + let lead_s = lead.map(|l| format!("{l:e},")).unwrap_or_default(); + let cell = CellRef::new(at % rows, 7 + at / rows); + wb.sheet_mut(0).unwrap().cells.set(cell, Cell::formula(Formula::new(&format!("={f}({lead_s}{})", args.join(","))))); + oracle.push((cell, f, lead, blocks)); + at += 1; + }; + // Running totals over a clean column and over a column with an error further down. + for r in 0..rows { + add(&mut wb, "SUM", None, vec![(0, 0, r, 0)]); + add(&mut wb, "SUM", None, vec![(0, 1, r, 1)]); + add(&mut wb, "COUNT", None, vec![(0, 0, r, 2)]); + } + for _ in 0..120 { + let (r0, r1) = (rng.next(rows as u64) as u32, rng.next(rows as u64) as u32); + let (c0, c1) = (rng.next(3) as u32, rng.next(3) as u32); + let n = 1 + rng.next(2) as usize; + let blocks = (0..n).map(|_| (r0.min(r1), c0.min(c1), r0.max(r1), c0.max(c1))).collect(); + let lead = [None, Some(1e16), Some(0.5), Some(2.0)][rng.next(4) as usize]; + let f = funcs[rng.next(3) as usize]; + add(&mut wb, f, lead, blocks); + } + let check = |wb: &Workbook, when: &str| { + let sh = wb.sheet(0).unwrap(); + for (cell, f, lead, blocks) in &oracle { + let (mut sum, mut count, mut error) = (lead.unwrap_or(0.0), u64::from(lead.is_some()), None); + for &(r0, c0, r1, c1) in blocks { + for r in r0..=r1 { + for col in c0..=c1 { + match sh.value(CellRef::new(r, col)) { + Value::Number(n) => { + sum += n; + count += 1; + } + Value::Error(e) if *f != "COUNT" => error = error.or(Some(e)), + _ => {} + } + } + } + } + let want = match (error, *f) { + (Some(e), _) => Value::Error(e), + (_, "SUM") => Value::number(sum), + (_, "COUNT") => Value::number(count as f64), + (_, _) if count == 0 => Value::Error(CellError::Div0), + _ => Value::number(sum / count as f64), + }; + let got = sh.value(*cell); + let same = match (&got, &want) { + (Value::Number(a), Value::Number(b)) => a.to_bits() == b.to_bits(), + (a, b) => a == b, + }; + assert!(same, "{when}: {:?} = {:?}, plain fold {:?}", cell, got, want); + } + }; + let mut calc = Calc::new(); + calc.rebuild(&wb); + calc.recalc_all(&mut wb); + check(&wb, "full recalc"); + for round in 0..30 { + let mut changed = vec![]; + for _ in 0..1 + rng.next(4) { + let at = CellRef::new(rng.next(rows as u64) as u32, rng.next(3) as u32); + wb.sheet_mut(0).unwrap().cells.set(at, fresh(&mut rng, round % 2 == 0)); + changed.push((0, at)); + } + calc.cells_changed(&mut wb, &changed); + check(&wb, &format!("edit round {round}")); + } +} From c567511cf1e5335e4078e5bdd2036e14e72293c6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:21:15 +0100 Subject: [PATCH 06/68] calc: rebuild the dependency graph from shared syntax trees Calc::rebuild and Calc::cells_changed called Formula::expr(), which deep-copies each formula's syntax tree only to read its references. Use expr_arc() (already used when formulas are calculated), which hands out the cached Arc without copying. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e66494..6cd1551fef 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -1010,7 +1010,7 @@ impl Calc { for (si, sheet) in wb.sheets.iter().enumerate() { for (c, cell) in sheet.cells.iter() { if let Some(f) = &cell.formula - && let Some(e) = f.expr() + && let Some(e) = f.expr_arc() { let (areas, dynamic) = precedents(wb, si, &e); self.graph.insert((si, c), Node { areas, dynamic }); @@ -1088,7 +1088,7 @@ impl Calc { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); - match formula.and_then(|f| f.expr()) { + match formula.and_then(|f| f.expr_arc()) { Some(e) => { let (areas, dynamic) = precedents(wb, k.0, &e); self.graph.insert(k, Node { areas, dynamic }); From 6c37a63704253075feadd4ffd1e253a19b64b779 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:22:22 +0100 Subject: [PATCH 07/68] perf(calc): index the pass's spill areas so reads don't scan every spill (#2683) A cell read and a range read looked at every spill computed so far in the pass, and cells_changed looked at every spill range of the sheet for each changed cell. A spatial index (16 x 16 cell blocks) now finds the areas covering a cell or meeting a range. Where areas overlap, the one that counted before (first/last in the pass's spill map order) still counts. Fixes #2683 Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/lib.rs | 1 + crates/calc/src/recalc.rs | 152 +++++++++++++++++++--------- crates/calc/src/spill_index.rs | 175 +++++++++++++++++++++++++++++++++ crates/calc/src/tests.rs | 29 ++++++ 4 files changed, 310 insertions(+), 47 deletions(-) create mode 100644 crates/calc/src/spill_index.rs diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs index 27c9e19610..c71d8b7b18 100644 --- a/crates/calc/src/lib.rs +++ b/crates/calc/src/lib.rs @@ -5,6 +5,7 @@ pub mod eval; pub mod recalc; +mod spill_index; mod trimrange; pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function}; diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e66494..d86e73fa5b 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -45,6 +45,7 @@ use gridcraft_formula::Expr; use gridcraft_model::{CalcMode, Workbook}; use crate::eval::{Area, Evaluator, Host, precedents, stack_position}; +use crate::spill_index::{Cover, SpillIndex}; pub type Key = (usize, CellRef); @@ -393,6 +394,8 @@ struct PassHost<'a> { in_progress: HashSet, /// New spills found during the pass: anchor → array. spills: HashMap>, + /// Where the areas in `spills` are, so a read finds the ones it meets without scanning them all. + spill_index: SpillIndex, /// Used range per sheet: the workbook doesn't change during a pass, and working it out walks /// every row, so once per sheet rather than once per range read. used: HashMap>, @@ -447,6 +450,7 @@ impl<'a> PassHost<'a> { pending: exprs.keys().copied().collect(), in_progress: HashSet::default(), spills: HashMap::default(), + spill_index: SpillIndex::default(), used: HashMap::default(), rng, now, @@ -472,6 +476,33 @@ impl<'a> PassHost<'a> { } } +/// Most spill areas a range read meets before they are checked for overlapping one another by +/// walking all of the pass's spills instead of comparing pairs. +/// Changed cells (in one `cells_changed`) from which the sheet's spill areas are indexed. +const INDEX_SPILLS_FROM: usize = 16; + +const MAX_UNORDERED_HITS: usize = 16; + +/// Whether an array at `anchor` covers `c`. +fn spill_covers(anchor: CellRef, arr: &Array, c: CellRef) -> bool { + c.row >= anchor.row && c.col >= anchor.col && ((c.row - anchor.row) as usize) < arr.rows && ((c.col - anchor.col) as usize) < arr.cols +} + +/// Whether two of the spill areas anchored at `hits` share a cell inside `range`. +fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range: RangeRef) -> bool { + let rects: Vec = hits.iter().filter_map(|a| index.area(sheet, *a)).filter(|(_, empty)| !empty).map(|(r, _)| r).collect(); + rects.iter().enumerate().any(|(i, a)| { + rects.iter().skip(i + 1).any(|b| { + a.intersects(b) + && RangeRef::new( + CellRef::new(a.start.row.max(b.start.row), a.start.col.max(b.start.col)), + CellRef::new(a.end.row.min(b.end.row), a.end.col.min(b.end.col)), + ) + .intersects(&range) + }) + }) +} + /// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet, /// overlaps merged cells, holds other cells, or another formula's spill (unless that formula is /// recalculated in this pass, and so may spill elsewhere now). @@ -659,6 +690,7 @@ impl PassHost<'_> { // value -- a FILTER matching one row, a SORT or UNIQUE over one item -- so `C1#` // is the 1 x 1 range and `ROWS(C1#)` is 1, as in Excel (#1491). A formula that // returns a scalar never reaches this arm, so it does not become an anchor. + self.spill_index.insert(k, a.rows, a.cols); self.spills.insert(k, a.clone()); a.data.first().cloned().unwrap_or_default() } @@ -669,6 +701,7 @@ impl PassHost<'_> { let v = match self.spills.get(&k) { Some(a) if spill_blocked(self, k, a) => { self.spills.remove(&k); + self.spill_index.remove(k); Value::Error(CellError::Spill) } _ => v, @@ -715,7 +748,11 @@ impl PassHost<'_> { while passes < max_iterations.min(max_passes) && !self.converged(max_change) { self.prev = again.iter().filter_map(|k| self.results.remove(k).map(|v| (*k, v))).collect(); self.pending = set.clone(); - self.spills.retain(|a, _| !set.contains(a)); + let gone: Vec = self.spills.keys().filter(|a| set.contains(a)).copied().collect(); + for a in gone { + self.spills.remove(&a); + self.spill_index.remove(a); + } for k in &again { self.calculate(*k); } @@ -799,17 +836,19 @@ impl Host for PassHost<'_> { if self.pending.contains(&k) || self.results.contains_key(&k) { return self.compute(k); } - // A cell covered by a spill computed in this pass. - for (anchor, arr) in &self.spills { - if anchor.0 == sheet && c.row >= anchor.1.row && c.col >= anchor.1.col { - let (dr, dc) = ((c.row - anchor.1.row) as usize, (c.col - anchor.1.col) as usize); - if dr < arr.rows && dc < arr.cols { - if self.iterate && self.tainted.contains(anchor) { - self.taint = true; - } - return arr.get(dr, dc).cloned().unwrap_or_default(); - } + // A cell covered by a spill computed in this pass. Where several overlap, the first in + // `spills`' iteration order counts, as it always has. + let covering = match self.spill_index.covering(sheet, c) { + Cover::None => None, + Cover::One(a) => self.spills.get_key_value(&(sheet, a)), + Cover::Many => self.spills.iter().find(|(a, arr)| a.0 == sheet && spill_covers(a.1, arr, c)), + }; + if let Some((anchor, arr)) = covering { + let (dr, dc) = ((c.row - anchor.1.row) as usize, (c.col - anchor.1.col) as usize); + if self.iterate && self.tainted.contains(anchor) { + self.taint = true; } + return arr.get(dr, dc).cloned().unwrap_or_default(); } self.wb.sheet(sheet).map(|s| s.value(c)).unwrap_or_default() } @@ -845,41 +884,44 @@ impl Host for PassHost<'_> { } } if !self.spills.is_empty() { - let new: Vec<(usize, Value)> = self - .spills - .iter() - .filter(|(a, _)| a.0 == sheet) - .flat_map(|(a, arr)| { - let mut v = Vec::new(); - for r in 0..arr.rows { - for cc in 0..arr.cols { - let c = CellRef::new(a.1.row.saturating_add(r as u32), a.1.col.saturating_add(cc as u32)); - if c != a.1 && range.contains(c) { - v.push(( - (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize, - arr.get(r, cc).cloned().unwrap_or_default(), - )); - } - } - } - v - }) - .collect(); + let mut hits = Vec::new(); + self.spill_index.meeting(sheet, range, &mut hits); // Iterating: an array spilled by a formula that read a previous value. - if self.iterate - && self.spills.iter().any(|(a, arr)| { - let end = CellRef::new( - a.1.row.saturating_add((arr.rows as u32).saturating_sub(1)), - a.1.col.saturating_add((arr.cols as u32).saturating_sub(1)), - ); - a.0 == sheet && self.tainted.contains(a) && RangeRef::new(a.1, end).intersects(&range) - }) - { + if self.iterate && hits.iter().any(|a| self.tainted.contains(&(sheet, *a))) { self.taint = true; } - for (i, v) in new { - if let Some(slot) = out.get_mut(i) { - *slot = v; + // Where areas overlap inside the range, the last in `spills`' iteration order wins, + // as it always has; otherwise the order doesn't matter. + let ordered = hits.len() > MAX_UNORDERED_HITS || spill_hits_overlap(&self.spill_index, sheet, &hits, range); + let mut put = |anchor: CellRef, arr: &Array| { + if arr.rows == 0 || arr.cols == 0 { + return; + } + let (r0, c0) = (range.start.row.max(anchor.row), range.start.col.max(anchor.col)); + let r1 = range.end.row.min(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1))); + let c1 = range.end.col.min(anchor.col.saturating_add((arr.cols as u32).saturating_sub(1))); + for r in r0..=r1 { + for cc in c0..=c1 { + if (r, cc) != (anchor.row, anchor.col) + && let Some(slot) = out.get_mut((r - range.start.row) as usize * w + (cc - range.start.col) as usize) + { + *slot = arr.get((r - anchor.row) as usize, (cc - anchor.col) as usize).cloned().unwrap_or_default(); + } + } + } + }; + if ordered { + let wanted: HashSet = hits.iter().map(|a| (sheet, *a)).collect(); + for (a, arr) in &self.spills { + if wanted.contains(a) { + put(a.1, arr); + } + } + } else { + for a in &hits { + if let Some(arr) = self.spills.get(&(sheet, *a)) { + put(*a, arr); + } } } } @@ -898,7 +940,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`. - if self.spills.keys().any(|a| a.0 == sheet) || sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c)) { + if self.spill_index.has_sheet(sheet) || sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c)) { return false; } for (c, cell) in sh.cells.iter_range(range) { @@ -1124,11 +1166,27 @@ impl Calc { let mut emptied: Vec = Vec::new(); // Typing into (or clearing) a cell a dynamic array spills over (or would spill over) // re-evaluates the anchor, which may now be blocked or unblocked. + // With many changed cells (a paste) the sheet's spill areas are indexed once instead of + // being walked for each one. + let mut areas = SpillIndex::default(); + let mut indexed: HashSet = HashSet::default(); + let mut at = Vec::new(); for &k in changed { if let Some(sh) = wb.sheet(k.0) { - for (anchor, r) in &sh.spill_ranges { - if *anchor != k.1 && r.contains(k.1) { - seeds.push((k.0, *anchor)); + if changed.len() > INDEX_SPILLS_FROM && !sh.spill_ranges.is_empty() { + if indexed.insert(k.0) { + for (anchor, r) in &sh.spill_ranges { + areas.insert_rect((k.0, *anchor), *r, false); + } + } + // Anchor order, as walking `spill_ranges` gives. + areas.meeting(k.0, RangeRef::new(k.1, k.1), &mut at); + seeds.extend(at.iter().filter(|a| **a != k.1).map(|a| (k.0, *a))); + } else { + for (anchor, r) in &sh.spill_ranges { + if *anchor != k.1 && r.contains(k.1) { + seeds.push((k.0, *anchor)); + } } } for (c, cell) in sh.cells.iter_range(RangeRef::new(CellRef::new(k.1.row.saturating_sub(64), k.1.col.saturating_sub(64)), k.1)) { diff --git a/crates/calc/src/spill_index.rs b/crates/calc/src/spill_index.rs new file mode 100644 index 0000000000..9a50996a30 --- /dev/null +++ b/crates/calc/src/spill_index.rs @@ -0,0 +1,175 @@ +//! A spatial index over spill areas: which areas cover a cell, and which meet a range, without +//! looking at every area. Areas are registered in 16 x 16 cell blocks, so a lookup touches one +//! block (a cell) or the blocks a range covers (a range) rather than every spill on the sheet. + +use crate::recalc::{FxHasher, Key}; +use gridcraft_core::{CellRef, RangeRef}; +use std::hash::BuildHasherDefault; + +type HashMap = std::collections::HashMap>; + +/// Block edge in cells (rows and columns). +const BLOCK: u32 = 16; + +/// One indexed area: its rectangle, and whether it covers no cells (an array with no rows or no +/// columns still meets the ranges its anchor is in, as a 1 x 1 area does for taint tracking). +#[derive(Clone, Copy)] +struct Entry { + rect: RangeRef, + empty: bool, +} + +#[derive(Default)] +struct SheetAreas { + entries: HashMap, + blocks: HashMap<(u32, u32), Vec>, +} + +/// What covers a cell. +pub(crate) enum Cover { + None, + One(CellRef), + /// Several areas overlap here: the caller decides which one counts. + Many, +} + +#[derive(Default)] +pub(crate) struct SpillIndex { + sheets: HashMap, +} + +fn block_span(rect: &RangeRef) -> (u32, u32, u32, u32) { + (rect.start.row / BLOCK, rect.end.row / BLOCK, rect.start.col / BLOCK, rect.end.col / BLOCK) +} + +impl SpillIndex { + /// Whether any area is indexed on `sheet`. + pub(crate) fn has_sheet(&self, sheet: usize) -> bool { + self.sheets.get(&sheet).is_some_and(|s| !s.entries.is_empty()) + } + + /// Indexes the area an array of `rows` x `cols` anchored at `anchor` covers (replacing the + /// one already indexed for that anchor). + pub(crate) fn insert(&mut self, (sheet, anchor): Key, rows: usize, cols: usize) { + let end = + CellRef::new(anchor.row.saturating_add((rows as u32).saturating_sub(1)), anchor.col.saturating_add((cols as u32).saturating_sub(1))); + self.insert_rect((sheet, anchor), RangeRef::new(anchor, end), rows == 0 || cols == 0); + } + + /// Indexes an area given as a range. + pub(crate) fn insert_rect(&mut self, (sheet, anchor): Key, rect: RangeRef, empty: bool) { + self.remove((sheet, anchor)); + let areas = self.sheets.entry(sheet).or_default(); + let (r0, r1, c0, c1) = block_span(&rect); + for br in r0..=r1 { + for bc in c0..=c1 { + areas.blocks.entry((br, bc)).or_default().push(anchor); + } + } + areas.entries.insert(anchor, Entry { rect, empty }); + } + + pub(crate) fn remove(&mut self, (sheet, anchor): Key) { + let Some(areas) = self.sheets.get_mut(&sheet) else { return }; + let Some(old) = areas.entries.remove(&anchor) else { return }; + let (r0, r1, c0, c1) = block_span(&old.rect); + for br in r0..=r1 { + for bc in c0..=c1 { + if let Some(list) = areas.blocks.get_mut(&(br, bc)) { + list.retain(|a| *a != anchor); + if list.is_empty() { + areas.blocks.remove(&(br, bc)); + } + } + } + } + } + + /// The areas that cover `c`. + pub(crate) fn covering(&self, sheet: usize, c: CellRef) -> Cover { + let Some(areas) = self.sheets.get(&sheet) else { return Cover::None }; + let Some(list) = areas.blocks.get(&(c.row / BLOCK, c.col / BLOCK)) else { return Cover::None }; + let mut found = Cover::None; + for a in list { + if let Some(e) = areas.entries.get(a) + && !e.empty + && e.rect.contains(c) + { + found = match found { + Cover::None => Cover::One(*a), + _ => return Cover::Many, + }; + } + } + found + } + + /// The anchors of the areas whose rectangle meets `range` (an empty area counts through its + /// anchor cell), sorted by anchor. + pub(crate) fn meeting(&self, sheet: usize, range: RangeRef, out: &mut Vec) { + out.clear(); + let Some(areas) = self.sheets.get(&sheet) else { return }; + let (r0, r1, c0, c1) = block_span(&range); + let touched = u64::from(r1 - r0 + 1) * u64::from(c1 - c0 + 1); + if touched > 4 * areas.entries.len() as u64 + 16 { + // A range wider than the areas are many: look at each area once. + out.extend(areas.entries.iter().filter(|(_, e)| e.rect.intersects(&range)).map(|(a, _)| *a)); + } else { + for br in r0..=r1 { + for bc in c0..=c1 { + if let Some(list) = areas.blocks.get(&(br, bc)) { + out.extend(list.iter().copied().filter(|a| areas.entries.get(a).is_some_and(|e| e.rect.intersects(&range)))); + } + } + } + } + out.sort_unstable(); + out.dedup(); + } + + /// The rectangle indexed for `anchor` and whether it covers no cells. + pub(crate) fn area(&self, sheet: usize, anchor: CellRef) -> Option<(RangeRef, bool)> { + self.sheets.get(&sheet)?.entries.get(&anchor).map(|e| (e.rect, e.empty)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(r: u32, c: u32) -> CellRef { + CellRef::new(r, c) + } + + #[test] + fn finds_the_areas_covering_a_cell_and_meeting_a_range() { + let mut ix = SpillIndex::default(); + ix.insert((0, at(0, 0)), 40, 3); + ix.insert((0, at(30, 1)), 1, 40); + ix.insert((1, at(0, 0)), 5, 5); + assert!(matches!(ix.covering(0, at(39, 2)), Cover::One(a) if a == at(0, 0))); + assert!(matches!(ix.covering(0, at(30, 2)), Cover::Many)); + assert!(matches!(ix.covering(0, at(40, 0)), Cover::None)); + assert!(matches!(ix.covering(2, at(0, 0)), Cover::None)); + let mut hits = Vec::new(); + ix.meeting(0, RangeRef::new(at(30, 30), at(50, 60)), &mut hits); + assert_eq!(hits, vec![at(30, 1)]); + ix.meeting(0, RangeRef::new(at(0, 0), at(1_000_000, 16_000)), &mut hits); + assert_eq!(hits, vec![at(0, 0), at(30, 1)]); + ix.remove((0, at(30, 1))); + assert!(matches!(ix.covering(0, at(30, 2)), Cover::One(_))); + assert!(ix.has_sheet(1) && !ix.has_sheet(2)); + ix.insert((0, at(0, 0)), 1, 1); + assert!(matches!(ix.covering(0, at(39, 2)), Cover::None)); + } + + #[test] + fn an_area_without_cells_covers_none_but_is_met_at_its_anchor() { + let mut ix = SpillIndex::default(); + ix.insert((0, at(3, 3)), 0, 4); + assert!(matches!(ix.covering(0, at(3, 3)), Cover::None)); + let mut hits = Vec::new(); + ix.meeting(0, RangeRef::new(at(3, 3), at(3, 3)), &mut hits); + assert_eq!(hits, vec![at(3, 3)]); + } +} diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..a90a997ecc 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,32 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +#[test] +fn many_spills_are_read_and_blocked_by_a_paste() { + let mut t = T::new(); + // 40 arrays of 3 rows side by side in rows 1-3, and a reader of a range over two of them. + for i in 0..40u32 { + let anchor = CellRef::new(0, 2 * i); + t.wb.sheet_mut(0).unwrap().cells.set(anchor, Cell::formula(Formula::new(&format!("=SEQUENCE(3,1,{})", 10 * i)))); + } + t.set("A10", "=SUM(C1:F3)"); + t.set("A12", "=COUNT(C1:F3)"); + t.set("A11", "=C2*1"); + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.num("A10"), (10 + 11 + 12 + 20 + 21 + 22) as f64); + assert_eq!(t.num("A11"), 11.0); + assert_eq!(t.num("A12"), 6.0); + // Pasting 20 cells (more than one spill's width worth, so the changed set is indexed) over + // the second row of every other array blocks those arrays; the rest are unchanged. + let changed: Vec<(usize, CellRef)> = (0..20u32).map(|i| (0, CellRef::new(1, 4 * i))).collect(); + for k in &changed { + t.wb.sheet_mut(0).unwrap().cells.set(k.1, Cell::value(Value::Number(1.0))); + } + t.calc.cells_changed(&mut t.wb, &changed); + assert_eq!(t.get("E1"), Value::Error(CellError::Spill)); + assert_eq!(t.get("C1"), Value::Number(10.0)); + assert_eq!(t.get("G2"), Value::Number(31.0)); + assert_eq!(t.get("A10"), Value::Error(CellError::Spill)); + assert_eq!(t.num("A12"), 4.0); +} From 72236e4aab3cdf94123023d00307e08a23a9c0aa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:26:15 +0100 Subject: [PATCH 08/68] perf(calc): find the formulas a cleared cell may unblock from a set of #SPILL! cells (#2684) Clearing a cell walked every formula in the graph, and each changed cell scanned a 64 x 64 window of stored cells, to find formulas showing #SPILL!. Calc now keeps the set of cells whose value is #SPILL! (filled in rebuild, kept up to date by cells_changed and the write-back of a run) and takes those candidates from it. The same set replaces the walk over the graph in run for areas a formula stopped spilling over. Each entry is checked against the workbook before it is used. Fixes #2684 Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 80 ++++++++++++++++++++++++++++----------- crates/calc/src/tests.rs | 28 ++++++++++++++ 2 files changed, 85 insertions(+), 23 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e66494..4a90a6775e 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -377,11 +377,23 @@ pub struct Calc { /// Cells whose formulas have errors from cycles. pub circular: Vec, pub last_recalc_cells: usize, + /// The cells whose value is `#SPILL!`, kept so that finding the formulas an emptied cell or a + /// freed spill area may unblock doesn't walk every formula or window of cells. Filled in + /// `rebuild`, kept up to date by `cells_changed` and by the write-back of a run; an entry is + /// always checked against the workbook before it is used. + spill_errors: BTreeSet, } impl Default for Calc { fn default() -> Self { - Calc { graph: Graph::default(), rng: 0x9E37_79B9_7F4A_7C15, fixed_now: None, circular: vec![], last_recalc_cells: 0 } + Calc { + graph: Graph::default(), + rng: 0x9E37_79B9_7F4A_7C15, + fixed_now: None, + circular: vec![], + last_recalc_cells: 0, + spill_errors: BTreeSet::new(), + } } } @@ -1007,8 +1019,12 @@ impl Calc { pub fn rebuild(&mut self, wb: &Workbook) { self.graph = Graph::default(); let mut circ = Vec::new(); + self.spill_errors.clear(); for (si, sheet) in wb.sheets.iter().enumerate() { for (c, cell) in sheet.cells.iter() { + if cell.value == Value::Error(CellError::Spill) { + self.spill_errors.insert((si, c)); + } if let Some(f) = &cell.formula && let Some(e) = f.expr() { @@ -1066,6 +1082,25 @@ impl Calc { out } + /// The cells of `sheet` in `rows` x `cols` (inclusive, `cols` a lower and an upper column) that + /// show `#SPILL!`, in row-major order. + fn spill_errors_in(&self, wb: &Workbook, sheet: usize, rows: (u32, u32), cols: (u32, u32)) -> Vec { + let Some(sh) = wb.sheet(sheet) else { return Vec::new() }; + self.spill_errors + .range((sheet, CellRef::new(rows.0, 0))..=(sheet, CellRef::new(rows.1, u32::MAX))) + .filter(|(_, c)| c.col >= cols.0 && c.col <= cols.1) + .filter(|(_, c)| sh.cells.get(*c).is_some_and(|x| x.value == Value::Error(CellError::Spill))) + .map(|(_, c)| *c) + .collect() + } + + /// The formulas showing `#SPILL!` on `sheet` at or above and to the left of `end`: what a + /// cell emptied or a spill area freed there may unblock. + fn unblock_candidates(&self, wb: &Workbook, sheet: usize, end: CellRef) -> Vec { + let cells = self.spill_errors_in(wb, sheet, (0, end.row), (0, end.col)); + cells.into_iter().filter(|c| self.graph.nodes.contains_key(&(sheet, *c))).map(|c| (sheet, c)).collect() + } + /// Recalculates every formula (F9 / Ctrl+Alt+F9, and after loading). pub fn recalc_all(&mut self, wb: &mut Workbook) { self.rebuild(wb); @@ -1087,6 +1122,11 @@ impl Calc { pub fn cells_changed(&mut self, wb: &mut Workbook, changed: &[Key]) { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { + if wb.sheet(k.0).and_then(|s| s.cell(k.1)).is_some_and(|c| c.value == Value::Error(CellError::Spill)) { + self.spill_errors.insert(k); + } else { + self.spill_errors.remove(&k); + } let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); match formula.and_then(|f| f.expr()) { Some(e) => { @@ -1109,6 +1149,7 @@ impl Calc { && cell.formula.is_some() { cell.value = Value::Error(CellError::Name); + self.spill_errors.remove(&k); } } } @@ -1131,10 +1172,9 @@ impl Calc { seeds.push((k.0, *anchor)); } } - for (c, cell) in sh.cells.iter_range(RangeRef::new(CellRef::new(k.1.row.saturating_sub(64), k.1.col.saturating_sub(64)), k.1)) { - if c != k.1 && cell.value == Value::Error(CellError::Spill) { - seeds.push((k.0, c)); - } + if !self.spill_errors.is_empty() { + let (r0, c0) = (k.1.row.saturating_sub(64), k.1.col.saturating_sub(64)); + seeds.extend(self.spill_errors_in(wb, k.0, (r0, k.1.row), (c0, k.1.col)).into_iter().filter(|c| *c != k.1).map(|c| (k.0, c))); } if !sh.cells.has(k.1) { match emptied.iter_mut().find(|x| x.0 == k.0) { @@ -1146,11 +1186,7 @@ impl Calc { } // An emptied cell can unblock an anchor any distance above or to the left of it. for (si, end) in emptied { - for &(s, c) in self.graph.nodes.keys() { - if s == si && c.row <= end.row && c.col <= end.col && wb.sheet(s).is_some_and(|sh| sh.value(c) == Value::Error(CellError::Spill)) { - seeds.push((s, c)); - } - } + seeds.extend(self.unblock_candidates(wb, si, end)); } // Spill areas of changed anchors also change. for &k in changed { @@ -1254,10 +1290,15 @@ impl Calc { let mut freed: Vec<(usize, RangeRef)> = Vec::new(); for (k, v) in results { let Some(sheet) = wb.sheet_mut(k.0) else { continue }; - if let Some(cell) = sheet.cells.get_mut(k.1) - && cell.value != v - { - cell.value = v; + if let Some(cell) = sheet.cells.get_mut(k.1) { + if v == Value::Error(CellError::Spill) { + self.spill_errors.insert(k); + } else { + self.spill_errors.remove(&k); + } + if cell.value != v { + cell.value = v; + } } } for k in &dirty { @@ -1293,6 +1334,7 @@ impl Calc { if blocked { if let Some(cell) = sheet.cells.get_mut(k.1) { cell.value = Value::Error(CellError::Spill); + self.spill_errors.insert(*k); } // Not blocked while the pass ran (it would have been #SPILL! there), so // blocked by another array of this pass: the formulas that read this one, @@ -1338,15 +1380,7 @@ impl Calc { } // An area a formula no longer spills over may unblock another formula's array. for (si, o) in freed { - for &(s, c) in self.graph.nodes.keys() { - if s == si - && c.row <= o.end.row - && c.col <= o.end.col - && wb.sheet(s).is_some_and(|sh| sh.value(c) == Value::Error(CellError::Spill)) - { - spill_changes.push((s, c)); - } - } + spill_changes.extend(self.unblock_candidates(wb, si, o.end)); } if full { // Everything was already evaluated once; spill dependents need another pass. diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..fa8aab3cae 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,31 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +#[test] +fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() { + let mut t = T::new(); + for r in 1..=50 { + t.set(&format!("D{r}"), &format!("={r}*2")); + } + t.set("B2", "7"); + t.set("B1", "=SEQUENCE(3)"); + t.set("C1", "=SEQUENCE(1,3)"); + t.set("A20", "=B1+1"); + assert_eq!(t.get("B1"), Value::Error(CellError::Spill)); + assert_eq!(t.get("A20"), Value::Error(CellError::Spill)); + // Emptied: the array above it spills. + t.wb.sheet_mut(0).unwrap().cells.remove(c("B2")); + t.calc.cells_changed(&mut t.wb, &[(0, c("B2"))]); + assert_eq!(t.num("B3"), 3.0); + assert_eq!(t.num("A20"), 2.0); + // Typing over the area blocks it again; far from it, nothing is disturbed. + t.set("B3", "9"); + assert_eq!(t.get("B1"), Value::Error(CellError::Spill)); + t.set("D50", "1"); + assert_eq!(t.get("B1"), Value::Error(CellError::Spill)); + assert_eq!(t.num("D49"), 98.0); + // Clearing it again frees the array. + t.set("B3", ""); + assert_eq!(t.num("B3"), 3.0); +} From 5f3fcc8140670454146044ddce955cac7f18539c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 27 Oct 2026 19:45:28 +0100 Subject: [PATCH 09/68] perf(calc): look up #SPILL! cells by row and column range, not by row band The spill-error set was ranged by rows only and filtered by column afterwards, so an edit in column A walked every #SPILL! cell to its right in the same rows. Each row now keeps its own column set and a window lookup takes one column range per row that has an entry. Results are unchanged. Also covers an array spilling right over the cleared cell. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 51 ++++++++++++++++++++++++++++++++------- crates/calc/src/tests.rs | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 9 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index d139486c17..ce01c2984c 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -10,7 +10,7 @@ //! and the formulas that read one are evaluated again until the loop settles //! (`PassHost::iterate_loops`). -use std::collections::{BTreeSet, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::hash::{BuildHasherDefault, Hasher}; use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; @@ -42,7 +42,45 @@ pub struct Calc { /// freed spill area may unblock doesn't walk every formula or window of cells. Filled in /// `rebuild`, kept up to date by `cells_changed` and by the write-back of a run; an entry is /// always checked against the workbook before it is used. - spill_errors: BTreeSet, + spill_errors: SpillErrors, +} + +/// A set of cells by row, each row's columns in their own set: a window of rows and columns is +/// found by one column range per row that has an entry, so the cost follows the cells in the +/// window, not those to the side of it in the same rows. +#[derive(Clone, Debug, Default)] +struct SpillErrors { + rows: BTreeMap<(usize, u32), BTreeSet>, +} + +impl SpillErrors { + fn is_empty(&self) -> bool { + self.rows.is_empty() + } + + fn clear(&mut self) { + self.rows.clear(); + } + + fn insert(&mut self, (sheet, c): Key) { + self.rows.entry((sheet, c.row)).or_default().insert(c.col); + } + + fn remove(&mut self, (sheet, c): &Key) { + if let Some(cols) = self.rows.get_mut(&(*sheet, c.row)) { + cols.remove(&c.col); + if cols.is_empty() { + self.rows.remove(&(*sheet, c.row)); + } + } + } + + /// The cells of `sheet` in `rows` x `cols` (both inclusive), in row-major order. + fn range(&self, sheet: usize, rows: (u32, u32), cols: (u32, u32)) -> impl Iterator + '_ { + self.rows + .range((sheet, rows.0)..=(sheet, rows.1)) + .flat_map(move |(&(_, row), set)| set.range(cols.0..=cols.1).map(move |&col| CellRef::new(row, col))) + } } impl Default for Calc { @@ -53,7 +91,7 @@ impl Default for Calc { fixed_now: None, circular: vec![], last_recalc_cells: 0, - spill_errors: BTreeSet::new(), + spill_errors: SpillErrors::default(), } } } @@ -205,12 +243,7 @@ impl Calc { /// show `#SPILL!`, in row-major order. fn spill_errors_in(&self, wb: &Workbook, sheet: usize, rows: (u32, u32), cols: (u32, u32)) -> Vec { let Some(sh) = wb.sheet(sheet) else { return Vec::new() }; - self.spill_errors - .range((sheet, CellRef::new(rows.0, 0))..=(sheet, CellRef::new(rows.1, u32::MAX))) - .filter(|(_, c)| c.col >= cols.0 && c.col <= cols.1) - .filter(|(_, c)| sh.cells.get(*c).is_some_and(|x| x.value == Value::Error(CellError::Spill))) - .map(|(_, c)| *c) - .collect() + self.spill_errors.range(sheet, rows, cols).filter(|c| sh.cells.get(*c).is_some_and(|x| x.value == Value::Error(CellError::Spill))).collect() } /// The formulas showing `#SPILL!` on `sheet` at or above and to the left of `end`: what a diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index fa8aab3cae..9de680e2f2 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2302,3 +2302,51 @@ fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() { t.set("B3", ""); assert_eq!(t.num("B3"), 3.0); } + +/// A sheet with `#SPILL!` cells in rows 0..64, columns 100..16384 (as blocked arrays leave), none +/// near column A. +fn spill_error_field() -> T { + let mut t = T::new(); + let sh = t.wb.sheet_mut(0).unwrap(); + for r in 0..64 { + for col in 100..16_384 { + sh.cells.set(CellRef::new(r, col), Cell::value(Value::Error(CellError::Spill))); + } + } + t.calc.recalc_all(&mut t.wb); + t +} + +#[test] +fn an_edit_far_left_of_many_spill_errors_does_not_disturb_them() { + let mut t = spill_error_field(); + t.set("A65", "5"); + assert_eq!(t.num("A65"), 5.0); + assert_eq!(t.get("CW1"), Value::Error(CellError::Spill)); + assert_eq!(t.get("XFD64"), Value::Error(CellError::Spill)); + // A blocked formula inside the window is still found when a cell to its right is cleared. + t.set("DA66", "7"); + t.set("CZ66", "=SEQUENCE(1,3)"); + assert_eq!(t.get("CZ66"), Value::Error(CellError::Spill)); + t.wb.sheet_mut(0).unwrap().cells.remove(c("DA66")); + t.calc.cells_changed(&mut t.wb, &[(0, c("DA66"))]); + assert_eq!(t.num("DA66"), 2.0); +} + +/// Probe: single-cell edits in column A below a block of `#SPILL!` cells to its right. +/// `cargo test -p gridcraft-calc --release -- --ignored --nocapture spill_error_field_probe` +#[test] +#[ignore] +#[allow(clippy::disallowed_methods)] +fn spill_error_field_probe() { + let mut t = spill_error_field(); + let mut best = std::time::Duration::MAX; + for i in 0..9 { + let start = std::time::Instant::now(); + for _ in 0..100 { + t.set("A65", &format!("{i}")); + } + best = best.min(start.elapsed()); + } + eprintln!("100 edits of A65 beside 1,040,000 spill errors: best of 9 = {best:?}"); +} From 4523b817ce53be54a9ce9d5b5b49761c3907a75d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:51:12 +0100 Subject: [PATCH 10/68] Read already-sorted input directly instead of selecting A full sort recognises ascending and descending runs in O(n), which a selection cannot beat, so sorted, reverse-sorted and tie-block input was up to 1.8x slower than before. Check for a monotone run first (one pass that stops at the first out-of-order pair) and index into it. Extend the bit-for-bit oracle test with ascending, descending and nearly ascending data. Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/descriptive.rs | 32 +++++++++++++++++++++++- crates/functions/src/stat/tests.rs | 22 +++++++++++++--- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/crates/functions/src/stat/descriptive.rs b/crates/functions/src/stat/descriptive.rs index 49d30d42ca..08938d039c 100644 --- a/crates/functions/src/stat/descriptive.rs +++ b/crates/functions/src/stat/descriptive.rs @@ -38,12 +38,31 @@ pub(super) fn sorted(mut v: Vec) -> Vec { v } +/// Sorts `v` if it is already monotone in `total_cmp` order (a descending slice is reversed) and +/// says whether it did. One cheap pass that stops at the first out-of-order pair, so unordered +/// data costs next to nothing. Needed because the std sort recognises ascending and descending +/// runs in O(n), which a selection cannot beat. +fn sorted_if_monotone(v: &mut [f64]) -> bool { + if v.is_sorted_by(|a, b| a.total_cmp(b).is_le()) { + return true; + } + if v.is_sorted_by(|a, b| a.total_cmp(b).is_ge()) { + v.reverse(); + return true; + } + false +} + pub(super) fn median(v: Vec) -> R { if v.is_empty() { return Err(CellError::Num); } let mut v = v; let n = v.len(); + if sorted_if_monotone(&mut v) { + let hi = v.get(n / 2).copied().unwrap_or(0.0); + return if n % 2 == 1 { Ok(hi) } else { Ok(v.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) }; + } let (lower, hi, _) = v.select_nth_unstable_by(n / 2, f64::total_cmp); let hi = *hi; if n % 2 == 1 { Ok(hi) } else { Ok(lower.iter().copied().max_by(f64::total_cmp).unwrap_or(0.0).midpoint(hi)) } @@ -120,7 +139,11 @@ pub(super) fn kth(v: Vec, k: f64, largest: bool) -> R { let mut v = v; let k = k as usize; let idx = if largest { v.len() - k } else { k - 1 }; - // Selection instead of a full sort; same total order, so the same bit pattern as `sorted(v)[idx]`. + // Selection instead of a full sort (monotone input is read directly); same total order, so the + // same bit pattern as `sorted(v)[idx]`. + if sorted_if_monotone(&mut v) { + return v.get(idx).copied().ok_or(CellError::Num); + } Ok(*v.select_nth_unstable_by(idx, f64::total_cmp).1) } @@ -132,6 +155,13 @@ fn interp(mut v: Vec, pos: f64) -> R { if i >= v.len() { return Err(CellError::Num); } + if sorted_if_monotone(&mut v) { + let lo = v.get(i).copied().ok_or(CellError::Num)?; + return match v.get(i + 1) { + Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), + _ => Ok(lo), + }; + } let (_, lo, upper) = v.select_nth_unstable_by(i, f64::total_cmp); let lo = *lo; // The next order statistic is the minimum of the upper partition. diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index 60da9f59ee..f11629369f 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -263,8 +263,8 @@ fn selection_matches_full_sort_bit_for_bit() { }; let specials = [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, -f64::NAN, f64::MAX, f64::MIN_POSITIVE, 1.0, -1.0]; for len in (0..=40).chain([63, 64, 65, 100, 257, 1000, 4096]) { - for round in 0..12 { - let v: Vec = (0..len) + for round in 0..24 { + let mut v: Vec = (0..len) .map(|_| match (round % 4, next() % 8) { // Few distinct values: many ties. (0, r) => (r % 3) as f64, @@ -277,7 +277,23 @@ fn selection_matches_full_sort_bit_for_bit() { _ => (next() % 50) as f64, }) .collect(); - assert!(same(median(v.clone()), old_median(v.clone())), "median len={len}"); + // Rounds 12..24 repeat the data as already ascending, already descending and nearly + // ascending (ends swapped): the monotone shortcut and its fallback to selection. + match round / 4 { + 3 => v.sort_by(f64::total_cmp), + 4 => { + v.sort_by(f64::total_cmp); + v.reverse(); + } + 5 => { + v.sort_by(f64::total_cmp); + if let Some(last) = v.len().checked_sub(1) { + v.swap(0, last); + } + } + _ => {} + } + assert!(same(median(v.clone()), old_median(v.clone())), "median len={len} round={round}"); let ks = [-1.0, 0.0, 0.2, 1.0, 1.5, 2.0, len as f64 / 2.0, len as f64 - 0.5, len as f64, len as f64 + 1.0, f64::NAN]; for &k in &ks { for largest in [true, false] { From b6bbdcd5cf23626171768d0cf061e4b0319a67c1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:51:45 +0100 Subject: [PATCH 11/68] calc: build precedents from a borrowed syntax tree, no Arc for text-only formulas Formula::with_expr runs a closure on the cached tree, or on a freshly parsed one that is dropped afterwards, so rebuild and cells_changed need neither a tree copy nor an Arc allocation / reference count. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 11 +++++------ crates/calc/src/tests.rs | 39 +++++++++++++++++++++++++++++++++++++++ crates/model/src/cell.rs | 10 ++++++++++ 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 34c712ddc6..9886ca9bd1 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -128,9 +128,8 @@ impl Calc { for (si, sheet) in wb.sheets.iter().enumerate() { for (c, cell) in sheet.cells.iter() { if let Some(f) = &cell.formula - && let Some(e) = f.expr_arc() + && let Some((areas, dynamic)) = f.with_expr(|e| precedents(wb, si, e)) { - let (areas, dynamic) = precedents(wb, si, &e); self.graph.insert((si, c), Node { areas, dynamic }); if cell.value == Value::Error(CellError::Circ) { circ.push((si, c)); @@ -205,10 +204,10 @@ impl Calc { pub fn cells_changed(&mut self, wb: &mut Workbook, changed: &[Key]) { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { - let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); - match formula.and_then(|f| f.expr_arc()) { - Some(e) => { - let (areas, dynamic) = precedents(wb, k.0, &e); + let precedent = + wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.as_ref()).and_then(|f| f.with_expr(|e| precedents(wb, k.0, e))); + match precedent { + Some((areas, dynamic)) => { self.graph.insert(k, Node { areas, dynamic }); } None => { diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..0d4c973d4a 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,42 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +/// `rebuild` and `cells_changed` read formulas through `Formula::with_expr`, which borrows the +/// cached tree or parses on the fly. The dependency graph must come out the same for formulas that +/// carry their tree and for formulas that only carry their text (as after loading a file). +#[test] +fn graph_built_from_text_only_formulas_matches_cached() { + fn run(cached: bool) -> Vec { + let mut t = T::new(); + t.set("A1", "2"); + for (at, f) in [("B1", "=A1*10"), ("C1", "=B1+A1"), ("D1", "=SUM(A1:C1)"), ("E1", "=NOPE(")] { + // E1 does not parse, so it has no tree either way and only covers the `None` branch. + let mut formula = Formula::new(f); + if !cached { + formula.expr = None; + } + t.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::formula(formula)); + } + t.calc.rebuild(&t.wb); + t.calc.recalc_all(&mut t.wb); + let mut out: Vec = ["B1", "C1", "D1", "E1"].iter().map(|a| t.get(a)).collect(); + // Editing the input must reach the dependents through the rebuilt graph. + t.set("A1", "5"); + out.extend(["B1", "C1", "D1"].iter().map(|a| t.get(a))); + // A text-only formula that is rewritten through `cells_changed` joins the graph too. + let mut formula = Formula::new("=A1+100"); + if !cached { + formula.expr = None; + } + t.wb.sheet_mut(0).unwrap().cells.set(c("F1"), Cell::formula(formula)); + t.calc.cells_changed(&mut t.wb, &[(0, c("F1"))]); + t.set("A1", "7"); + out.push(t.get("F1")); + out + } + let cached = run(true); + assert_eq!(cached, run(false)); + assert_eq!(cached[4], Value::Number(50.0)); + assert_eq!(cached[7], Value::Number(107.0)); +} diff --git a/crates/model/src/cell.rs b/crates/model/src/cell.rs index d4466365f7..7d3a7715ee 100644 --- a/crates/model/src/cell.rs +++ b/crates/model/src/cell.rs @@ -46,6 +46,16 @@ impl Formula { pub fn expr_arc(&self) -> Option> { self.expr.clone().or_else(|| gridcraft_formula::parse(&self.text).ok().map(Arc::new)) } + /// Runs `f` on the parsed expression, borrowing the cached tree or, after deserialization, + /// a freshly parsed one that is dropped afterwards. Unlike [`expr`](Self::expr) it never copies + /// the tree, and unlike [`expr_arc`](Self::expr_arc) it needs no reference count or `Arc` + /// allocation. `None` when the text does not parse. + pub fn with_expr(&self, f: impl FnOnce(&Expr) -> R) -> Option { + match &self.expr { + Some(e) => Some(f(e)), + None => gridcraft_formula::parse(&self.text).ok().map(|e| f(&e)), + } + } } /// A static picture stored as cell content, independent of floating drawing anchors. From 8b330ac9e213c05906b4dee0468444e558f6e4a0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:52:59 +0100 Subject: [PATCH 12/68] Tighten selection comment and test index arithmetic Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/descriptive.rs | 7 ++++--- crates/functions/src/stat/tests.rs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/functions/src/stat/descriptive.rs b/crates/functions/src/stat/descriptive.rs index 08938d039c..3c8f78f691 100644 --- a/crates/functions/src/stat/descriptive.rs +++ b/crates/functions/src/stat/descriptive.rs @@ -39,9 +39,10 @@ pub(super) fn sorted(mut v: Vec) -> Vec { } /// Sorts `v` if it is already monotone in `total_cmp` order (a descending slice is reversed) and -/// says whether it did. One cheap pass that stops at the first out-of-order pair, so unordered -/// data costs next to nothing. Needed because the std sort recognises ascending and descending -/// runs in O(n), which a selection cannot beat. +/// says whether it did. At most two passes, each stopping at the first out-of-order pair, so +/// unordered data costs next to nothing. Needed because the std sort recognises ascending and +/// descending runs in O(n) with a small constant; selection is O(n) too but measured 1.2-1.8x +/// slower on such input. fn sorted_if_monotone(v: &mut [f64]) -> bool { if v.is_sorted_by(|a, b| a.total_cmp(b).is_le()) { return true; diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index f11629369f..023b36815d 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -269,7 +269,7 @@ fn selection_matches_full_sort_bit_for_bit() { // Few distinct values: many ties. (0, r) => (r % 3) as f64, // Specials, including both zeros and NaNs. - (1, r) => specials[(next() as usize + r as usize) % specials.len()], + (1, r) => specials[(next() as usize).wrapping_add(r as usize) % specials.len()], // Wide random range. (2, _) => (next() as i64 as f64) / 1e3, // Integers with some specials mixed in. From 95c3bb9b89e229759077aa025032396e951e30a8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 23:05:54 +0100 Subject: [PATCH 13/68] Fix clippy complexity after merging upstream/main --- crates/chart/src/render/cartesian.rs | 84 +++++++++++++++++++--------- 1 file changed, 58 insertions(+), 26 deletions(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index f30283b58d..78774b078f 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -3,8 +3,8 @@ use super::legend::{cat_label, plot_kind}; use super::lines::{decimate, draw_markers, draw_runs}; use super::trend::{draw_trend_labels, draw_trendlines, max_backward, max_forward, max_forward_slots, supports_trendline}; use super::{ - Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, Prim, Scale, SeriesData, TEXT, - VAlign, WHITE, clean, fixed_scale, nice_scale, + Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, MIN_BAR_PX, Prim, Rgba, Scale, + SeriesData, TEXT, VAlign, WHITE, clean, fixed_scale, nice_scale, }; // ---------------------------------------------------------------- cartesian (column/bar/line/area/combo) @@ -81,6 +81,58 @@ impl BarRun { } } +/// Whether bars of width `bw` are merged per pixel column (never when they carry data labels). +fn merge_hairlines(bw: f32, labels_on: bool) -> bool { + bw < MIN_BAR_PX && !labels_on +} + +/// Draws the bars of one series: a rectangle each, or, for hairline bars, one merged [`BarRun`] +/// per pixel column. +struct BarSink { + run: Option, + bw: f32, + horizontal: bool, + color: Rgba, + nslots: f32, + k: f32, +} + +impl BarSink { + fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self { + BarSink { run: None, bw, horizontal, color, nslots, k } + } + /// Start of this series' slot along the category axis, for the category centered at `c`. + fn pos(&self, c: f32) -> f32 { + if self.horizontal { c + self.nslots * self.bw / 2.0 - (self.k + 1.0) * self.bw } else { c - self.nslots * self.bw / 2.0 + self.k * self.bw } + } + /// Draws the bar at category center `c` spanning `lo..lo + len` on the value axis, or, when + /// `merge` is set, adds it to the current run. + fn bar(&mut self, ctx: &mut Ctx, merge: bool, c: f32, lo: f32, len: f32) { + let pos = self.pos(c); + if !merge { + if self.horizontal { + ctx.rect(lo, pos, len, self.bw, self.color, None); + } else { + ctx.rect(pos, lo, self.bw, len, self.color, None); + } + return; + } + match &mut self.run { + Some(m) if m.bucket == pos.floor() => m.add(pos, lo, lo + len), + run => { + if let Some(m) = run.replace(BarRun::new(pos, lo, lo + len)) { + m.draw(ctx, self.bw, self.horizontal, self.color); + } + } + } + } + fn finish(self, ctx: &mut Ctx) { + if let Some(m) = self.run { + m.draw(ctx, self.bw, self.horizontal, self.color); + } + } +} + fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); @@ -307,33 +359,15 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx 1 => { let k = slot_of.get(i).copied().unwrap_or(0) as f32; // Hairline bars are merged per pixel column (their envelope is what shows). - let cull = bw < MIN_BAR_PX && !labels_on; - let mut run: Option = None; + let cull = merge_hairlines(bw, labels_on); + let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k); for (j, sp) in row.iter().enumerate() { let Some((b, t)) = sp else { continue }; let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc)); let c = center(j); let lo = pb.min(pt); let len = (pb - pt).abs(); - if cull { - let pos = if horizontal { c + nslots * bw / 2.0 - (k + 1.0) * bw } else { c - nslots * bw / 2.0 + k * bw }; - match &mut run { - Some(m) if m.bucket == pos.floor() => m.add(pos, lo, lo + len), - _ => { - if let Some(m) = run.replace(BarRun::new(pos, lo, lo + len)) { - m.draw(ctx, bw, horizontal, s.color); - } - } - } - continue; - } - if horizontal { - let y = c + nslots * bw / 2.0 - (k + 1.0) * bw; - ctx.rect(lo, y, len, bw, s.color, None); - } else { - let x = c - nslots * bw / 2.0 + k * bw; - ctx.rect(x, lo, bw, len, s.color, None); - } + sink.bar(ctx, cull, c, lo, len); if labels_on && let Some(v) = s.values.get(j).copied().flatten() { let t = fmt.format(v, None); let stacked = fam != Fam::Col; @@ -359,9 +393,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx } } } - if let Some(m) = run { - m.draw(ctx, bw, horizontal, s.color); - } + sink.finish(ctx); } _ => { let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); From 6c912d2eb130130f93d9281baca435a37e5d30e7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 23:48:11 +0100 Subject: [PATCH 14/68] perf(calc): keep tall and wide spill areas out of the block index A full-height column spill took 65,536 block registrations, on every pass that produced it. Areas over 1024 blocks are now tested directly by each lookup instead. Adds a randomized comparison against a scan of all areas. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/spill_index.rs | 121 +++++++++++++++++++++++++++++---- crates/calc/src/tests.rs | 21 ++++++ 2 files changed, 127 insertions(+), 15 deletions(-) diff --git a/crates/calc/src/spill_index.rs b/crates/calc/src/spill_index.rs index 7cf2d44fe2..1bbf0f9c0e 100644 --- a/crates/calc/src/spill_index.rs +++ b/crates/calc/src/spill_index.rs @@ -1,6 +1,9 @@ //! A spatial index over spill areas: which areas cover a cell, and which meet a range, without //! looking at every area. Areas are registered in 16 x 16 cell blocks, so a lookup touches one //! block (a cell) or the blocks a range covers (a range) rather than every spill on the sheet. +//! An area that would take more than `BIG_AREA_BLOCKS` blocks (a full-height column spill takes +//! 65,536) is not registered in blocks but kept in a short list that every lookup tests directly, +//! so registering costs what the area's size warrants only for small areas. use crate::recalc::{FxHasher, Key}; use gridcraft_core::{CellRef, RangeRef}; @@ -11,6 +14,9 @@ type HashMap = std::collections::HashMap, blocks: HashMap<(u32, u32), Vec>, + /// Anchors of the areas too big to register in blocks. + big: Vec, } /// What covers a cell. @@ -42,16 +50,24 @@ fn block_span(rect: &RangeRef) -> (u32, u32, u32, u32) { (rect.start.row / BLOCK, rect.end.row / BLOCK, rect.start.col / BLOCK, rect.end.col / BLOCK) } +fn block_count(rect: &RangeRef) -> u64 { + let (r0, r1, c0, c1) = block_span(rect); + u64::from(r1 - r0 + 1) * u64::from(c1 - c0 + 1) +} + /// Whether registering `areas` in blocks costs less than checking each of them against each of /// `lookups` cells would: a few block entries cost about one containment check each. A tall or -/// wide area (a full-height column spill takes 65,536 blocks) is cheaper to test directly. +/// wide area is not registered at all (see `BIG_AREA_BLOCKS`) and so costs nothing here. pub(crate) fn indexing_pays<'a>(areas: impl ExactSizeIterator, lookups: usize) -> bool { const BLOCK_COST: u64 = 16; let budget = (lookups as u64).saturating_mul(areas.len() as u64) / BLOCK_COST; let mut blocks = 0u64; for r in areas { - let (r0, r1, c0, c1) = block_span(r); - blocks = blocks.saturating_add(u64::from(r1 - r0 + 1) * u64::from(c1 - c0 + 1)); + let n = block_count(r); + if n > BIG_AREA_BLOCKS { + continue; + } + blocks = blocks.saturating_add(n); if blocks > budget { return false; } @@ -77,10 +93,14 @@ impl SpillIndex { pub(crate) fn insert_rect(&mut self, (sheet, anchor): Key, rect: RangeRef, empty: bool) { self.remove((sheet, anchor)); let areas = self.sheets.entry(sheet).or_default(); - let (r0, r1, c0, c1) = block_span(&rect); - for br in r0..=r1 { - for bc in c0..=c1 { - areas.blocks.entry((br, bc)).or_default().push(anchor); + if block_count(&rect) > BIG_AREA_BLOCKS { + areas.big.push(anchor); + } else { + let (r0, r1, c0, c1) = block_span(&rect); + for br in r0..=r1 { + for bc in c0..=c1 { + areas.blocks.entry((br, bc)).or_default().push(anchor); + } } } areas.entries.insert(anchor, Entry { rect, empty }); @@ -89,6 +109,10 @@ impl SpillIndex { pub(crate) fn remove(&mut self, (sheet, anchor): Key) { let Some(areas) = self.sheets.get_mut(&sheet) else { return }; let Some(old) = areas.entries.remove(&anchor) else { return }; + if block_count(&old.rect) > BIG_AREA_BLOCKS { + areas.big.retain(|a| *a != anchor); + return; + } let (r0, r1, c0, c1) = block_span(&old.rect); for br in r0..=r1 { for bc in c0..=c1 { @@ -105,9 +129,9 @@ impl SpillIndex { /// The areas that cover `c`. pub(crate) fn covering(&self, sheet: usize, c: CellRef) -> Cover { let Some(areas) = self.sheets.get(&sheet) else { return Cover::None }; - let Some(list) = areas.blocks.get(&(c.row / BLOCK, c.col / BLOCK)) else { return Cover::None }; + let in_block = areas.blocks.get(&(c.row / BLOCK, c.col / BLOCK)).map_or(&[][..], |l| l.as_slice()); let mut found = Cover::None; - for a in list { + for a in in_block.iter().chain(&areas.big) { if let Some(e) = areas.entries.get(a) && !e.empty && e.rect.contains(c) @@ -139,6 +163,7 @@ impl SpillIndex { } } } + out.extend(areas.big.iter().copied().filter(|a| areas.entries.get(a).is_some_and(|e| e.rect.intersects(&range)))); } out.sort_unstable(); out.dedup(); @@ -181,15 +206,81 @@ mod tests { } #[test] - fn tall_or_wide_areas_are_not_worth_indexing_for_a_small_paste() { + fn tall_or_wide_areas_are_not_registered_in_blocks() { let column = RangeRef::new(at(0, 0), at(1_048_575, 0)); - assert!(!indexing_pays([column].iter(), 17)); - assert!(!indexing_pays([column].iter(), 1_000)); - // Many small areas pay back for a paste of a hundred cells. + assert!(block_count(&column) > BIG_AREA_BLOCKS); + let mut ix = SpillIndex::default(); + ix.insert_rect((0, at(0, 0)), column, false); + assert!(ix.sheets[&0].blocks.is_empty()); + assert!(matches!(ix.covering(0, at(900_000, 0)), Cover::One(a) if a == at(0, 0))); + assert!(matches!(ix.covering(0, at(900_000, 1)), Cover::None)); + let mut hits = Vec::new(); + ix.meeting(0, RangeRef::new(at(5, 0), at(6, 3)), &mut hits); + assert_eq!(hits, vec![at(0, 0)]); + ix.remove((0, at(0, 0))); + assert!(matches!(ix.covering(0, at(900_000, 0)), Cover::None) && ix.sheets[&0].big.is_empty()); + // Registering a big area costs nothing (lookups test it directly), so a small paste still indexes next to many small areas. + assert!(indexing_pays([column].iter(), 17)); + // Many small areas pay back for a paste of a hundred cells, but not for a handful. let small: Vec = (0..1_000).map(|i| RangeRef::new(at(i * 3, 0), at(i * 3 + 2, 0))).collect(); assert!(indexing_pays(small.iter(), 100)); - // A big area among many areas is paid for by a big paste. - assert!(indexing_pays([column].iter(), 2_000_000)); + assert!(!indexing_pays(small.iter(), 17)); + } + + /// The index against the old way: test every area for every lookup. Mixed shapes: small, + /// thin and tall, wide, big (kept out of the blocks), empty, on two sheets, replaced and removed. + #[test] + fn matches_a_scan_of_every_area_on_mixed_shapes() { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + let mut next = |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as u32 % n + }; + let mut ix = SpillIndex::default(); + let mut model: std::collections::BTreeMap<(usize, CellRef), (RangeRef, bool)> = Default::default(); + for step in 0..3_000 { + let sheet = next(2) as usize; + let anchor = at(next(400) * 5, next(40) * 3); + if next(4) == 0 { + ix.remove((sheet, anchor)); + model.remove(&(sheet, anchor)); + } else { + let (rows, cols) = match next(8) { + 0 => (0, 1 + next(5) as usize), + 1 => (1 + next(5) as usize, 0), + 2 => (5_000 + next(100_000) as usize, 1), + 3 => (1, 1 + next(40_000) as usize), + 4 => (200 + next(300) as usize, 40 + next(40) as usize), + _ => (1 + next(60) as usize, 1 + next(40) as usize), + }; + ix.insert((sheet, anchor), rows, cols); + let end = at(anchor.row + (rows as u32).saturating_sub(1), anchor.col + (cols as u32).saturating_sub(1)); + model.insert((sheet, anchor), (RangeRef::new(anchor, end), rows == 0 || cols == 0)); + } + if step % 7 != 0 { + continue; + } + let sheet = next(3) as usize; + for _ in 0..20 { + let cell = at(next(2_100), next(130)); + let want: Vec = + model.iter().filter(|((s, _), (r, e))| *s == sheet && !e && r.contains(cell)).map(|((_, a), _)| *a).collect(); + match ix.covering(sheet, cell) { + Cover::None => assert!(want.is_empty(), "{cell:?}"), + Cover::One(a) => assert_eq!(want, vec![a], "{cell:?}"), + Cover::Many => assert!(want.len() > 1, "{cell:?}"), + } + let (r0, c0) = (next(2_100), next(130)); + let (tall, wide) = (if next(5) == 0 { 3_000 } else { 40 }, if next(5) == 0 { 130 } else { 20 }); + let range = RangeRef::new(at(r0, c0), at(r0 + next(tall), c0 + next(wide))); + let want: Vec = model.iter().filter(|((s, _), (r, _))| *s == sheet && r.intersects(&range)).map(|((_, a), _)| *a).collect(); + let mut got = Vec::new(); + ix.meeting(sheet, range, &mut got); + assert_eq!(got, want, "{range:?}"); + } + } } #[test] diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 9dd1fd9255..ac254239a0 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2350,3 +2350,24 @@ fn many_spills_are_read_and_blocked_by_a_paste() { assert_eq!(t.get("A10"), Value::Error(CellError::Spill)); assert_eq!(t.num("A12"), 4.0); } + +#[test] +fn a_paste_over_small_and_tall_spills_blocks_those_it_touches() { + let mut t = T::new(); + for i in 0..40u32 { + t.wb.sheet_mut(0).unwrap().cells.set(CellRef::new(0, 2 * i), Cell::formula(Formula::new("=SEQUENCE(3)"))); + } + t.wb.sheet_mut(0).unwrap().cells.set(CellRef::new(0, 200), Cell::formula(Formula::new("=SEQUENCE(1048576)"))); + t.calc.recalc_all(&mut t.wb); + // 20 cells: the middle row of the small arrays in columns 0, 8, 16 ... 72 (columns 80 and up hit + // nothing), and one deep inside the tall one. + let mut cells: Vec<(u32, u32)> = (0..19u32).map(|i| (1, 8 * i)).collect(); + cells.push((700_000, 200)); + paste_into(&mut t, &cells); + assert_eq!(t.get("A1"), Value::Error(CellError::Spill)); + assert_eq!(t.get("GS1"), Value::Error(CellError::Spill)); + assert_eq!(t.num("C1"), 1.0); + assert_eq!(t.num("C3"), 3.0); + assert_eq!(t.get("I1"), Value::Error(CellError::Spill)); + assert_eq!(t.num("E3"), 3.0); +} From bdbd29e623c7ddf4df27331a7f7834295b5f770c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 30 Oct 2026 00:04:25 +0100 Subject: [PATCH 15/68] perf(calc): size the spill-index decision by the sheet's own changed cells A batch spread over several sheets used its total length for every sheet, so a one-cell sheet with many spills built the block index as if it had the whole batch's lookups. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 44 +++++++++++++++++++++++++++++---------- crates/calc/src/tests.rs | 22 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index aae212dd33..7c3a6f3611 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -22,6 +22,13 @@ use crate::spill_index::{SpillIndex, indexing_pays}; /// Changed cells (in one `cells_changed`) from which a sheet's spill areas may be indexed. const INDEX_SPILLS_FROM: usize = 16; +/// Whether a sheet's spill areas are indexed for a batch of `batch` changed cells of which +/// `on_sheet` are on that sheet: the batch must be a paste, and registering the areas must cost +/// less than walking them once for each of the sheet's own changed cells. +fn index_spills<'a>(batch: usize, on_sheet: usize, areas: impl ExactSizeIterator) -> bool { + batch > INDEX_SPILLS_FROM && areas.len() > 0 && indexing_pays(areas, on_sheet) +} + mod graph; mod pass_host; @@ -250,20 +257,22 @@ impl Calc { // walked for each one, when registering them costs less than walking them would. let mut areas = SpillIndex::default(); let mut strategy: HashMap = HashMap::default(); + let mut per_sheet: HashMap = HashMap::default(); + for k in changed { + *per_sheet.entry(k.0).or_insert(0) += 1; + } let mut at = Vec::new(); for &k in changed { if let Some(sh) = wb.sheet(k.0) { - let indexed = changed.len() > INDEX_SPILLS_FROM - && !sh.spill_ranges.is_empty() - && *strategy.entry(k.0).or_insert_with(|| { - let indexed = indexing_pays(sh.spill_ranges.values(), changed.len()); - if indexed { - for (anchor, r) in &sh.spill_ranges { - areas.insert_rect((k.0, *anchor), *r, false); - } + let indexed = *strategy.entry(k.0).or_insert_with(|| { + let indexed = index_spills(changed.len(), per_sheet[&k.0], sh.spill_ranges.values()); + if indexed { + for (anchor, r) in &sh.spill_ranges { + areas.insert_rect((k.0, *anchor), *r, false); } - indexed - }); + } + indexed + }); if indexed { // Anchor order, as walking `spill_ranges` gives. areas.meeting(k.0, RangeRef::new(k.1, k.1), &mut at); @@ -556,7 +565,7 @@ pub(crate) mod tests { use gridcraft_core::{CellRef, RangeRef, Value}; use gridcraft_model::{Cell, Formula, Workbook}; - use super::{Calc, HashMap, Host, Intervals, Key, PassHost}; + use super::{Calc, HashMap, Host, Intervals, Key, PassHost, index_spills}; /// xorshift64 for repeatable pseudo-random cases. fn rng(state: &mut u64) -> u64 { @@ -573,6 +582,19 @@ pub(crate) mod tests { v } + /// One changed cell on a sheet with many small spills does not index them just because the + /// batch (mostly on another sheet) is large; the sheet's own share of the batch decides. + #[test] + fn the_spill_index_is_chosen_from_the_sheets_own_changed_cells() { + let small: Vec = (0..1_000).map(|i| RangeRef::new(CellRef::new(i * 3, 0), CellRef::new(i * 3 + 2, 0))).collect(); + // Same areas, same batch of 5000: indexed when 5000 of them are on the sheet, walked when 1 is. + assert!(index_spills(5_000, 5_000, small.iter())); + assert!(!index_spills(5_000, 1, small.iter())); + // Not a paste, or nothing to index: never. + assert!(!index_spills(16, 16, small.iter())); + assert!(!index_spills(5_000, 5_000, [].iter())); + } + #[test] fn intervals_match_a_linear_scan() { let mut iv: Intervals = Intervals::default(); diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index ac254239a0..a3e7f810d5 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2371,3 +2371,25 @@ fn a_paste_over_small_and_tall_spills_blocks_those_it_touches() { assert_eq!(t.get("I1"), Value::Error(CellError::Spill)); assert_eq!(t.num("E3"), 3.0); } + +#[test] +fn a_big_paste_on_one_sheet_and_one_cell_over_many_spills_on_another() { + let mut t = T::new(); + t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Data"))); + for i in 0..1_500u32 { + t.wb.sheet_mut(1).unwrap().cells.set(CellRef::new(4 * i, 0), Cell::formula(Formula::new(&format!("=SEQUENCE(3,1,{})", 10 * i)))); + } + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.wb.sheet(1).unwrap().value(CellRef::new(4 * 700 + 2, 0)), Value::Number(7002.0)); + // 5000 cells pasted on the first sheet, one over the middle of the 701st array on the second. + let mut changed: Vec<(usize, CellRef)> = (0..5_000u32).map(|i| (0, CellRef::new(i / 50, i % 50))).collect(); + changed.push((1, CellRef::new(4 * 700 + 1, 0))); + for k in &changed { + t.wb.sheet_mut(k.0).unwrap().cells.set(k.1, Cell::value(Value::Number(1.0))); + } + t.calc.cells_changed(&mut t.wb, &changed); + let data = t.wb.sheet(1).unwrap(); + assert_eq!(data.value(CellRef::new(4 * 700, 0)), Value::Error(CellError::Spill)); + assert_eq!(data.value(CellRef::new(4 * 699 + 2, 0)), Value::Number(6992.0)); + assert_eq!(data.value(CellRef::new(4 * 701 + 2, 0)), Value::Number(7012.0)); +} From 494a7dbb5c0fe57d819b83f1981d62e15d4b14d4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 30 Oct 2026 00:54:56 +0100 Subject: [PATCH 16/68] Keep clustered hairline bars of each series in their own strip of the pixel column Co-Authored-By: Claude Sonnet 5.5 --- crates/chart/src/render/cartesian.rs | 32 ++++++++++++++++++++------ crates/chart/src/tests/budget.rs | 34 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 78774b078f..1d643c21ff 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -59,24 +59,32 @@ struct BarRun { a1: f32, lo: f32, hi: f32, + /// More than one bar was merged. + merged: bool, } impl BarRun { fn new(pos: f32, lo: f32, hi: f32) -> Self { - BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi } + BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false } } fn add(&mut self, pos: f32, lo: f32, hi: f32) { + self.merged = true; self.a0 = self.a0.min(pos); self.a1 = self.a1.max(pos); self.lo = self.lo.min(lo); self.hi = self.hi.max(hi); } - fn draw(&self, ctx: &mut Ctx, bw: f32, horizontal: bool, color: Rgba) { - let along = self.a1 - self.a0 + bw; + /// `band` is the part of the pixel column reserved for this series (`start`, `len`): in a + /// clustered chart a merged run stays inside it, so the other series keep a visible strip. + fn draw(&self, ctx: &mut Ctx, bw: f32, horizontal: bool, color: Rgba, band: Option<(f32, f32)>) { + let (a0, along) = match band { + Some((start, len)) if self.merged => (self.bucket + start, len), + _ => (self.a0, self.a1 - self.a0 + bw), + }; if horizontal { - ctx.rect(self.lo, self.a0, self.hi - self.lo, along, color, None); + ctx.rect(self.lo, a0, self.hi - self.lo, along, color, None); } else { - ctx.rect(self.a0, self.lo, along, self.hi - self.lo, color, None); + ctx.rect(a0, self.lo, along, self.hi - self.lo, color, None); } } } @@ -105,10 +113,19 @@ impl BarSink { fn pos(&self, c: f32) -> f32 { if self.horizontal { c + self.nslots * self.bw / 2.0 - (self.k + 1.0) * self.bw } else { c - self.nslots * self.bw / 2.0 + self.k * self.bw } } + /// This series' strip of a pixel column (offset, length) when the columns hold several + /// clustered series, in the direction the slots run. + fn band(&self) -> Option<(f32, f32)> { + (self.nslots > 1.0).then(|| { + let idx = if self.horizontal { self.nslots - 1.0 - self.k } else { self.k }; + (idx / self.nslots, 1.0 / self.nslots) + }) + } /// Draws the bar at category center `c` spanning `lo..lo + len` on the value axis, or, when /// `merge` is set, adds it to the current run. fn bar(&mut self, ctx: &mut Ctx, merge: bool, c: f32, lo: f32, len: f32) { let pos = self.pos(c); + let band = self.band(); if !merge { if self.horizontal { ctx.rect(lo, pos, len, self.bw, self.color, None); @@ -121,14 +138,15 @@ impl BarSink { Some(m) if m.bucket == pos.floor() => m.add(pos, lo, lo + len), run => { if let Some(m) = run.replace(BarRun::new(pos, lo, lo + len)) { - m.draw(ctx, self.bw, self.horizontal, self.color); + m.draw(ctx, self.bw, self.horizontal, self.color, band); } } } } fn finish(self, ctx: &mut Ctx) { + let band = self.band(); if let Some(m) = self.run { - m.draw(ctx, self.bw, self.horizontal, self.color); + m.draw(ctx, self.bw, self.horizontal, self.color, band); } } } diff --git a/crates/chart/src/tests/budget.rs b/crates/chart/src/tests/budget.rs index 1f2e35ab36..54d33aa7d8 100644 --- a/crates/chart/src/tests/budget.rs +++ b/crates/chart/src/tests/budget.rs @@ -124,6 +124,40 @@ fn hairline_columns_are_merged_and_wide_ones_are_not() { assert!((1..=320).contains(&n), "{n} bars"); } +#[test] +fn clustered_hairline_series_keep_a_visible_strip() { + // Four series of similar height, 20,000 categories in 400 px: every pixel column holds a + // merged bar of each series, and they must not cover each other. + for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] { + let horizontal = kind == ChartKind::BarClustered; + let mut c = chart(kind); + c.data_labels = false; + c.legend = LegendPos::None; + let mut d = data_of(4, 20_000); + for (s, series) in d.series.iter_mut().enumerate() { + for (i, v) in series.values.iter_mut().enumerate() { + *v = Some(50.0 + ((i + s) % 3) as f64); + } + } + let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure); + let along = |r: &(f32, f32, f32, f32)| if horizontal { (r.1, r.1 + r.3) } else { (r.0, r.0 + r.2) }; + let mut strips: Vec<(f32, f32, usize)> = Vec::new(); + for (s, series) in d.series.iter().enumerate() { + strips.extend(series_rects(&prims, series.color).iter().map(|r| (along(r).0, along(r).1, s))); + } + strips.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert!(strips.len() > 400); + // Rectangles of different series never overlap (more than rounding). + for w in strips.windows(2) { + assert!(w[0].2 == w[1].2 || w[1].0 >= w[0].1 - 1e-3, "series {} and {} overlap", w[0].2, w[1].2); + } + // And all four series show up in the same pixel column. + let col = strips[strips.len() / 2].0.floor(); + let seen: std::collections::BTreeSet = strips.iter().filter(|s| s.0.floor() == col).map(|s| s.2).collect(); + assert_eq!(seen.len(), 4, "series visible in pixel column {col}"); + } +} + #[test] fn clean_data_is_rendered_without_a_copy() { let d = data_of(3, 50); From 96672e8ad5900dd20bd2034a99d4abebaccda297 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 2 Nov 2026 19:33:53 +0100 Subject: [PATCH 17/68] Drop helpers the merged range reads no longer use Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc/pass_host.rs | 7 ------- crates/calc/src/spill_index.rs | 1 + 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 9d00f9784f..9a733501b0 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -185,13 +185,6 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef, .all(|(i, c)| c == anchor || (!sheet.cells.has(c) && sheet.spill.get(&c) == Some(arr.data.get(i).unwrap_or(&Value::Empty)))) } -/// The area an array anchored at `anchor` covers. -fn array_area(anchor: CellRef, a: &Array) -> RangeRef { - let end = - CellRef::new(anchor.row.saturating_add((a.rows as u32).saturating_sub(1)), anchor.col.saturating_add((a.cols as u32).saturating_sub(1))); - RangeRef::new(anchor, end) -} - /// The spilled values `sheet` stores inside `range`, passed to `f` until it returns false. Values /// outside the range are not walked: with fewer rows in the range than spilled values, each row /// is looked up on its own; otherwise one ordered scan visits each spilled value at most once. diff --git a/crates/calc/src/spill_index.rs b/crates/calc/src/spill_index.rs index 1bbf0f9c0e..d642bdee72 100644 --- a/crates/calc/src/spill_index.rs +++ b/crates/calc/src/spill_index.rs @@ -77,6 +77,7 @@ pub(crate) fn indexing_pays<'a>(areas: impl ExactSizeIterator bool { self.sheets.get(&sheet).is_some_and(|s| !s.entries.is_empty()) } From 00f565bc11d69623f5260a13e143c20c65d0c85f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 2 Nov 2026 19:44:16 +0100 Subject: [PATCH 18/68] Factor out types clippy flags as too complex Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc/pass_host.rs | 5 ++++- crates/calc/src/tests.rs | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 6151b74d3c..9964b33639 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -13,6 +13,9 @@ const MAX_NESTED: usize = 64; /// evaluated again), however high Maximum Iterations is. const MAX_ITERATION_WORK: usize = 10_000_000; +/// A block's results by last row: its sum and count, or `None` when it can't be summed from constants. +type BlockSums = std::collections::BTreeMap>; + pub(super) struct PassHost<'a> { wb: &'a Workbook, exprs: &'a HashMap>, @@ -71,7 +74,7 @@ pub(super) struct PassHost<'a> { /// Sum and count of blocks that hold only constants, for `range_sum`. Keyed by sheet, first /// cell and last column; each value maps a last row to the block's result (`None`: the block /// has a formula, a Python cell, an error value or a spilled value, so every longer one has too). - sums: HashMap<(usize, CellRef, u32), std::collections::BTreeMap>>, + sums: HashMap<(usize, CellRef, u32), BlockSums>, /// The kept results of the Python cells in the pass: a Python cell isn't evaluated, its /// result is laid out (an array spills from the cell, as a formula's does). Each one is in /// `pending` until it is laid out, so a formula that reads it first gets its new value. diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index a55231794b..0c9ec4aa19 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2348,7 +2348,8 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() { } } // Formulas in column H and up: (function, optional leading number, blocks). - let mut oracle: Vec<(CellRef, &str, Option, Vec<(u32, u32, u32, u32)>)> = vec![]; + type Oracle<'a> = (CellRef, &'a str, Option, Vec<(u32, u32, u32, u32)>); + let mut oracle: Vec = vec![]; let funcs = ["SUM", "COUNT", "AVERAGE"]; let mut at = 0; let mut add = |wb: &mut Workbook, f: &'static str, lead: Option, blocks: Vec<(u32, u32, u32, u32)>| { From e85b24df5724d224ae69b2d9b7bc5cf7554f4d42 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 2 Nov 2026 20:31:52 +0100 Subject: [PATCH 19/68] calc: register a Python result's spill in the spill index python_result wrote into spills but not into spill_index, so indexed readers (cell_value, range_values, visit_range) missed a Python array laid out in the same pass. Insert on spill, remove when blocked, as the formula path does. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 33 +++++++++++++++++++++++++++++ crates/calc/src/recalc/pass_host.rs | 2 ++ 2 files changed, 35 insertions(+) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 77d5b68dd4..286569822b 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -663,6 +663,39 @@ pub(crate) mod tests { assert!(!host.visit_range(0, inside, &mut |_| true), "an overlapping read leaves the block to range_values"); } + /// A Python array laid out in this pass is seen by the indexed readers, whether the sheet + /// has no spill from before or an older, smaller one. + #[test] + fn a_python_spill_found_in_the_pass_is_read_through_the_index() { + for stale in [false, true] { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + let anchor = CellRef::new(0, 0); + let py = gridcraft_model::PyCode::new("grid"); + sh.set_cell(anchor, Cell { value: Value::Number(0.0), py: Some(std::sync::Arc::new(py)), ..Cell::default() }); + if stale { + // The last calculation spilled a 2 x 2 block of 100s. + sh.spill_ranges.insert(anchor, RangeRef::new(anchor, CellRef::new(1, 1))); + for c in RangeRef::new(anchor, CellRef::new(1, 1)).iter().skip(1) { + sh.spill.insert(c, Value::Number(100.0)); + } + } + let data: Vec = (1..=9).map(|i| Value::Number(f64::from(i))).collect(); + let array = gridcraft_core::Array::new(3, 3, data).unwrap(); + let mut python = HashMap::default(); + python.insert((0, anchor), Value::Array(std::sync::Arc::new(array))); + let exprs = HashMap::default(); + let mut rng = 1u64; + let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0).with_python(python); + assert_eq!(host.cell_value(0, anchor), Value::Number(1.0)); + let all = RangeRef::parse("A1:C3").unwrap(); + let sum: f64 = host.range_values(0, all).iter().map(|v| if let Value::Number(n) = v { *n } else { 0.0 }).sum(); + assert_eq!(sum, 45.0, "stale={stale}: a SUM over the new 3 x 3 spill reads all of it"); + assert_eq!(host.cell_value(0, CellRef::new(2, 2)), Value::Number(9.0), "stale={stale}"); + assert!(!host.visit_range(0, all, &mut |_| true), "stale={stale}: the new spill leaves the block to range_values"); + } + } + #[test] fn intervals_match_a_linear_scan() { let mut iv: Intervals = Intervals::default(); diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 9a733501b0..1ef24bc427 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -400,6 +400,7 @@ impl PassHost<'_> { && a.cols >= 1 && a.rows.checked_mul(a.cols).is_some_and(|n| n == a.data.len() && n <= gridcraft_model::python::MAX_RESULT_CELLS); if sane { + self.spill_index.insert(k, a.rows, a.cols); self.spills.insert(k, a.clone()); a.data.first().cloned().unwrap_or_default() } else { @@ -411,6 +412,7 @@ impl PassHost<'_> { let v = match self.spills.get(&k) { Some(a) if spill_blocked(self, k, a) => { self.spills.remove(&k); + self.spill_index.remove(k); Value::Error(CellError::Spill) } _ => v, From 472132b1585bef6bec6a296128f2ac72166034ca Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 19:44:55 +0100 Subject: [PATCH 20/68] math: refuse macro definitions and cap matrix cells RaTeX counts macro expansions (1,000) but not how large they grow, so a definition whose argument doubles on every call keeps the expander busy without bound. User macros have no use in an equation, so check_caps now refuses the definers (def, gdef, edef, xdef, let, futurelet, global, long, newcommand, renewcommand, providecommand) before RaTeX sees the source. The scan reads control words, verbatim text and comments the way RaTeX's lexer does. A matrix is laid out and written as rows times the widest row, so one long row in a tall matrix multiplied the output. check_caps now counts the padded cells of every environment from the source and refuses more than 2,500 in total; to_omml checks the parsed grid as well. Co-Authored-By: Claude Sonnet 5.5 --- crates/math/src/lib.rs | 232 ++++++++++++++++++++++++++++++++++++++-- crates/math/src/omml.rs | 3 + docs/decisions.md | 5 +- 3 files changed, 232 insertions(+), 8 deletions(-) diff --git a/crates/math/src/lib.rs b/crates/math/src/lib.rs index 5e1e99a411..e1f783dcab 100644 --- a/crates/math/src/lib.rs +++ b/crates/math/src/lib.rs @@ -3,7 +3,7 @@ //! without calling RaTeX again. //! //! RaTeX is young (0.1.x), so it only ever runs inside this crate's entry points ([`layout`], -//! [`to_omml`], [`check`]). Each one caps its input (4 KB, nesting 32) and runs under +//! [`to_omml`], [`check`]). Each one caps its input (4 KB, nesting 32, no macro definitions, at most [`MAX_CELLS`] matrix cells) and runs under //! `catch_unwind`, so a stray panic becomes a [`MathError`]. See the RaTeX gate in //! `docs/decisions.md` and `tests/gate.rs`. //! @@ -33,6 +33,9 @@ pub const MAX_DEPTH: usize = 32; pub const MAX_EM: f32 = 10_000.0; /// Most items one equation may produce. pub const MAX_ITEMS: usize = 50_000; +/// Most matrix cells one equation may have, counting the empty cells that pad a short row to the +/// width of the widest one. A ragged matrix costs rows times the widest row, not what is typed. +pub const MAX_CELLS: usize = 2_500; /// The error for a source over [`MAX_SOURCE_BYTES`]. It is one shared value so that a cache can /// answer for such a source by its length alone, without reading it. @@ -223,20 +226,61 @@ fn parse(latex: &str) -> Result, MathError> { }) } -/// The size and nesting caps, checked before RaTeX sees the source. +/// Control words that define or rebind macros. User macros have no use in an equation, and +/// RaTeX caps only how many expansions run, not how large they grow, so a self-referencing +/// definition whose argument doubles on every call keeps the expander busy without bound. They are +/// refused before RaTeX sees the source. +const MACRO_DEFINERS: &[&str] = + &["def", "gdef", "edef", "xdef", "let", "futurelet", "global", "long", "newcommand", "renewcommand", "providecommand"]; + +/// One open `\begin…\end` environment, counted from the source text. +struct Grid { + /// Rows ended so far (by `\\` or `\cr`). + rows: usize, + /// Cells in the current row. + cells: usize, + /// Cells in the widest row so far. + widest: usize, +} + +impl Grid { + fn new() -> Grid { + Grid { rows: 0, cells: 1, widest: 0 } + } + fn end_row(&mut self) { + self.widest = self.widest.max(self.cells); + self.rows += 1; + self.cells = 1; + } + /// The padded grid RaTeX lays out and `to_omml` writes: every row as wide as the widest. + fn padded_cells(&self) -> usize { + (self.rows + 1).saturating_mul(self.widest.max(self.cells)) + } +} + +/// The size, nesting, macro and matrix caps, checked before RaTeX sees the source. fn check_caps(latex: &str) -> Result<(), MathError> { if latex.len() > MAX_SOURCE_BYTES { return Err(SOURCE_TOO_LONG.clone()); } + // `%` starts a comment, except inside the address of `\href` and `\url`, where RaTeX reads it + // as a character. Which one it is decides what the rest of the line means, so the two are not + // allowed together. + if latex.contains('%') && (latex.contains("\\href") || latex.contains("\\url")) { + return Err(MathError::new("A % can't be combined with a link in an equation.", latex.find('%').map(|i| i..i + 1))); + } let mut depth = 0usize; + let mut grids: Vec = Vec::new(); + let mut cells_total = 0usize; let mut chars = latex.char_indices().peekable(); while let Some((i, c)) = chars.next() { let open = match c { '\\' => { - // A control word, or an escaped character (`\{` is not a group). + // A control word (letters and `@`, as RaTeX's lexer reads it), or an escaped + // character (`\{` is not a group). let mut word = String::new(); while let Some(&(_, n)) = chars.peek() { - if n.is_ascii_alphabetic() { + if n.is_ascii_alphabetic() || n == '@' { word.push(n); chars.next(); } else { @@ -244,15 +288,69 @@ fn check_caps(latex: &str) -> Result<(), MathError> { } } if word.is_empty() { - chars.next(); + if let Some((_, n)) = chars.next() + && n == '\\' + && let Some(g) = grids.last_mut() + { + g.end_row(); + } continue; } + if MACRO_DEFINERS.contains(&word.as_str()) { + return Err(MathError::new("Macro definitions are not supported in equations.", Some(i..i + 1 + word.len()))); + } match word.as_str() { - "left" | "begin" => Some(true), - "right" | "end" => Some(false), + "verb" => { + // Verbatim text runs to the next copy of its delimiter, whatever it + // holds: no group, comment, row or definition starts inside it. + if chars.peek().is_some_and(|&(_, n)| n == '*') { + chars.next(); + } + if let Some((_, delim)) = chars.next() { + for (_, n) in chars.by_ref() { + if n == delim { + break; + } + } + } + None + } + "cr" => { + if let Some(g) = grids.last_mut() { + g.end_row(); + } + None + } + "begin" => { + if let Some(n) = alignat_columns(latex.get(i + 6..).unwrap_or_default()) + && n > MAX_ALIGNAT_PAIRS + { + return Err(too_many_cells(i..i + 6)); + } + grids.push(Grid::new()); + Some(true) + } + "end" => { + if let Some(g) = grids.pop() { + cells_total = cells_total.saturating_add(g.padded_cells()); + if cells_total > MAX_CELLS { + return Err(too_many_cells(i..i + 1 + word.len())); + } + } + Some(false) + } + "left" => Some(true), + "right" => Some(false), _ => None, } } + '&' | '@' => { + // `@` makes an arrow cell and an empty cell beside it in a `CD` diagram. + if let Some(g) = grids.last_mut() { + g.cells += if c == '@' { 2 } else { 1 }; + } + None + } '%' => { // A comment runs to the end of the line. for (_, n) in chars.by_ref() { @@ -277,9 +375,39 @@ fn check_caps(latex: &str) -> Result<(), MathError> { None => {} } } + // An environment left open is a syntax error for the parser to report, but it still counts. + for g in grids { + cells_total = cells_total.saturating_add(g.padded_cells()); + } + if cells_total > MAX_CELLS { + return Err(too_many_cells(latex.len()..latex.len())); + } Ok(()) } +/// Most column pairs `\begin{alignedat}{N}` may ask for. RaTeX allocates 2N column specs before +/// it lays anything out. +const MAX_ALIGNAT_PAIRS: usize = 50; + +/// N of `{alignat}{N}`, `{alignat*}{N}` or `{alignedat}{N}` at the start of `rest` (just after +/// `\begin`); `usize::MAX` when the count is present but too long to read. +fn alignat_columns(rest: &str) -> Option { + let rest = rest.trim_start().strip_prefix('{')?; + let (name, after) = rest.split_once('}')?; + if !matches!(name, "alignat" | "alignat*" | "alignedat") { + return None; + } + let digits = after.trim_start().strip_prefix('{')?.split('}').next()?.trim(); + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(digits.parse().unwrap_or(usize::MAX)) +} + +fn too_many_cells(span: Range) -> MathError { + MathError::new(format!("An equation can have at most {MAX_CELLS} matrix cells (rows times the widest row)."), Some(span)) +} + fn color(c: &Color) -> Option<[u8; 3]> { let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; let rgb = [q(c.r), q(c.g), q(c.b)]; @@ -509,6 +637,96 @@ mod tests { } } + /// Runs `f` on its own thread and fails if it has not returned within `secs` seconds. + fn within(secs: u64, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .stack_size(2 << 20) + .spawn(move || { + let _ = tx.send(f()); + }) + .unwrap(); + match rx.recv_timeout(std::time::Duration::from_secs(secs)) { + Ok(v) => v, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!("did not return within {secs} s"), + Err(e) => panic!("the worker thread died: {e}"), + } + } + + #[test] + fn macro_definitions_are_refused_before_the_expander_runs() { + let defs = [ + "\\def\\a#1{\\a{#1#1}}\\a{x}", + "\\gdef\\a#1{\\a{#1#1#1#1}}\\a{x}", + "\\edef\\a#1{\\a{#1#1}}\\a{x}", + "\\xdef\\a#1{{#1}{#1}}\\a{x}", + "\\newcommand{\\a}[1]{\\a{#1#1}}\\a{x}", + "\\renewcommand{\\a}[1]{\\a{#1#1}}\\a{x}", + "\\providecommand{\\a}[1]{\\a{#1#1}}\\a{x}", + "\\let\\a\\frac \\a{1}{2}", + "\\futurelet\\a\\frac \\a{1}{2}", + "\\global\\def\\a#1{\\a{#1#1}}\\a{x}", + "\\long\\def\\a#1{\\a{#1#1}}\\a{x}", + "{\\def\\a#1{\\a{#1#1}}}\\a{x}", + ]; + for src in defs { + // `check_caps` alone, so this cannot hang even if the refusal regresses. + let e = check_caps(src).unwrap_err(); + assert!(e.message.contains("Macro definitions"), "{src}: {e}"); + assert_eq!(e.span.as_ref().map(|r| &src[r.clone()]).map(|w| w.starts_with('\\')), Some(true)); + let s = src.to_string(); + let (c, l, o) = within(10, move || (check(&s).is_err(), layout(&s).is_err(), to_omml(&s, 11.0, None).is_err())); + assert!(c && l && o, "{src}"); + } + // Names that merely start with a definer, escaped backslashes and comments are not macros. + for ok in ["\\default", "\\letter", "\\\\def", "x % \\def\\a\n+1", "\\longrightarrow"] { + assert!(check_caps(ok).is_ok(), "{ok}"); + } + assert!(layout("\\longrightarrow x").is_ok()); + // Text the lexer reads differently from a plain scan must not hide a definition: a + // verbatim `%` is no comment, a `%` in a link address is no comment, `@` joins a word. + for src in [ + "\\verb|%|\\def\\a#1{\\a{#1#1}}\\a{x}", + "\\verb\\x\\\\def\\a#1{\\a{#1#1}}\\a{x}", + "%\\verb|\n\\def\\a#1{\\a{#1#1}}\\a{x}", + "\\href{a%b}{x}\\def\\a#1{\\a{#1#1}}\\a{x}", + "\\url{a%}\\def\\a#1{\\a{#1#1}}\\a{x}", + ] { + assert!(check_caps(src).is_err(), "{src}"); + } + assert!(check_caps("\\verb|\\def| x").is_ok(), "verbatim text is not a definition"); + assert!(check_caps("\\def@x").is_ok(), "`\\def@x` is one unknown word to the lexer"); + } + + #[test] + fn ragged_matrices_are_capped_by_their_padded_size() { + let ragged = format!("\\begin{{matrix}}{}{}\\end{{matrix}}", "a\\\\".repeat(650), "a&".repeat(999) + "a"); + assert!(ragged.len() < MAX_SOURCE_BYTES); + let e = check_caps(&ragged).unwrap_err(); + assert!(e.message.contains("matrix cells"), "{e}"); + let r = ragged.clone(); + let (l, o) = within(10, move || (layout(&r).unwrap_err(), to_omml(&r, 11.0, None).unwrap_err())); + assert!(l.message.contains("matrix cells") && o.message.contains("matrix cells")); + // Without the environment words there is no grid to count; the parser rejects it. + // Ordinary and wide-but-regular matrices still work, and so does a trailing `\\`. + let wide = format!("\\begin{{pmatrix}}{}\\end{{pmatrix}}", vec!["a&".repeat(39) + "a"; 40].join("\\\\")); + assert!(wide.len() < MAX_SOURCE_BYTES); + assert!(layout(&wide).is_ok()); + assert!(to_omml(&wide, 11.0, None).is_ok()); + assert!(layout("\\begin{pmatrix} a & b \\\\ c & d \\\\ \\end{pmatrix}").is_ok()); + // Diagram arrows and `alignedat` column counts size a grid without any `&`. + let cd = format!("\\begin{{CD}}{}{}\\end{{CD}}", "A\\\\".repeat(900), "@>>>".repeat(300)); + assert!(cd.len() < MAX_SOURCE_BYTES); + assert!(check_caps(&cd).is_err_and(|e| e.message.contains("matrix cells"))); + let r = "\\begin{alignedat}{99999999}a\\end{alignedat}"; + assert!(check_caps(r).is_err_and(|e| e.message.contains("matrix cells"))); + assert!(check_caps("\\begin{alignedat}{2}a&b&c&d\\end{alignedat}").is_ok()); + assert!(layout("\\begin{CD}A @>f>> B \\\\ @VVV @VVV \\\\ C @>>> D\\end{CD}").is_ok()); + assert!(check_caps("\\operatorname{curl} 50\\%").is_ok()); + let two = format!("{0}{0}", "\\begin{matrix}a&b\\\\c&d\\end{matrix}"); + assert!(check_caps(&two).is_ok()); + } + #[test] fn an_injected_panic_is_an_error_not_a_crash() { INJECT_PANIC.with(|p| p.set(true)); diff --git a/crates/math/src/omml.rs b/crates/math/src/omml.rs index dc0141aed8..7d5c668353 100644 --- a/crates/math/src/omml.rs +++ b/crates/math/src/omml.rs @@ -406,6 +406,9 @@ impl Writer { } ParseNode::Array { body, is_cd: None | Some(false), .. } => { let cols = body.iter().map(Vec::len).max().unwrap_or(0).max(1); + if body.len().saturating_mul(cols) > crate::MAX_CELLS { + return Err(MathError::new(format!("An equation can have at most {} matrix cells.", crate::MAX_CELLS), None)); + } self.out.push_str(&format!( "" )); diff --git a/docs/decisions.md b/docs/decisions.md index 09bc9b5cc9..7ccc445c8b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -95,7 +95,10 @@ LaTeX subset: access. Indexing is not counted; the fuzz run covers it. - **Fuzzing.** 70,000 random token strings and 50,000 mutations of valid equations: no panic, no input slower than 5 ms. Self-referencing and exponential macros stop at the parser's - 1,000-expansion limit. Nesting deeper than 32 is refused ("Recursion limit exceeded"), and + 1,000-expansion limit, which counts expansions and not their size: a definition whose + argument doubles on every call never reaches it. The wrapper therefore refuses macro + definitions (`\def`, `\newcommand`, `\let` and the like) before RaTeX sees the source, and + caps the padded size of matrices at 2,500 cells. Nesting deeper than 32 is refused ("Recursion limit exceeded"), and the deepest accepted input needs under 256 KB of stack in a release build, well inside the smallest main-thread stack we run on (1 MB on Windows). Absurd sizes (`\rule{1e308em}{1em}`) lay out with huge dimensions, so the wrapper caps them. From 1ff10df55756d3823bcf91e3d3fc31462b6276b4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 20:56:00 +0100 Subject: [PATCH 21/68] fix(autosum): stop the guessed range at a blank cell (#3291) The single-cell AutoSum guess stepped over one blank cell when a number sat above it, so a second block of numbers below a gap was summed together with the first block. It now stops at the first non-number, as Excel does. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/formulas.rs | 5 +---- crates/engine/src/tests.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index d72f814a18..b38571d64d 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -179,10 +179,7 @@ fn guessed_range(sh: &gridcraft_model::sheet::Sheet, at: CellRef) -> Option 0 && (numeric(CellRef::new(at.row - 1, at.col)) || at.col == 0 || !numeric(CellRef::new(at.row, at.col - 1))) { let mut top = at.row - 1; - while top > 0 - && (numeric(CellRef::new(top - 1, at.col)) - || sh.value(CellRef::new(top - 1, at.col)).is_empty() && top > 1 && numeric(CellRef::new(top - 2, at.col))) - { + while top > 0 && numeric(CellRef::new(top - 1, at.col)) { top -= 1; } if numeric(CellRef::new(at.row - 1, at.col)) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fe42b6977b..0fccb81e1a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2067,6 +2067,19 @@ fn formula_at(s: &Session, a: &str) -> Option { s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).and_then(|c| c.formula.as_ref().map(|f| f.text.clone())) } +#[test] +fn autosum_of_a_single_cell_stops_at_a_blank_cell() { + // #3291: a blank row between two blocks of numbers ended the guess one block too late, so the + // second total summed the first block (and its total) as well. + let mut s = s(); + s.execute("range.setValues", json!({"range": "B4", "values": [[1], [2], [3]]})).unwrap(); + s.execute("cell.set", json!({"cell": "B7", "input": "=SUM(B4:B6)"})).unwrap(); + s.execute("range.setValues", json!({"range": "B9", "values": [[10], [20]]})).unwrap(); + s.execute("selection.set", json!({"cell": "B11"})).unwrap(); + s.execute("formulas.autoSum", json!({})).unwrap(); + assert_eq!(v(&s, "B11"), Value::Number(30.0)); +} + #[test] fn autosum_over_a_row_totals_it_to_the_right() { // As in Excel: a row selected and AutoSum puts one total to its right, not a one-cell total From 22c06b7a4a394334e0d35f8880da2e9ce7d830e6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:49:52 +0100 Subject: [PATCH 22/68] BINOM.DIST, POISSON.DIST: Loader mass, recurrence sums, exact prefactors (#3324) The mass came from ln_gamma differences (relative error 1.1e-13 at n = 100, 1.5e-11 at n = 10,000) and the cumulative forms summed up to 10,000 of them. The mass now comes from Loader's saddle-point formula, the cumulative sum walks away from the mode by the ratio of neighbouring terms and stops when terms stop mattering, and the incomplete beta / gamma branches take the same mass as their prefactor. Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/special.rs | 36 +++- crates/functions/src/stat.rs | 5 +- crates/functions/src/stat/distributions.rs | 191 +++++++++++++++-- crates/functions/src/stat/tests.rs | 230 +++++++++++++++++++++ 4 files changed, 436 insertions(+), 26 deletions(-) diff --git a/crates/functions/src/special.rs b/crates/functions/src/special.rs index 1541cd8a13..b173ff7654 100644 --- a/crates/functions/src/special.rs +++ b/crates/functions/src/special.rs @@ -88,11 +88,17 @@ pub(crate) fn reg_gamma_p(a: f64, x: f64) -> f64 { if x.is_infinite() { return 1.0; } - if x < a + 1.0 { gamma_series(a, x) } else { 1.0 - gamma_cf(a, x) } + if x < a + 1.0 { gamma_series(a, x, front_of(a, x)) } else { 1.0 - gamma_cf(a, x, front_of(a, x)) } } /// Regularised upper incomplete gamma Q(a, x) = 1 − P(a, x). pub(crate) fn reg_gamma_q(a: f64, x: f64) -> f64 { + let front = if a > 0.0 && x > 0.0 && x.is_finite() { (-x + a * x.ln() - ln_gamma(a)).exp() } else { 0.0 }; + reg_gamma_q_front(a, x, front) +} + +/// Q(a, x) given the prefactor `e^-x x^a / Γ(a)` (the Poisson mass at a - 1, times x). +pub(crate) fn reg_gamma_q_front(a: f64, x: f64, front: f64) -> f64 { if a.is_nan() || a <= 0.0 || x.is_nan() || x < 0.0 || !a.is_finite() { return f64::NAN; } @@ -102,10 +108,15 @@ pub(crate) fn reg_gamma_q(a: f64, x: f64) -> f64 { if x.is_infinite() { return 0.0; } - if x < a + 1.0 { 1.0 - gamma_series(a, x) } else { gamma_cf(a, x) } + if x < a + 1.0 { 1.0 - gamma_series(a, x, front) } else { gamma_cf(a, x, front) } } -fn gamma_series(a: f64, x: f64) -> f64 { +/// `e^-x x^a / Γ(a)`. +fn front_of(a: f64, x: f64) -> f64 { + (-x + a * x.ln() - ln_gamma(a)).exp() +} + +fn gamma_series(a: f64, x: f64, front: f64) -> f64 { let mut ap = a; let mut sum = 1.0 / a; let mut del = sum; @@ -117,10 +128,10 @@ fn gamma_series(a: f64, x: f64) -> f64 { break; } } - sum * (-x + a * x.ln() - ln_gamma(a)).exp() + sum * front } -fn gamma_cf(a: f64, x: f64) -> f64 { +fn gamma_cf(a: f64, x: f64, front: f64) -> f64 { let tiny = 1e-300; let mut b = x + 1.0 - a; let mut c = 1.0 / tiny; @@ -144,7 +155,7 @@ fn gamma_cf(a: f64, x: f64) -> f64 { break; } } - (-x + a * x.ln() - ln_gamma(a)).exp() * h + front * h } /// Error function. @@ -187,6 +198,17 @@ pub(crate) fn erfc(x: f64) -> f64 { /// Regularised incomplete beta I_x(a, b). pub(crate) fn reg_inc_beta(x: f64, a: f64, b: f64) -> f64 { + if x > 0.0 && x < 1.0 && a > 0.0 && b > 0.0 { + let ln_bt = -ln_beta(a, b) + a * x.ln() + b * (1.0 - x).ln(); + return reg_inc_beta_front(x, a, b, ln_bt.exp()); + } + reg_inc_beta_front(x, a, b, 0.0) +} + +/// I_x(a, b) given the prefactor `bt = x^a (1-x)^b / B(a, b)` (symmetric in the two sides). A +/// caller that knows `bt` more accurately than the log-gamma route gives (the binomial mass, for +/// instance) passes it here. +pub(crate) fn reg_inc_beta_front(x: f64, a: f64, b: f64, bt: f64) -> f64 { if a.is_nan() || a <= 0.0 || b.is_nan() || b <= 0.0 || !(0.0..=1.0).contains(&x) { return f64::NAN; } @@ -196,8 +218,6 @@ pub(crate) fn reg_inc_beta(x: f64, a: f64, b: f64) -> f64 { if x == 1.0 { return 1.0; } - let ln_bt = -ln_beta(a, b) + a * x.ln() + b * (1.0 - x).ln(); - let bt = ln_bt.exp(); if x < (a + 1.0) / (a + b + 2.0) { bt * beta_cf(a, b, x) / a } else { 1.0 - bt * beta_cf(b, a, 1.0 - x) / b } } diff --git a/crates/functions/src/stat.rs b/crates/functions/src/stat.rs index 270bd23735..790915c953 100644 --- a/crates/functions/src/stat.rs +++ b/crates/functions/src/stat.rs @@ -3,7 +3,10 @@ use gridcraft_core::{CellError, Value}; -use crate::special::{erf, gamma, invert, ln_beta, ln_gamma, norm_cdf, norm_inv, norm_pdf, reg_gamma_p, reg_gamma_q, reg_inc_beta}; +use crate::special::{ + erf, gamma, invert, ln_beta, ln_gamma, norm_cdf, norm_inv, norm_pdf, reg_gamma_p, reg_gamma_q, reg_gamma_q_front, reg_inc_beta, + reg_inc_beta_front, +}; use crate::util::{A, R, S, arg, array_numbers, array_val, as_array, boolean, has, num, num_val, numbers, numbers_a, opt_num}; use crate::{Arg, Ctx, FnSpec, VAR}; diff --git a/crates/functions/src/stat/distributions.rs b/crates/functions/src/stat/distributions.rs index a3964ad80e..7fa486e933 100644 --- a/crates/functions/src/stat/distributions.rs +++ b/crates/functions/src/stat/distributions.rs @@ -1,7 +1,7 @@ use super::descriptive::{arg_nums, arg_pairs, mean, var_s}; use super::{ Arg, C, CellError, R, Value, arg, as_array, boolean, erf, gamma, has, invert, ln_beta, ln_gamma, norm_cdf, norm_inv, norm_pdf, num, num_val, - reg_gamma_p, reg_gamma_q, reg_inc_beta, + reg_gamma_p, reg_gamma_q, reg_gamma_q_front, reg_inc_beta, reg_inc_beta_front, }; // --------------------------------------------------------------------------------------------- @@ -93,6 +93,95 @@ fn f_pdf(x: f64, d1: f64, d2: f64) -> f64 { const MAX_BINOM_TRIALS: f64 = 2_147_483_646.0; +/// Stirling-series error `ln n! - ((n + 1/2) ln n - n + ln(2π)/2)` for integer `n >= 1`: exact +/// table (computed with 60-digit Decimal arithmetic) up to 30, then the series, whose first +/// omitted term is below 1e-19 there. +fn stirlerr(n: f64) -> f64 { + const TABLE: [f64; 31] = [ + 0.0, + 0.08106146679532726, + 0.0413406959554093, + 0.02767792568499834, + 0.020790672103765093, + 0.016644691189821193, + 0.013876128823070748, + 0.01189670994589177, + 0.010411265261972096, + 0.009255462182712733, + 0.00833056343336287, + 0.007573675487951841, + 0.00694284010720953, + 0.006408994188004207, + 0.0059513701127588475, + 0.005554733551962801, + 0.0052076559196096404, + 0.004901395948434738, + 0.004629153749334028, + 0.004385560249232324, + 0.004166319691996922, + 0.00396795421864086, + 0.0037876180684444346, + 0.0036229602246830948, + 0.003472021382978767, + 0.003333155636728093, + 0.003204970228055038, + 0.0030862786826087773, + 0.002976063983550409, + 0.0028734493623524663, + 0.0027776749297526936, + ]; + if n <= 30.0 { + return TABLE.get(n as usize).copied().unwrap_or(0.0); + } + let r = 1.0 / n; + let r2 = r * r; + r * (1.0 / 12.0 - r2 * (1.0 / 360.0 - r2 * (1.0 / 1260.0 - r2 * (1.0 / 1680.0 - r2 * (1.0 / 1188.0))))) +} + +/// `x ln(x/np) + np - x` without the cancellation of the direct formula when `x` is near `np` +/// (Loader, 2000). +fn bd0(x: f64, np: f64) -> f64 { + if (x - np).abs() < 0.1 * (x + np) { + let v = (x - np) / (x + np); + let mut s = (x - np) * v; + if s.abs() < f64::MIN_POSITIVE { + return s; + } + let mut ej = 2.0 * x * v; + let v2 = v * v; + for j in 1..1000 { + ej *= v2; + let s1 = s + ej / f64::from(2 * j + 1); + if s1 == s { + return s1; + } + s = s1; + } + } + x * (x / np).ln() + np - x +} + +/// `(1 - p)^e` with the rounding error of `1 - p` (it is not exact for `p < 1/2`) folded back in, +/// which `e` would otherwise multiply. +fn pow_one_minus(p: f64, e: f64) -> f64 { + let hi = 1.0 - p; + let lo = (1.0 - hi) - p; + hi.powf(e) * (e * (lo / hi).ln_1p()).exp() +} + +/// `C(n, k)` for a small `k` as a product of `k` ratios. +fn choose_small(n: f64, k: f64) -> f64 { + let mut c = 1.0; + let mut j = 0.0; + while j < k { + c *= (n - j) / (j + 1.0); + j += 1.0; + } + c +} + +/// Binomial mass at integer `k`, `0 <= k <= n`, by Loader's saddle-point formula: no log-gamma +/// of large numbers, so the relative error stays near 1e-15 for any `n`. fn binom_pmf(k: f64, n: f64, p: f64) -> f64 { if k < 0.0 || k > n { return 0.0; @@ -103,7 +192,60 @@ fn binom_pmf(k: f64, n: f64, p: f64) -> f64 { if p == 1.0 { return if k == n { 1.0 } else { 0.0 }; } - (ln_comb(n, k) + k * p.ln() + (n - k) * (1.0 - p).ln()).exp() + if k == 0.0 { + return if n == 0.0 { 1.0 } else { pow_one_minus(p, n) }; + } + if k == n { + return p.powf(n); + } + // A few successes or a few failures: the product form has no large cancelling terms. + if k < 16.0 { + return choose_small(n, k) * p.powi(k as i32) * pow_one_minus(p, n - k); + } + if n - k < 16.0 { + return choose_small(n, n - k) * p.powf(k) * pow_one_minus(p, n - k); + } + let q = 1.0 - p; + let lc = stirlerr(n) - stirlerr(k) - stirlerr(n - k) - bd0(k, n * p) - bd0(n - k, n * q); + let lf = std::f64::consts::TAU.ln() + k.ln() + (-k / n).ln_1p(); + (lc - 0.5 * lf).exp() +} + +/// Sum of the binomial masses 0..=k for `n <= 10_000`: starts at the term nearest the mode +/// (accurate by the formula above) and walks away from it by the ratio of neighbouring masses, +/// one multiply per term, stopping once the terms no longer matter. Above the mode it sums the +/// upper tail instead and subtracts it from 1. +fn binom_cdf_sum(k: f64, n: f64, p: f64) -> f64 { + let q = 1.0 - p; + if p == 0.0 { + return 1.0; + } + if p == 1.0 { + return 0.0; + } + if k <= n * p { + // mass(i - 1) = mass(i) * i / (n - i + 1) * q / p + let mut t = binom_pmf(k, n, p); + let mut s = t; + let mut i = k; + while i >= 1.0 && t > s * 1e-18 { + t *= i / (n - i + 1.0) * (q / p); + s += t; + i -= 1.0; + } + s.min(1.0) + } else { + // mass(i + 1) = mass(i) * (n - i) / (i + 1) * p / q + let mut t = binom_pmf(k + 1.0, n, p); + let mut s = t; + let mut i = k + 1.0; + while i < n && t > s * 1e-18 { + t *= (n - i) / (i + 1.0) * (p / q); + s += t; + i += 1.0; + } + (1.0 - s).max(0.0) + } } fn binom_cdf(k: f64, n: f64, p: f64) -> f64 { @@ -114,13 +256,7 @@ fn binom_cdf(k: f64, n: f64, p: f64) -> f64 { return 1.0; } if n <= 10_000.0 { - let mut s = 0.0; - let mut i = 0.0; - while i <= k { - s += binom_pmf(i, n, p); - i += 1.0; - } - return s.min(1.0); + return binom_cdf_sum(k, n, p); } if p == 0.0 { return 1.0; @@ -128,14 +264,19 @@ fn binom_cdf(k: f64, n: f64, p: f64) -> f64 { if p == 1.0 { return 0.0; } - reg_inc_beta(1.0 - p, n - k, k + 1.0) + // I_(1-p)(n-k, k+1) has prefactor (n-k) p mass(k). + reg_inc_beta_front(1.0 - p, n - k, k + 1.0, (n - k) * p * binom_pmf(k, n, p)) } +/// Poisson mass at integer `x >= 0` by Loader's formula. fn poisson_pmf(x: f64, m: f64) -> f64 { if m == 0.0 { return if x == 0.0 { 1.0 } else { 0.0 }; } - (-m + x * m.ln() - ln_gamma(x + 1.0)).exp() + if x == 0.0 { + return (-m).exp(); + } + (-stirlerr(x) - bd0(x, m)).exp() / (std::f64::consts::TAU * x).sqrt() } fn poisson_cdf(x: f64, m: f64) -> f64 { @@ -143,15 +284,31 @@ fn poisson_cdf(x: f64, m: f64) -> f64 { return 1.0; } if x <= 1000.0 { - let mut s = 0.0; - let mut i = 0.0; - while i <= x { - s += poisson_pmf(i, m); + if x <= m { + // mass(i - 1) = mass(i) * i / m, downwards from x while the terms matter + let mut t = poisson_pmf(x, m); + let mut s = t; + let mut i = x; + while i >= 1.0 && t > s * 1e-18 { + t *= i / m; + s += t; + i -= 1.0; + } + return s.min(1.0); + } + // Above the mean: 1 minus the upper tail, mass(i + 1) = mass(i) * m / (i + 1). + let mut t = poisson_pmf(x + 1.0, m); + let mut s = t; + let mut i = x + 1.0; + while t > s * 1e-18 { + t *= m / (i + 1.0); + s += t; i += 1.0; } - return s.min(1.0); + return (1.0 - s).max(0.0); } - reg_gamma_q(x + 1.0, m) + // Q(x+1, m) has prefactor m mass(x). + reg_gamma_q_front(x + 1.0, m, m * poisson_pmf(x, m)) } pub(super) fn norm_dist(a: &[Arg], _: C) -> R { diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index ba59116cd7..f8a8c18903 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -617,3 +617,233 @@ fn aggregate_helper() { close(aggregate_values_k(9, &vals, &nv(2.0)), 9.0); is_err(aggregate_values_k(14, &vals, &nv(10.0)), CellError::Num); } + +// B1: BINOM.DIST and POISSON.DIST went through ln_gamma differences (relative error 1.1e-13 at +// n = 100, 1.5e-11 at n = 10,000). Reference values: 70-digit Decimal arithmetic on the exact +// double `p` (mass by the neighbour-ratio recurrence from q^n, cdf as the running sum), rounded +// once to f64. Columns: k, n, p, mass, cdf. +#[rustfmt::skip] +const BINOM_REF: &[(f64, f64, f64, f64, f64)] = &[ + (0.0, 10.0, 0.5, 0.0009765625, 0.0009765625), + (1.0, 10.0, 0.5, 0.009765625, 0.0107421875), + (3.0, 10.0, 0.5, 0.1171875, 0.171875), + (5.0, 10.0, 0.5, 0.24609375, 0.623046875), + (7.0, 10.0, 0.5, 0.1171875, 0.9453125), + (9.0, 10.0, 0.5, 0.009765625, 0.9990234375), + (0.0, 10.0, 0.3, 0.028247524900000005, 0.028247524900000005), + (1.0, 10.0, 0.3, 0.12106082100000001, 0.14930834590000003), + (2.0, 10.0, 0.3, 0.23347444050000002, 0.3827827864), + (3.0, 10.0, 0.3, 0.266827932, 0.6496107184000001), + (4.0, 10.0, 0.3, 0.200120949, 0.8497316674000001), + (5.0, 10.0, 0.3, 0.10291934519999998, 0.9526510126), + (7.0, 10.0, 0.3, 0.009001691999999999, 0.9984096136), + (9.0, 10.0, 0.3, 0.00013778099999999996, 0.9999940951), + (0.0, 10.0, 0.999, 1.0000000000000088e-30, 1.0000000000000088e-30), + (1.0, 10.0, 0.999, 9.99000000000008e-27, 9.99100000000008e-27), + (5.0, 10.0, 0.999, 2.507425174812609e-13, 2.50951798425701e-13), + (9.0, 10.0, 0.999, 0.00991035916125875, 0.009955119790251798), + (0.0, 100.0, 0.5, 7.888609052210118e-31, 7.888609052210118e-31), + (1.0, 100.0, 0.5, 7.888609052210118e-29, 7.967495142732219e-29), + (35.0, 100.0, 0.5, 0.0008638556657416528, 0.0017588208614850792), + (45.0, 100.0, 0.5, 0.048474296626430755, 0.18410080866334813), + (50.0, 100.0, 0.5, 0.07958923738717877, 0.5397946186935894), + (55.0, 100.0, 0.5, 0.048474296626430755, 0.8643734879630827), + (65.0, 100.0, 0.5, 0.0008638556657416528, 0.9991050348042566), + (99.0, 100.0, 0.5, 7.888609052210118e-29, 1.0), + (0.0, 100.0, 0.01, 0.3660323412732295, 0.3660323412732295), + (1.0, 100.0, 0.01, 0.3697296376497268, 0.7357619789229563), + (2.0, 100.0, 0.01, 0.1848648188248634, 0.9206267977478196), + (4.0, 100.0, 0.01, 0.014941714856895142, 0.9965676784122455), + (50.0, 100.0, 0.01, 6.103987557173001e-72, 1.0), + (99.0, 100.0, 0.01, 9.900000000000021e-197, 1.0), + (0.0, 100.0, 0.7, 5.15377520732019e-53, 5.15377520732019e-53), + (1.0, 100.0, 0.7, 1.2025475483747105e-50, 1.207701323582031e-50), + (50.0, 100.0, 0.7, 1.302622713144541e-05, 2.2060913327166086e-05), + (56.0, 100.0, 0.7, 0.001028871216633018, 0.0021146172813184595), + (65.0, 100.0, 0.7, 0.04677968235272982, 0.16285828837178737), + (70.0, 100.0, 0.7, 0.08678386475342809, 0.5376602639846381), + (75.0, 100.0, 0.7, 0.04955992276217012, 0.8864298182958186), + (84.0, 100.0, 0.7, 0.0005638655029474704, 0.9995950004580563), + (99.0, 100.0, 0.7, 1.3862042184106021e-14, 0.9999999999999997), + (0.0, 1000.0, 0.5, 9.332636185032189e-302, 9.332636185032189e-302), + (1.0, 1000.0, 0.5, 9.332636185032189e-299, 9.341968821217221e-299), + (453.0, 1000.0, 0.5, 0.00030353498700958767, 0.00162629990658169), + (484.0, 1000.0, 0.5, 0.015123665829158384, 0.1634683412157977), + (500.0, 1000.0, 0.5, 0.0252250181783608, 0.5126125090891804), + (516.0, 1000.0, 0.5, 0.015123665829158384, 0.8516553246133607), + (547.0, 1000.0, 0.5, 0.00030353498700958767, 0.9986772350804279), + (999.0, 1000.0, 0.5, 9.332636185032189e-299, 1.0), + (0.0, 1000.0, 0.3, 1.2532566399657381e-155, 1.2532566399657381e-155), + (1.0, 1000.0, 0.3, 5.371099885567449e-153, 5.383632451967106e-153), + (257.0, 1000.0, 0.3, 0.00030959977077928017, 0.0014835731103312242), + (286.0, 1000.0, 0.3, 0.0174263984921581, 0.1759288949498673), + (300.0, 1000.0, 0.3, 0.027521003821268385, 0.5155935198141203), + (314.0, 1000.0, 0.3, 0.017109129819617666, 0.8414952343056957), + (343.0, 1000.0, 0.3, 0.00036310112605077133, 0.9985016810663147), + (500.0, 1000.0, 0.3, 3.4791609391626546e-40, 1.0), + (999.0, 1000.0, 0.3, 0.0, 1.0), + (0.0, 1000.0, 0.001, 0.36769542477096406, 0.36769542477096406), + (1.0, 1000.0, 0.001, 0.36806348825922325, 0.7357589130301873), + (2.0, 1000.0, 0.001, 0.18403174412961162, 0.9197906571597989), + (4.0, 1000.0, 0.001, 0.01528995542083862, 0.9963631219704782), + (500.0, 1000.0, 0.001, 0.0, 1.0), + (999.0, 1000.0, 0.001, 0.0, 1.0), + (0.0, 10000.0, 0.5, 0.0, 0.0), + (1.0, 10000.0, 0.5, 0.0, 0.0), + (4850.0, 10000.0, 0.5, 8.861480551702583e-05, 0.0013939837588563594), + (4950.0, 10000.0, 0.5, 0.004839495142316416, 0.161087099897656), + (5000.0, 10000.0, 0.5, 0.007978646139382154, 0.5039893230696911), + (5050.0, 10000.0, 0.5, 0.004839495142316416, 0.8437523952446604), + (5150.0, 10000.0, 0.5, 8.861480551702583e-05, 0.9986946310466607), + (9999.0, 10000.0, 0.5, 0.0, 1.0), + (0.0, 10000.0, 0.3, 0.0, 0.0), + (1.0, 10000.0, 0.3, 0.0, 0.0), + (2863.0, 10000.0, 0.3, 9.71726742023389e-05, 0.0013927715709303387), + (2954.0, 10000.0, 0.3, 0.0052756073908582085, 0.16038574844431697), + (3000.0, 10000.0, 0.3, 0.008705361365067056, 0.504932983819298), + (3046.0, 10000.0, 0.3, 0.005244996814931252, 0.8448693061622872), + (3137.0, 10000.0, 0.3, 0.00010232641238302388, 0.9986013755801396), + (5000.0, 10000.0, 0.3, 0.0, 1.0), + (9999.0, 10000.0, 0.3, 0.0, 1.0), + (0.0, 10000.0, 0.0001, 0.3678610464329299, 0.3678610464329299), + (1.0, 10000.0, 0.0001, 0.3678978362165516, 0.7357588826494815), + (2.0, 10000.0, 0.0001, 0.1839489181082758, 0.9197078007577573), + (4.0, 10000.0, 0.0001, 0.015324477632794846, 0.996342452182816), + (5000.0, 10000.0, 0.0001, 0.0, 1.0), + (9999.0, 10000.0, 0.0001, 0.0, 1.0), + (0.0, 10000.0, 0.999, 0.0, 0.0), + (1.0, 10000.0, 0.999, 0.0, 0.0), + (5000.0, 10000.0, 0.999, 0.0, 0.0), + (9981.0, 10000.0, 0.999, 0.0037205945263045544, 0.007158161342006954), + (9987.0, 10000.0, 0.999, 0.07292252318084555, 0.20834867055478343), + (9990.0, 10000.0, 0.999, 0.12517263665023892, 0.5421328760209826), + (9993.0, 10000.0, 0.999, 0.09007019224850273, 0.8699847268232276), + (9999.0, 10000.0, 0.999, 0.00045218564541589875, 0.9999548266540229), + (0.0, 100000.0, 0.5, 0.0, 0.0), + (1.0, 100000.0, 0.5, 0.0, 0.0), + (49526.0, 100000.0, 0.5, 2.821098952769392e-05, 0.00137358872189177), + (49842.0, 100000.0, 0.5, 0.0015314620321580088, 0.15959653953914368), + (50000.0, 100000.0, 0.5, 0.00252312621419674, 0.5012615631070984), + (50158.0, 100000.0, 0.5, 0.0015314620321580088, 0.8419349224930143), + (50474.0, 100000.0, 0.5, 2.821098952769392e-05, 0.9986546222676359), + (99999.0, 100000.0, 0.5, 0.0, 1.0), + (0.0, 100000.0, 0.3, 0.0, 0.0), + (1.0, 100000.0, 0.3, 0.0, 0.0), + (29565.0, 100000.0, 0.3, 3.016598258904529e-05, 0.0013408650955754554), + (29855.0, 100000.0, 0.3, 0.0016703029966719045, 0.15934769308464344), + (30000.0, 100000.0, 0.3, 0.002752954648397428, 0.5015600059172672), + (30145.0, 100000.0, 0.3, 0.0016672321665529399, 0.8423208126454166), + (30435.0, 100000.0, 0.3, 3.067097885268188e-05, 0.9986570625478413), + (50000.0, 100000.0, 0.3, 0.0, 1.0), + (99999.0, 100000.0, 0.3, 0.0, 1.0), + (0.0, 100000.0, 0.99, 0.0, 0.0), + (1.0, 100000.0, 0.99, 0.0, 0.0), + (50000.0, 100000.0, 0.99, 0.0, 0.0), + (98906.0, 100000.0, 0.99, 0.00015962501729101418, 0.001680685850467731), + (98969.0, 100000.0, 0.99, 0.007723834924565287, 0.1660975153530963), + (99000.0, 100000.0, 0.99, 0.012678161323544589, 0.5042686879721229), + (99031.0, 100000.0, 0.99, 0.007885853372194001, 0.8416321140066325), + (99094.0, 100000.0, 0.99, 0.00013276363518518057, 0.9988439452168577), + (99999.0, 100000.0, 0.99, 0.0, 1.0), +]; + +// Columns: x, mean, mass, cdf. The last block has x > 1000, which takes the incomplete-gamma branch. +#[rustfmt::skip] +const POISSON_REF: &[(f64, f64, f64, f64)] = &[ + (0.0, 0.5, 0.6065306597126334, 0.6065306597126334), + (1.0, 0.5, 0.3032653298563167, 0.9097959895689501), + (3.0, 0.5, 0.012636055410679864, 0.9982483774437092), + (0.0, 5.0, 0.006737946999085467, 0.006737946999085467), + (2.0, 5.0, 0.08422433748856833, 0.12465201948308115), + (5.0, 5.0, 0.1754673697678507, 0.6159606548330632), + (10.0, 5.0, 0.018132788707821874, 0.986304731401617), + (25.0, 5.0, 1.294589320478486e-10, 0.9999999999695003), + (70.0, 100.0, 0.00031056089812001654, 0.0009714440282773882), + (100.0, 100.0, 0.039860996809147134, 0.5265621985299984), + (130.0, 100.0, 0.000575252683815463, 0.9982931596294985), + (900.0, 1000.0, 7.516954352125952e-05, 0.0006977673277963068), + (1000.0, 1000.0, 0.012614611348721499, 0.508409367168506), + (1100.0, 1000.0, 9.498944242299507e-05, 0.9991323590365564), + (1050.0, 1000.0, 0.003599490404803648, 0.9439711616363267), + (1200.0, 1000.0, 7.992642848843571e-11, 0.9999999996115061), + (1500.0, 2000.0, 1.878037542328086e-32, 7.468034373687017e-32), + (2000.0, 2000.0, 0.00892024889598624, 0.5059467004517837), + (2100.0, 2000.0, 0.0007442234118916615, 0.9872092799080792), + (2300.0, 2000.0, 4.011826753210622e-12, 0.999999999973895), + (4800.0, 5000.0, 9.987733294132511e-05, 0.002269403878343364), + (5000.0, 5000.0, 0.005641801804664022, 0.5037611677708467), +]; + +fn rel_err(got: Value, want: f64) -> f64 { + let g = got.as_f64().unwrap_or(f64::NAN); + if want == 0.0 { g.abs() } else { ((g - want) / want).abs() } +} + +/// Error bound the grid below must meet: 1e-13, plus 2e-16 per unit of |ln value| for far-tail +/// results (an exp of a sum of large logs cannot do better in double precision). Measured: at +/// most 9e-14 on the grid (the n = 100,000 cumulative cases), 2e-14 for n <= 10,000 away from the +/// far tails, 2e-15 on the Excel-sized central cases. The log-gamma code was off by 1.5e-11. +fn allowed(want: f64) -> f64 { + 1e-13 + 2e-16 * want.abs().ln().abs() +} + +#[test] +fn binom_and_poisson_match_exact_decimal_references() { + // Worst error relative to the allowance (above 1 is a failure) and plain worst error. + let (mut worst, mut worst_plain) = (0.0f64, 0.0f64); + let mut check = |what: &str, got: Value, want: f64| { + let e = rel_err(got, want); + let ratio = e / allowed(want); + if ratio > 1.0 { + println!("{what}: error {e:e}, allowed {:e}", allowed(want)); + } + worst = worst.max(ratio); + if want > 1e-3 { + worst_plain = worst_plain.max(e); + } + }; + for &(k, nn, p, pmf, cdf) in BINOM_REF { + check(&format!("BINOM.DIST({k},{nn},{p},FALSE)"), ev("BINOM.DIST", vec![n(k), n(nn), n(p), b(false)]), pmf); + check(&format!("BINOM.DIST({k},{nn},{p},TRUE)"), ev("BINOM.DIST", vec![n(k), n(nn), n(p), b(true)]), cdf); + } + for &(x, m, pmf, cdf) in POISSON_REF { + check(&format!("POISSON.DIST({x},{m},FALSE)"), ev("POISSON.DIST", vec![n(x), n(m), b(false)]), pmf); + check(&format!("POISSON.DIST({x},{m},TRUE)"), ev("POISSON.DIST", vec![n(x), n(m), b(true)]), cdf); + } + println!("worst error / allowance {worst:.3}; worst relative error where the result is above 1e-3: {worst_plain:e}"); + assert!(worst <= 1.0); + assert!(worst_plain < 1e-13); +} + +#[test] +fn binom_and_poisson_edge_cases() { + for cum in [false, true] { + let pm = |k: f64, nn: f64, p: f64| ev("BINOM.DIST", vec![n(k), n(nn), n(p), b(cum)]); + // p = 0 and p = 1 + close(pm(0.0, 50.0, 0.0), 1.0); + close(pm(3.0, 50.0, 1.0), 0.0); + close(pm(50.0, 50.0, 1.0), 1.0); + // n = 0 + close(pm(0.0, 0.0, 0.3), 1.0); + // k = n is certain when cumulative and p^n otherwise + close(pm(20.0, 20.0, 0.5), if cum { 1.0 } else { 0.5f64.powi(20) }); + close_tol(pm(10_000.0, 10_000.0, 0.999), if cum { 1.0 } else { 0.999f64.powi(10_000) }, 1e-12); + // k = 0 is q^n + close_tol(pm(0.0, 1000.0, 0.001), 0.999f64.powi(1000), 1e-12); + close_tol(pm(0.0, 100_000.0, 0.00001), (1.0f64 - 1e-5).powi(100_000), 1e-9); + } + close(ev("POISSON.DIST", vec![n(0.0), n(0.0), b(false)]), 1.0); + close(ev("POISSON.DIST", vec![n(4.0), n(0.0), b(false)]), 0.0); + close(ev("POISSON.DIST", vec![n(4.0), n(0.0), b(true)]), 1.0); + close_tol(ev("POISSON.DIST", vec![n(0.0), n(3.0), b(true)]), (-3.0f64).exp(), 1e-15); + // Fractions truncate as before. + close(ev("BINOM.DIST", vec![n(6.9), n(10.9), n(0.5), b(false)]), 0.205078125); + // The 10,000 trial switch of the method no longer shows: neighbours agree to 1e-14. + let lo = ev("BINOM.DIST", vec![n(5000.0), n(10_000.0), n(0.5), b(true)]).as_f64().unwrap(); + let hi = ev("BINOM.DIST", vec![n(5000.0), n(10_001.0), n(0.5), b(true)]).as_f64().unwrap(); + let pmf = ev("BINOM.DIST", vec![n(5000.0), n(10_000.0), n(0.5), b(false)]).as_f64().unwrap(); + // cdf(5000; 10,001) = cdf(5000; 10,000) - p * mass(5000; 10,000) by the recurrence on n + assert!(((hi - (lo - 0.5 * pmf)) / hi).abs() < 1e-13, "{lo} {hi}"); + // Inverse stays consistent: the smallest k with cdf >= alpha. + close(ev("BINOM.INV", vec![n(10_000.0), n(0.5), n(0.5)]), 5000.0); +} From 7e8b94fc39f345d8061402c2bdbda5b998018407 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:54:53 +0100 Subject: [PATCH 23/68] BINOM.DIST: keep tiny masses and huge n out of the product form Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/distributions.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/functions/src/stat/distributions.rs b/crates/functions/src/stat/distributions.rs index 7fa486e933..d2e4e34215 100644 --- a/crates/functions/src/stat/distributions.rs +++ b/crates/functions/src/stat/distributions.rs @@ -166,7 +166,9 @@ fn bd0(x: f64, np: f64) -> f64 { fn pow_one_minus(p: f64, e: f64) -> f64 { let hi = 1.0 - p; let lo = (1.0 - hi) - p; - hi.powf(e) * (e * (lo / hi).ln_1p()).exp() + let r = hi.powf(e) * (e * (lo / hi).ln_1p()).exp(); + // An exponent so large that the two factors under- and overflow: the plain form is enough. + if r.is_nan() { (e * (-p).ln_1p()).exp() } else { r } } /// `C(n, k)` for a small `k` as a product of `k` ratios. @@ -199,11 +201,15 @@ fn binom_pmf(k: f64, n: f64, p: f64) -> f64 { return p.powf(n); } // A few successes or a few failures: the product form has no large cancelling terms. - if k < 16.0 { - return choose_small(n, k) * p.powi(k as i32) * pow_one_minus(p, n - k); - } - if n - k < 16.0 { - return choose_small(n, n - k) * p.powf(k) * pow_one_minus(p, n - k); + // (Not for astronomically large n or a power of p near underflow: the saddle-point form + // below handles those through logs.) + if n < 1e30 && p.powf(k) > 1e-280 { + if k < 16.0 { + return choose_small(n, k) * p.powi(k as i32) * pow_one_minus(p, n - k); + } + if n - k < 16.0 { + return choose_small(n, n - k) * p.powf(k) * pow_one_minus(p, n - k); + } } let q = 1.0 - p; let lc = stirlerr(n) - stirlerr(k) - stirlerr(n - k) - bd0(k, n * p) - bd0(n - k, n * q); From d8ba397bb721ff16124b207ff3cedbb8bb5cc7d2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:04:32 +0100 Subject: [PATCH 24/68] math: refuse an alignedat count hidden by a comment or spaces (review point: cap bypass) CodeRabbit found that \begin{alignedat}%{99999999} and {9 9} made the count parser return None, which skipped the 50-pair cap. The lookahead now drops comments and spaces as RaTeX's lexer does, and a matched alignat name with a count that is not a plain digit string is refused. Co-Authored-By: Claude Sonnet 5.5 --- crates/math/src/lib.rs | 45 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/math/src/lib.rs b/crates/math/src/lib.rs index e1f783dcab..62033f2b8d 100644 --- a/crates/math/src/lib.rs +++ b/crates/math/src/lib.rs @@ -390,16 +390,39 @@ fn check_caps(latex: &str) -> Result<(), MathError> { const MAX_ALIGNAT_PAIRS: usize = 50; /// N of `{alignat}{N}`, `{alignat*}{N}` or `{alignedat}{N}` at the start of `rest` (just after -/// `\begin`); `usize::MAX` when the count is present but too long to read. +/// `\begin`). `usize::MAX` when the count is present but is not a plain digit string RaTeX reads +/// the same way (too long, or hidden by a comment, inner spaces or a macro): refused, not skipped. +/// +/// RaTeX reads the environment name and the count through its lexer, which drops comments and +/// spaces, so they are dropped here too before the two groups are compared. fn alignat_columns(rest: &str) -> Option { - let rest = rest.trim_start().strip_prefix('{')?; - let (name, after) = rest.split_once('}')?; + // Enough for the longest name and any count that fits `usize`; a longer count is refused. + const WINDOW: usize = 64; + let mut kept = String::new(); + let mut chars = rest.chars(); + while kept.len() < WINDOW { + match chars.next() { + None => break, + Some('%') => { + for n in chars.by_ref() { + if n == '\n' { + break; + } + } + } + Some(c) if c.is_whitespace() => {} + Some(c) => kept.push(c), + } + } + let (name, after) = kept.strip_prefix('{')?.split_once('}')?; if !matches!(name, "alignat" | "alignat*" | "alignedat") { return None; } - let digits = after.trim_start().strip_prefix('{')?.split('}').next()?.trim(); + let Some(digits) = after.strip_prefix('{').and_then(|a| a.split_once('}')).map(|(d, _)| d) else { + return Some(usize::MAX); + }; if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { - return None; + return Some(usize::MAX); } Some(digits.parse().unwrap_or(usize::MAX)) } @@ -721,6 +744,18 @@ mod tests { let r = "\\begin{alignedat}{99999999}a\\end{alignedat}"; assert!(check_caps(r).is_err_and(|e| e.message.contains("matrix cells"))); assert!(check_caps("\\begin{alignedat}{2}a&b&c&d\\end{alignedat}").is_ok()); + // A comment, inner spaces or a macro in the count do not hide it from the cap. + for hidden in [ + "\\begin{alignedat}%\n{99999999}a\\end{alignedat}", + "\\begin %c\n {alignedat}{99999999}a\\end{alignedat}", + "\\begin{alignedat}{9 9}a\\end{alignedat}", + "\\begin{alignedat}{9%x\n9}a\\end{alignedat}", + "\\begin{align%x\nedat}{99}a\\end{alignedat}", + "\\begin{alignedat}{9\\relax9}a\\end{alignedat}", + ] { + assert!(check_caps(hidden).is_err_and(|e| e.message.contains("matrix cells")), "{hidden}"); + } + assert!(check_caps("\\begin{alignedat} {2} % two pairs\na&b&c&d\\end{alignedat}").is_ok()); assert!(layout("\\begin{CD}A @>f>> B \\\\ @VVV @VVV \\\\ C @>>> D\\end{CD}").is_ok()); assert!(check_caps("\\operatorname{curl} 50\\%").is_ok()); let two = format!("{0}{0}", "\\begin{matrix}a&b\\\\c&d\\end{matrix}"); From 40e75c79127ffa545040d2d97e6cc7d596bafe9b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:05:58 +0100 Subject: [PATCH 25/68] binom/poisson reference test: fail on errors, NaN and non-zero results for zero references (review point) CodeRabbit pointed out that an error or NaN result passed the accuracy test and that a zero reference allowed any finite value (the bound was infinite). Errors now count as infinite error and a zero reference allows 1e-300. Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index f8a8c18903..67e626251d 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -775,7 +775,8 @@ const POISSON_REF: &[(f64, f64, f64, f64)] = &[ ]; fn rel_err(got: Value, want: f64) -> f64 { - let g = got.as_f64().unwrap_or(f64::NAN); + // An error or a non-finite result is the worst possible miss, not a skipped one. + let Some(g) = got.as_f64().filter(|g| g.is_finite()) else { return f64::INFINITY }; if want == 0.0 { g.abs() } else { ((g - want) / want).abs() } } @@ -784,6 +785,10 @@ fn rel_err(got: Value, want: f64) -> f64 { /// most 9e-14 on the grid (the n = 100,000 cumulative cases), 2e-14 for n <= 10,000 away from the /// far tails, 2e-15 on the Excel-sized central cases. The log-gamma code was off by 1.5e-11. fn allowed(want: f64) -> f64 { + // A reference that underflows to 0 must come back as (almost) 0, not as any finite value. + if want == 0.0 { + return 1e-300; + } 1e-13 + 2e-16 * want.abs().ln().abs() } From 86c5c8dd813e05b2f9912bd3dcc4a1e9e042e5a5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:31:04 +0100 Subject: [PATCH 26/68] Math: count \newline as a row break in the matrix cell cap (#3327) RaTeX reads \newline as \\, but the source scan only counted \\ and \cr, so a matrix built with \newline skipped the 2,500 cell cap. Co-Authored-By: Claude Sonnet 5.5 --- crates/math/src/lib.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/math/src/lib.rs b/crates/math/src/lib.rs index 62033f2b8d..3a5b310cfa 100644 --- a/crates/math/src/lib.rs +++ b/crates/math/src/lib.rs @@ -235,7 +235,7 @@ const MACRO_DEFINERS: &[&str] = /// One open `\begin…\end` environment, counted from the source text. struct Grid { - /// Rows ended so far (by `\\` or `\cr`). + /// Rows ended so far (by `\\`, `\cr` or `\newline`). rows: usize, /// Cells in the current row. cells: usize, @@ -315,7 +315,8 @@ fn check_caps(latex: &str) -> Result<(), MathError> { } None } - "cr" => { + // RaTeX reads `\newline` as `\\`, so it ends a row like `\cr` does. + "cr" | "newline" => { if let Some(g) = grids.last_mut() { g.end_row(); } @@ -783,4 +784,20 @@ mod tests { let l = layout("").unwrap(); assert!(l.items.is_empty()); } + + #[test] + fn newline_rows_count_toward_the_matrix_cap() { + // RaTeX reads `\newline` as `\\`, so it ends a row like `\cr` does. + for brk in ["\\newline ", "\\cr ", "\\\\"] { + let src = format!("\\begin{{matrix}}{}{}\\end{{matrix}}", format!("a{brk}").repeat(250), "a&".repeat(700) + "a"); + assert!(src.len() < MAX_SOURCE_BYTES); + let e = check_caps(&src).unwrap_err(); + assert!(e.message.contains("matrix cells"), "{brk}: {e}"); + let s = src.clone(); + let (l, o) = within(10, move || (layout(&s).unwrap_err(), to_omml(&s, 11.0, None).unwrap_err())); + assert!(l.message.contains("matrix cells") && o.message.contains("matrix cells"), "{brk}"); + } + assert!(check_caps("\\begin{matrix}a&b\\newline c&d\\end{matrix}").is_ok()); + assert!(layout("\\begin{matrix}a&b\\newline c&d\\end{matrix}").is_ok()); + } } From b3a709f314ef7203959f23a121836868342451aa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 02:12:09 +0100 Subject: [PATCH 27/68] contributors: set names for vangel76 Co-Authored-By: Claude Sonnet 5.5 --- contributors/people.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index 00f6ce76a1..1b8bcf9965 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -33,7 +33,8 @@ sync_github_name = false [people.vangel76] real_name = "Valentin Klein" -sync_github_name = true +display_name = "vangel76" +sync_github_name = false [people.MacJedi42] sync_github_name = true From 7e828a982c608c5c1e418065af37bc09729ea53c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 01:02:21 +0100 Subject: [PATCH 28/68] Tabs: Ctrl-click on the sheet arrows jumps to the first or last visible sheet (#3350) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/tabs.rs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index ea11615d09..917dc3b7f5 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -22,6 +22,12 @@ fn navigator_items(sheets: &[Arc]) -> Vec<(String, String)> { sheets.iter().enumerate().filter(|(_, s)| s.visibility == Visibility::Visible).map(|(i, s)| (i.to_string(), s.name.clone())).collect() } +/// Workbook index of the first (or, with `last`, the last) visible sheet: where Ctrl-clicking a tab arrow lands. +fn edge_sheet(sheets: &[Arc], last: bool) -> Option { + let mut visible = sheets.iter().enumerate().filter(|(_, s)| s.visibility == Visibility::Visible).map(|(i, _)| i); + if last { visible.next_back() } else { visible.next() } +} + /// Switch to sheet `i` from the tab strip or the navigator. In point mode the formula being typed keeps going on the /// other sheet; otherwise the edit is committed first. fn activate_sheet(app: &mut SheetApp, i: usize) { @@ -117,10 +123,22 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) { ui.add_space(8.0); if view.show_sheet_tabs { if crate::widgets::icon_button(ui, Icon::Left, t.text_dim, app.ui.language.tr("Previous sheet"), vec2(24.0, 24.0)).clicked() { - app.run_or_alert("sheet.previous", json!({})); + // Ctrl-click jumps to the first visible sheet, like Excel's tab scroll buttons. + let edge = + if ui.input(|i| i.modifiers.command) { app.session.active().and_then(|d| edge_sheet(&d.wb.sheets, false)) } else { None }; + match edge { + Some(i) => activate_sheet(app, i), + None => app.run_or_alert("sheet.previous", json!({})), + } } if crate::widgets::icon_button(ui, Icon::Right, t.text_dim, app.ui.language.tr("Next sheet"), vec2(24.0, 24.0)).clicked() { - app.run_or_alert("sheet.next", json!({})); + // Ctrl-click jumps to the last visible sheet. + let edge = + if ui.input(|i| i.modifiers.command) { app.session.active().and_then(|d| edge_sheet(&d.wb.sheets, true)) } else { None }; + match edge { + Some(i) => activate_sheet(app, i), + None => app.run_or_alert("sheet.next", json!({})), + } } let all = crate::widgets::icon_button(ui, Icon::SheetList, t.text_dim, app.ui.language.tr("All sheets"), vec2(24.0, 24.0)); all.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, app.ui.language.tr("All sheets"))); @@ -522,7 +540,8 @@ fn status_bar_menu(app: &mut SheetApp, ui: &mut Ui) { #[cfg(test)] mod tests { use super::{ - MIN_TRACK, NEW_SHEET_WIDTH, SPLIT_WIDTH, activate_sheet, dragged_share, drop_copies_sheet, navigator_items, rename_needs_focus, tab_drop, + MIN_TRACK, NEW_SHEET_WIDTH, SPLIT_WIDTH, activate_sheet, dragged_share, drop_copies_sheet, edge_sheet, navigator_items, rename_needs_focus, + tab_drop, }; use crate::SheetApp; use egui::Modifiers; @@ -614,6 +633,16 @@ mod tests { assert_eq!(navigator_items(&sheets), vec![("0".to_string(), "Data".to_string()), ("3".to_string(), "Summary".to_string())]); } + #[test] + fn ctrl_click_on_the_tab_arrows_lands_on_the_first_and_last_visible_sheet() { + let mut hidden = Sheet::new("Hidden"); + hidden.visibility = Visibility::Hidden; + let sheets = [hidden.clone(), Sheet::new("A"), Sheet::new("B"), Sheet::new("C"), hidden].map(Arc::new); + assert_eq!(edge_sheet(&sheets, false), Some(1)); + assert_eq!(edge_sheet(&sheets, true), Some(3)); + assert_eq!(edge_sheet(&[], true), None); + } + #[test] fn a_rejected_commit_keeps_the_sheet_and_the_edit() { let mut session = gridcraft_engine::Session::new(); From 23c909e4775ac8d28e722ada888980f4faefe42f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 01:53:24 +0100 Subject: [PATCH 29/68] chart perf tests: import LegendPos (legend module now imports it itself) Co-Authored-By: Claude Sonnet 5.5 --- crates/chart/src/render_perf_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/chart/src/render_perf_tests.rs b/crates/chart/src/render_perf_tests.rs index 461c2f1598..ce15e78615 100644 --- a/crates/chart/src/render_perf_tests.rs +++ b/crates/chart/src/render_perf_tests.rs @@ -7,6 +7,7 @@ use super::kinds::squarify; use super::legend::swatch_w; use super::*; use crate::{ApproxMeasure, Measure}; +use gridcraft_model::LegendPos; /// The pre-rewrite `Ctx::fit`: one `Measure` call per candidate length, longest first. fn fit_reference(ctx: &Ctx, s: &str, size: f32, maxw: f32) -> String { From 292b784f0240ae9c415889155eaf3aca686c2e52 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:24:49 -0600 Subject: [PATCH 30/68] fix(calc): apply "Set precision as displayed" in calculation (#1366) * ft-121.7.9: apply Set precision as displayed in calculation (#1343) With the option on, a formula result (and each element of a spill) is rounded to its cell's number format before it is stored and before other formulas read it. Numbers typed, pasted or reformatted while it is on are rounded at once, and turning it on through formulas.calculationOptions {precisionAsDisplayed} rounds every number constant, as Excel does. The rounding is NumberFormat::round_as_displayed in the numfmt crate, which shares the renderer's digit logic (fixed, scientific, fraction). General, date/time, text, digitless and conditional formats keep the full value, as observed in Excel through COM. Nothing changes when the flag is off. Co-Authored-By: Claude Opus 5.5 * ft-121.7.9: round conditional formats by the sign's section under precision as displayed (#1343) Excel does round formats with a condition when "Set precision as displayed" is on; the PR kept them at full value. Observed through COM with synthetic values (and in gridcraft-corpus excel/precision-displayed/pad-on-conditional-sections.xlsx): conditions are ignored and the sign picks the section, the first for positives and the second for negatives. `[<1]0.00;0` shows 2+1/3 as 2 but stores 2.33, and stores -10/3 as -3. Two more observed details: with a condition and a single number section, negatives keep the full value (`[<1]0.00`), unless an `@` section follows (`[<1]0.00;@` rounds them by the first section); and a completely empty section passes to the next one (`0.0;;0.000` stores -2.333 as -2.333, `;0.0` stores 2.333 as 2.3), for formats with or without a condition. Display is unchanged. Co-Authored-By: Claude Opus 5.5 * engine: recalculate spill anchors when a spill cell is reformatted under precision as displayed round_edited_as_displayed only looked at stored-cell changes, but a spill destination lives in Sheet::spill, so reformatting it (or its row or column) left the anchor out of the changed set and the element unrounded. Add each spill anchor whose range holds a changed cell or a changed row/column style to the changed set. Co-Authored-By: Claude Sonnet 5.5 * numfmt: drop a cast the fraction merge made redundant * precision as displayed: keep locked constants on protected sheets, round new sheets, fix manual-mode comment * precision as displayed: name the input sheet in the new-sheet histogram test * precision as displayed: use six values in the new-sheet histogram test --------- Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 2 + crates/calc/src/lib.rs | 2 + crates/calc/src/precision.rs | 52 ++++++++ crates/calc/src/recalc/pass_host.rs | 25 ++++ crates/calc/src/tests.rs | 66 ++++++++++ crates/engine/src/cmd.rs | 116 +++++++++++++++++- crates/engine/src/cmd/file.rs | 4 +- crates/engine/src/cmd/formulas.rs | 22 +++- crates/engine/src/tests.rs | 176 ++++++++++++++++++++++++++- crates/numfmt/src/lib.rs | 54 +++++++++ crates/numfmt/src/render.rs | 181 +++++++++++++++++++++------- crates/numfmt/src/tests.rs | 117 ++++++++++++++++++ docs/function-parity.md | 4 +- 13 files changed, 770 insertions(+), 51 deletions(-) create mode 100644 crates/calc/src/precision.rs diff --git a/ROADMAP.md b/ROADMAP.md index 4219bad028..59b3bf2d8e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -177,6 +177,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) | | 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format | | 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) | +| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) | | 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison | | 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift | | 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) | @@ -288,6 +289,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook | | 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) | | 2026-10-16 | minor | Progress log: interface fonts held once instead of twice | +| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) | | 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting | | 2026-10-14 | minor | Progress log: lookups compare numbers exactly | | 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references | diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs index 27c9e19610..2cc6bf4cf3 100644 --- a/crates/calc/src/lib.rs +++ b/crates/calc/src/lib.rs @@ -4,10 +4,12 @@ #![forbid(unsafe_code)] pub mod eval; +mod precision; pub mod recalc; mod trimrange; pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function}; +pub use precision::DisplayedPrecision; pub use recalc::{Calc, Key, evaluate, now_serial}; #[cfg(test)] diff --git a/crates/calc/src/precision.rs b/crates/calc/src/precision.rs new file mode 100644 index 0000000000..c60f520798 --- /dev/null +++ b/crates/calc/src/precision.rs @@ -0,0 +1,52 @@ +//! "Set precision as displayed" (File › Options › Advanced; `fullPrecision="0"` in `.xlsx`, +//! CalcPrecision in `.xls`): with it on, a number is stored as its cell's number format shows it, +//! and formulas read those rounded values. The rounding itself is the number format crate's +//! ([`gridcraft_numfmt::NumberFormat::round_as_displayed`]); this module looks up each cell's +//! format, parsing every style's code once. + +use std::collections::HashMap; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{StyleId, Workbook}; +use gridcraft_numfmt::NumberFormat; + +/// Rounds values to their cell's displayed precision, remembering each style's parsed format. +/// Styles don't change while it is used (one recalculation pass, one sweep of a workbook). +#[derive(Default)] +pub struct DisplayedPrecision { + /// Parsed format per style; `None` for General, which keeps the full value. + formats: HashMap>, +} + +impl DisplayedPrecision { + pub fn new() -> Self { + Self::default() + } + + /// `n` as the format of `c` on sheet `sheet` displays it (the cell's own style, else its + /// row's, else its column's, as the grid shows it). + pub fn round(&mut self, wb: &Workbook, sheet: usize, c: CellRef, n: f64) -> f64 { + let Some(sh) = wb.sheet(sheet) else { return n }; + let id = sh.style_id(c); + let fmt = self.formats.entry(id).or_insert_with(|| { + let f = NumberFormat::parse_cached(wb.styles.get(id).num_fmt.as_str()); + (!f.is_general()).then_some(f) + }); + match fmt { + Some(f) => f.round_as_displayed(n), + None => n, + } + } + + /// Like [`DisplayedPrecision::round`] for a value: only numbers change. + pub fn round_value(&mut self, wb: &Workbook, sheet: usize, c: CellRef, v: Value) -> Value { + match v { + Value::Number(n) => { + let r = self.round(wb, sheet, c, n); + // Bit-equal results keep the value as it was (no needless change for undo/diffs). + if r.to_bits() == n.to_bits() { Value::Number(n) } else { Value::Number(r) } + } + v => v, + } + } +} diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 5909369fda..9c56b29120 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -64,6 +64,9 @@ pub(super) struct PassHost<'a> { pub(super) tainted: HashSet, /// Whether the formula being evaluated has read a previous value. taint: bool, + /// "Set precision as displayed" is on: results are rounded to their cells' formats before + /// they are stored or read by other formulas. + precision: Option, /// `stack_position()` where the outermost formula being calculated started. stack_top: usize, /// Whether an evaluation ran past the stack budget since the innermost formula started. @@ -104,6 +107,7 @@ impl<'a> PassHost<'a> { members: HashSet::default(), tainted: HashSet::default(), taint: false, + precision: wb.calc.precision_as_displayed.then(crate::DisplayedPrecision::new), stack_top: 0, out_of_stack: false, python: HashMap::default(), @@ -344,6 +348,23 @@ impl PassHost<'_> { let data = a.data.iter().map(|x| if matches!(x, Value::Empty) { Value::Number(0.0) } else { x.clone() }).collect(); Array::new(a.rows, a.cols, data).map(std::sync::Arc::new).unwrap_or(a) }; + // Precision as displayed: each element takes the format of the cell it lands in. + let a = match self.precision.as_mut() { + Some(p) if a.data.iter().any(|x| matches!(x, Value::Number(_))) => { + let cols = a.cols.max(1); + let data = a + .data + .iter() + .enumerate() + .map(|(i, x)| { + let at = CellRef::new(k.1.row.saturating_add((i / cols) as u32), k.1.col.saturating_add((i % cols) as u32)); + p.round_value(self.wb, k.0, at, x.clone()) + }) + .collect(); + Array::new(a.rows, a.cols, data).map(std::sync::Arc::new).unwrap_or(a) + } + _ => a, + }; // A dynamic-array formula anchors a spill range even while its result is one // value -- a FILTER matching one row, a SORT or UNIQUE over one item -- so `C1#` // is the 1 x 1 range and `ROWS(C1#)` is 1, as in Excel (#1491). A formula that @@ -352,6 +373,10 @@ impl PassHost<'_> { a.data.first().cloned().unwrap_or_default() } Value::Empty => Value::Number(0.0), + v @ Value::Number(_) => match self.precision.as_mut() { + Some(p) => p.round_value(self.wb, k.0, k.1, v), + None => v, + }, v => v, }; // An array that can't spill is #SPILL! for the formulas evaluated after it in this pass too. diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index d635907370..d10c2f9832 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1922,6 +1922,72 @@ fn offset_extreme_arguments_return_ref() { } } +/// "Set precision as displayed": results are rounded to their cell's format before they are +/// stored and before other formulas read them. Values observed in Excel (COM, +/// `Workbook.PrecisionAsDisplayed = True`) with the same synthetic formulas. +#[test] +fn precision_as_displayed_rounds_results_by_cell_format() { + let fmt = |t: &mut T, at: &str, code: &str| { + let id = t.wb.styles.intern(gridcraft_model::Style { num_fmt: gridcraft_model::NumFmt::new(code), ..Default::default() }); + t.wb.sheet_mut(0).unwrap().set_style(c(at), id); + }; + let mut t = T::new(); + t.set("A1", "=-130+657.91"); + t.set("A2", "=A1*10"); + t.set("A3", "=A1/7"); + // Cross-cell: E2 rounds what it reads from E1; E1 itself (General) keeps full precision. + t.set("E1", "=10/3"); + t.set("E2", "=E1"); + t.set("E3", "=E2*10"); + t.set("E4", "=E1*10"); + // A spill: each element takes the format of the cell it lands in. + t.set("F1", "=SEQUENCE(3,1,0.123,0.111)"); + t.set("G4", "=SUM(F1:F3)"); + t.set("H1", "=TRUE"); + t.set("H2", "=\"1.5\""); + // A conditional format rounds by the sign's section, not the one displayed: `[<1]0.00;0` + // shows 2+1/3 as `2` but stores 2.33, and stores -10/3 as -3. + t.set("J1", "=2+1/3"); + t.set("J2", "=-10/3"); + t.set("K1", "=J1*3"); + t.set("K2", "=J2*3"); + fmt(&mut t, "J1", "[<1]0.00;0"); + fmt(&mut t, "J2", "[<1]0.00;0"); + fmt(&mut t, "A1", "0"); + fmt(&mut t, "A3", "0.0000"); + fmt(&mut t, "E2", "0"); + fmt(&mut t, "F1", "0.0"); + fmt(&mut t, "F2", "0.0"); + fmt(&mut t, "H1", "0"); + fmt(&mut t, "H2", "0"); + // Off: formats don't change values. + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.num("A1"), -130.0 + 657.91); + assert_eq!(t.num("E2"), 10.0 / 3.0); + t.wb.calc.precision_as_displayed = true; + t.calc.recalc_all(&mut t.wb); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (528.0, 5280.0, 75.4286)); + assert_eq!((t.num("E1"), t.num("E2"), t.num("E3"), t.num("E4")), (10.0 / 3.0, 3.0, 30.0, 10.0 / 3.0 * 10.0)); + let sh = t.wb.sheet(0).unwrap(); + assert_eq!( + (sh.value(c("F1")), sh.value(c("F2")), sh.value(c("F3"))), + (Value::Number(0.1), Value::Number(0.2), Value::Number(0.123 + 0.111 * 2.0)) + ); + assert_eq!(t.num("G4"), 0.1 + 0.2 + (0.123 + 0.111 * 2.0)); + assert_eq!((t.num("J1"), t.num("J2"), t.num("K1"), t.num("K2")), (2.33, -3.0, 2.33 * 3.0, -9.0)); + // Booleans and text are left alone. + assert_eq!((t.get("H1"), t.get("H2")), (Value::Bool(true), Value::from("1.5"))); + // An edit recalculates through the rounded values too. + t.set("A1", "=-130+657.41"); + fmt(&mut t, "A1", "0"); + t.calc.cells_changed(&mut t.wb, &[(0, c("A1"))]); + assert_eq!((t.num("A1"), t.num("A2")), (527.0, 5270.0)); + // Off again: a recalculation brings back full precision. + t.wb.calc.precision_as_displayed = false; + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.num("A2"), (-130.0 + 657.41) * 10.0); +} + #[test] fn analysis_toolpak_value_params_reject_multi_cell_references() { // Excel 365 (observed): EOMONTH, WORKDAY, COUPDAYS, BIN2DEC... give #VALUE! for a reference to more diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index bd18996bdb..da130fe2a2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -406,7 +406,7 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) edits: Vec::new(), }; let r = f(&mut ctx)?; - let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, edits, .. } = ctx; + let Ctx { mut wb, mut changed, structural, mut fit_rows, protection_checked, edits, .. } = ctx; // Equations whose source changed (or that arrived without a layout, as from a paste) are // laid out here, so painting only ever reads the cache. wb.refresh_equations(); @@ -416,6 +416,9 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) if !structural { check_arrays(&d.wb, &wb)?; } + if wb.calc.precision_as_displayed { + round_edited_as_displayed(&d.wb, &mut wb, &mut changed, structural); + } if let Some(log) = d.touched.as_mut() { for (si, c) in changed.iter().take(TOUCH_LOG_LIMIT.saturating_sub(log.len())) { if let Some(sh) = wb.sheet(*si) { @@ -454,6 +457,117 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) Ok(r) } +/// "Set precision as displayed": a number typed, pasted or reformatted is stored as its format +/// shows it (Excel rounds a constant when it is entered and when its cell's format changes, +/// observed through COM). Only cells the edit touched are visited, so this costs nothing for +/// the rest of the workbook; formula cells whose format changed are recalculated, and the +/// recalculation rounds them. A structural edit recalculates everything anyway, so it only +/// rounds its constants (a sheet the edit created, for one, holds written numbers). +fn round_edited_as_displayed(old: &Workbook, wb: &mut Workbook, changed: &mut Vec, structural: bool) { + let mut prec = gridcraft_calc::DisplayedPrecision::new(); + for si in 0..wb.sheets.len() { + let Some(after) = wb.sheets.get(si) else { continue }; + // Sheets are matched by name. A sheet the edit created has no earlier version, so all of + // its cells are new. + let before = old.sheet_index(&after.name).and_then(|i| old.sheets.get(i)); + if before.is_some_and(|b| std::sync::Arc::ptr_eq(b, after)) { + continue; + } + let diffs: Vec = match before { + Some(before) => before.cells.diff(&after.cells), + None => after.cells.iter().map(|(c, _)| c).collect(), + }; + let mut anchors = std::collections::HashSet::new(); + for &c in &diffs { + if !structural && after.cell(c).is_some_and(|cell| cell.formula.is_some()) { + changed.push((si, c)); + anchors.insert(c); + } + } + let updates = displayed_updates(&mut prec, wb, si, diffs.iter().copied()); + // A spill destination is no stored cell: reformatting it (or its row or column) leaves + // no change in the store, so its anchor is recalculated to round the new element. + if let (Some(before), false) = (before, structural) { + for (&anchor, range) in &after.spill_ranges { + if !anchors.contains(&anchor) + && (diffs.iter().any(|d| range.contains(*d)) + || line_styles_differ(&before.rows, &after.rows, range.start.row, range.end.row) + || line_styles_differ(&before.cols, &after.cols, range.start.col, range.end.col)) + { + changed.push((si, anchor)); + } + } + } + if updates.is_empty() { + continue; + } + let Some(sh) = wb.sheet_mut(si) else { continue }; + for (c, r) in updates { + if let Some(cell) = sh.cells.get_mut(c) { + cell.value = gridcraft_core::Value::Number(r); + if !structural { + changed.push((si, c)); + } + } + } + } +} + +/// Whether any row or column style in `lo..=hi` differs between two sheets' line maps. +fn line_styles_differ( + before: &std::collections::BTreeMap, + after: &std::collections::BTreeMap, + lo: u32, + hi: u32, +) -> bool { + let style = |m: &std::collections::BTreeMap, k: u32| m.get(&k).and_then(|l| l.style); + after.range(lo..=hi).any(|(k, l)| l.style != style(before, *k)) || before.range(lo..=hi).any(|(k, l)| l.style != style(after, *k)) +} + +/// Turning "Set precision as displayed" on rounds every number constant in the workbook to its +/// format, permanently (Excel warns "Data will permanently lose accuracy"). Formulas are rounded +/// by the recalculation that follows. +pub(crate) fn round_all_constants_as_displayed(wb: &mut Workbook) { + let mut prec = gridcraft_calc::DisplayedPrecision::new(); + for si in 0..wb.sheets.len() { + let Some(sh) = wb.sheets.get(si) else { continue }; + let updates = displayed_updates(&mut prec, wb, si, sh.cells.iter().map(|(c, _)| c)); + if updates.is_empty() { + continue; + } + let Some(sh) = wb.sheet_mut(si) else { continue }; + for (c, r) in updates { + if let Some(cell) = sh.cells.get_mut(c) { + cell.value = gridcraft_core::Value::Number(r); + } + } + } +} + +/// The constants among `cells` on sheet `si` whose value the option changes, with their rounded +/// values. A locked constant on a protected sheet keeps its value: protection keeps its content, +/// and rounding it by its format would change the content that the sheet protects. +fn displayed_updates( + prec: &mut gridcraft_calc::DisplayedPrecision, + wb: &Workbook, + si: usize, + cells: impl Iterator, +) -> Vec<(CellRef, f64)> { + let Some(sh) = wb.sheet(si) else { return Vec::new() }; + cells + .filter(|&c| !(sh.is_protected() && wb.styles.get(sh.style_id(c)).protection.locked)) + .filter_map(|c| { + let cell = sh.cell(c)?; + match cell.value { + gridcraft_core::Value::Number(n) if cell.formula.is_none() => { + let r = prec.round(wb, si, c, n); + (r.to_bits() != n.to_bits()).then_some((c, r)) + } + _ => None, + } + }) + .collect() +} /// The most cells a dry run's touch log keeps; a footprint whose log is full may be missing writes /// that kept a cell's value, so a shift is refused then. pub(crate) const TOUCH_LOG_LIMIT: usize = 1_000_000; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b3b515c2e0..aafb0850de 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Options", ["File"], None, - "{} → {calculation: {mode, iterative, maxIterations, maxChange}} for the active workbook (the interface opens File › Options; change settings with their own commands, e.g. formulas.calculationOptions, view.theme, app.language.set)", + "{} → {calculation: {mode, iterative, maxIterations, maxChange, precisionAsDisplayed}} for the active workbook (the interface opens File › Options; change settings with their own commands, e.g. formulas.calculationOptions, view.theme, app.language.set)", always, options ), @@ -230,7 +230,7 @@ fn options(s: &mut Session, _: &Json) -> Result { gridcraft_model::CalcMode::AutomaticExceptTables => "automaticExceptTables", gridcraft_model::CalcMode::Manual => "manual", }; - json!({"mode": mode, "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change}) + json!({"mode": mode, "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change, "precisionAsDisplayed": c.precision_as_displayed}) }); Ok(json!({"calculation": calculation})) } diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index d72f814a18..a62dc46f14 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Calculation Options", ["Formulas", "Calculation"], None, - "{mode?: automatic|automaticExceptTables|manual, iterative?: bool (Enable iterative calculation), maxIterations?: 1–32767 (100), maxChange?: number (0.001)} → the settings. File › Options › Formulas › Calculation options; stored in the workbook.", + "{mode?: automatic|automaticExceptTables|manual, iterative?: bool (Enable iterative calculation), maxIterations?: 1–32767 (100), maxChange?: number (0.001), precisionAsDisplayed?: bool (Set precision as displayed: numbers are stored as their format shows them; turning it on rounds every number constant permanently)} → the settings. File › Options › Formulas › Calculation options; stored in the workbook.", has_doc, calc_options ), @@ -954,14 +954,30 @@ fn calc_options(s: &mut Session, p: &Json) -> Result { if let Some(v) = f64_param(p, "maxChange") { cx.wb.calc.set_max_change(v); } + let precision = bool_param(p, "precisionAsDisplayed"); + if let Some(v) = precision { + cx.wb.calc.precision_as_displayed = v; + if v && !before.precision_as_displayed { + crate::cmd::round_all_constants_as_displayed(&mut cx.wb); + } + } let c = &cx.wb.calc; // Switching to automatic, or changing how circular references are calculated outside // manual mode, recalculates the workbook. let iteration_changed = (c.iterative, c.max_iterations, c.max_change) != (before.iterative, before.max_iterations, before.max_change); - if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) { + // Switching precision as displayed recalculates the workbook, in manual mode too, so the + // values change as soon as it is switched on or off. + let precision_changed = c.precision_as_displayed != before.precision_as_displayed; + if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) || precision_changed { cx.structural = true; } - Ok(json!({"mode": format!("{:?}", c.mode), "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change})) + Ok(json!({ + "mode": format!("{:?}", c.mode), + "iterative": c.iterative, + "maxIterations": c.max_iterations, + "maxChange": c.max_change, + "precisionAsDisplayed": c.precision_as_displayed, + })) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ab443bbe61..b83879c164 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3130,7 +3130,7 @@ fn calculation_options_enable_iterative_calculation() { assert!(!s.doc().unwrap().calc.circular.is_empty()); // Switching it on recalculates the loop. let r = s.execute("formulas.calculationOptions", json!({"iterative": true})).unwrap(); - assert_eq!(r, json!({"mode": "Automatic", "iterative": true, "maxIterations": 100, "maxChange": 0.001})); + assert_eq!(r, json!({"mode": "Automatic", "iterative": true, "maxIterations": 100, "maxChange": 0.001, "precisionAsDisplayed": false})); near(&s, "A1", 10.0); near(&s, "A2", 10.0); assert!(s.doc().unwrap().calc.circular.is_empty()); @@ -4791,6 +4791,180 @@ fn paste_special_validation_moves_relative_references() { assert!(ok(&mut s, "C3", "20")); } +/// "Set precision as displayed" (formulas.calculationOptions `precisionAsDisplayed`). Behaviour +/// observed in Excel through COM with synthetic values: turning it on rounds existing constants +/// and formulas to their formats; constants typed or reformatted while it is on are rounded at +/// once (permanently: a wider format later doesn't bring digits back); General keeps full +/// precision; turning it off restores formulas on recalculation, not constants. +#[test] +fn precision_as_displayed_option() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("cell.set", json!({"cell": "A1", "input": "1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=A1*100"})).unwrap(); + s.execute("cell.set", json!({"cell": "A3", "input": "=7/3"})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "0.333333333333333"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A1", "code": "0.00"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A3", "code": "0"})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A3")), (1.23456, 7.0 / 3.0)); + let r = s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + assert_eq!(r["precisionAsDisplayed"], true); + assert_eq!((num(&s, "A1"), num(&s, "A2"), num(&s, "A3"), num(&s, "A4")), (1.23, 123.0, 2.0, 0.333333333333333)); + let r = s.execute("file.options", json!({})).unwrap(); + assert_eq!(r["calculation"]["precisionAsDisplayed"], true); + // Typed while on: rounded to the cell's format, and dependents read the rounded value. + s.execute("cell.set", json!({"cell": "A1", "input": "4.56789"})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A2")), (4.57, 457.0)); + s.execute("range.setValues", json!({"range": "A1", "values": [[5.43219]]})).unwrap(); + assert_eq!(num(&s, "A1"), 5.43); + // Reformatting while on rounds a constant and a formula at once. + s.execute("cell.set", json!({"cell": "B1", "input": "1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "B2", "input": "=1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "B3", "input": "=B1*100"})).unwrap(); + assert_eq!(num(&s, "B1"), 1.23456); + s.execute("home.numberFormat", json!({"range": "B1:B2", "code": "0.0"})).unwrap(); + assert_eq!((num(&s, "B1"), num(&s, "B2"), num(&s, "B3")), (1.2, 1.2, 120.0)); + // The constant's digits are gone for good; the formula is rounded again from its result. + s.execute("home.numberFormat", json!({"range": "B1:B2", "code": "0.0000"})).unwrap(); + assert_eq!((num(&s, "B1"), num(&s, "B2")), (1.2, 1.2346)); + // Undo brings the unrounded constant back. + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(num(&s, "B1"), 1.23456); + // Saved with the workbook, and applied on recalculation after reopening. + reopen(&mut s); + assert!(s.doc().unwrap().wb.calc.precision_as_displayed); + assert_eq!(num(&s, "A3"), 2.0); + // Off: formulas get their full precision back, constants stay rounded. + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": false})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A3")), (5.43, 7.0 / 3.0)); +} + +/// Reformatting a cell a dynamic array spills into rounds that element as displayed: the cell +/// holds no stored value (the spill lives in `Sheet::spill`), so the edit changes only its +/// style, and the anchor must be recalculated for the element to be rounded. +#[test] +fn precision_as_displayed_rounds_a_reformatted_spill_cell() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("cell.set", json!({"cell": "F1", "input": "=SEQUENCE(3,1,0.123,0.111)"})).unwrap(); + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + s.execute("cell.set", json!({"cell": "G1", "input": "=SUM(F1:F3)"})).unwrap(); + let (f2, f3) = (0.123 + 0.111, 0.123 + 0.111 * 2.0); + assert_eq!((num(&s, "F1"), num(&s, "F2"), num(&s, "F3")), (0.123, f2, f3)); + // Formatting a spill destination (the anchor is not in the edit) rounds just that element. + s.execute("home.numberFormat", json!({"range": "F2", "code": "0.0"})).unwrap(); + assert_eq!((num(&s, "F1"), num(&s, "F2"), num(&s, "F3")), (0.123, 0.2, f3)); + assert_eq!(num(&s, "G1"), 0.123 + 0.2 + f3); + // A range covering anchor and spill, and a whole column, round every element. + s.execute("home.numberFormat", json!({"range": "F:F", "code": "0.00"})).unwrap(); + assert_eq!((num(&s, "F1"), num(&s, "F2"), num(&s, "F3")), (0.12, 0.23, 0.35)); + assert_eq!(num(&s, "G1"), 0.12 + 0.23 + 0.35); + // Formatting a cell that no spill covers changes nothing. + s.execute("home.numberFormat", json!({"range": "F4", "code": "0.0"})).unwrap(); + assert_eq!(num(&s, "F3"), 0.35); +} +#[test] +fn precision_as_displayed_enable_undoes_in_one_step() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("cell.set", json!({"cell": "A1", "input": "1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=A1*100"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A1", "code": "0.00"})).unwrap(); + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A2")), (1.23, 123.0)); + // One undo brings back the constants and the flag together. + s.execute("edit.undo", json!({})).unwrap(); + assert!(!s.doc().unwrap().wb.calc.precision_as_displayed); + assert_eq!((num(&s, "A1"), num(&s, "A2")), (1.23456, 1.23456 * 100.0)); +} + +#[test] +fn precision_as_displayed_applies_in_manual_mode() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("cell.set", json!({"cell": "A1", "input": "1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=A1*100"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A1", "code": "0.00"})).unwrap(); + s.execute("formulas.calculationOptions", json!({"mode": "manual"})).unwrap(); + // Turning it on rounds the values at once, without a calculation. + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A2")), (1.23, 123.0)); + // Turning it off recalculates at once too: the formula reads the rounded constant. + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": false})).unwrap(); + assert_eq!((num(&s, "A1"), num(&s, "A2")), (1.23, 1.23 * 100.0)); +} + +#[test] +fn precision_as_displayed_on_a_protected_sheet_keeps_locked_constants() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("cell.set", json!({"cell": "A1", "input": "1.23456"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=A1*100"})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "1.23456"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A1:B1", "code": "0.00"})).unwrap(); + s.execute("home.lockCell", json!({"range": "B1", "on": false})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + // Turning the option on is not refused: the locked constant keeps its digits, the unlocked + // one is rounded. + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + assert!(s.doc().unwrap().wb.calc.precision_as_displayed); + assert_eq!((num(&s, "A1"), num(&s, "B1"), num(&s, "A2")), (1.23456, 1.23, 1.23456 * 100.0)); + // Reformatting a locked constant, on a sheet that allows formatting, keeps its digits too. + s.execute("review.unprotectSheet", json!({})).unwrap(); + s.execute("review.protectSheet", json!({"formatCells": true})).unwrap(); + s.execute("home.numberFormat", json!({"range": "A1", "code": "0.0"})).unwrap(); + assert_eq!(num(&s, "A1"), 1.23456); +} + +#[test] +fn precision_as_displayed_rounds_a_legacy_array_by_each_cell() { + let mut s = s(); + let num = |s: &Session, a: &str| v(s, a).as_f64().unwrap_or(f64::NAN); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2]]})).unwrap(); + s.execute("home.numberFormat", json!({"range": "B1", "code": "0.00"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "B2", "code": "0.0"})).unwrap(); + s.execute("selection.set", json!({"range": "B1:B2"})).unwrap(); + s.execute("cell.set", json!({"input": "=A1:A2/3", "array": true})).unwrap(); + assert_eq!((num(&s, "B1"), num(&s, "B2")), (1.0 / 3.0, 2.0 / 3.0)); + // Each element takes the format of the cell it lands in. + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + assert_eq!((num(&s, "B1"), num(&s, "B2")), (0.33, 0.7)); +} + +#[test] +fn precision_as_displayed_rounds_numbers_written_to_a_new_sheet() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [4], [7], [3], [5]]})).unwrap(); + // Histogram output on a new sheet, with the option off, keeps full precision. + s.execute("data.analysisToolPak", json!({"tool": "histogram", "range": "Sheet1!A1:A6", "cumulative": true, "newSheet": "Raw"})).unwrap(); + let raw: Vec<(CellRef, f64)> = { + let d = s.doc().unwrap(); + let sh = d.wb.sheet(d.wb.sheet_index("Raw").unwrap()).unwrap(); + sh.cells + .iter() + .filter_map(|(c, cell)| match cell.value { + Value::Number(n) if cell.formula.is_none() => Some((c, n)), + _ => None, + }) + .collect() + }; + s.execute("formulas.calculationOptions", json!({"precisionAsDisplayed": true})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "histogram", "range": "Sheet1!A1:A6", "cumulative": true, "newSheet": "Rounded"})).unwrap(); + let d = s.doc().unwrap(); + let si = d.wb.sheet_index("Rounded").unwrap(); + let sh = d.wb.sheet(si).unwrap(); + let mut prec = gridcraft_calc::DisplayedPrecision::new(); + let mut rounded = 0; + for (c, n) in &raw { + let want = prec.round(&d.wb, si, *c, *n); + assert_eq!(sh.value(*c), Value::Number(want), "{c:?}"); + rounded += usize::from(want != *n); + } + // Cumulative shares of six values are sixths, which the percent format rounds. + assert!(rounded > 0, "the histogram's formatted cells should be rounded"); +} + #[test] fn editing_quote_prefixed_text_keeps_it_text() { let mut s = s(); diff --git a/crates/numfmt/src/lib.rs b/crates/numfmt/src/lib.rs index 52cada2c75..cbb11bc314 100644 --- a/crates/numfmt/src/lib.rs +++ b/crates/numfmt/src/lib.rs @@ -323,6 +323,60 @@ impl NumberFormat { (Formatted { text: out.text, color: sec.color, fill: out.fill, numeric: true }, false) } + /// The number `n` as this format displays it: what Excel stores when "Set precision as + /// displayed" is on. Fixed decimals, percent, thousands scaling (`0.0,,`), scientific and + /// fraction sections round to what they show; the section is picked as for display, so + /// `0.00;(0.0)` keeps one decimal for negatives. Observed in Excel (COM, + /// `Workbook.PrecisionAsDisplayed`), these keep the full value: General, date and time + /// formats (`mm:ss.0` included), text formats and sections without digits (`"x"`, `;;;`). + /// The section is picked by [`NumberFormat::rounding_section`], which ignores conditions. + /// Never returns `-0`. + pub fn round_as_displayed(&self, n: f64) -> f64 { + if self.is_general() || !n.is_finite() { + return n; + } + let Some(sec) = self.rounding_section(n) else { return n }; + if sec.kind != SecKind::Number { + return n; + } + let Some(m) = render::shown_value(sec, n) else { return n }; + if m == 0.0 { + 0.0 + } else if n < 0.0 { + -m + } else { + m + } + } + + /// The section whose digits "Set precision as displayed" rounds `n` by. Observed in Excel + /// (COM), this differs from the section that displays `n`: + /// - Conditions are ignored; the sign picks the section, the first for positives and the + /// second for negatives. `[<1]0.00;0` shows 2.333 as `2` but stores 2.33, and stores -10/3 + /// as -3 although it shows `-3.00`. `[>1]0.0;0.000` stores 1/3 as 0.3. + /// - A format with a condition and a single number section keeps negatives at full value + /// (`[<1]0.00`, `[>=-100]0.0`); with an `@` section added (`[<1]0.00;@`) negatives use the + /// first section, as every format without a condition does. + /// - A completely empty section (no characters, not even a colour) passes to the next one: + /// `0.0;;0.000` stores -2.333 as -2.333, `;0.0` stores 2.333 as 2.3, `;;0.0` too. A section + /// with only a colour or a literal (`0.0;[Red];0.000`, `0.0;" "`) has no digits and keeps + /// the full value. + /// + /// `None` keeps the full value. + fn rounding_section(&self, n: f64) -> Option<&Section> { + let secs = self.num_sections(); + let conditional = secs.iter().any(|s| s.cond.is_some()); + let slot = if n < 0.0 && secs.len() >= 2 { + 1 + } else if n < 0.0 && conditional && self.inner.text_section.is_none() { + return None; + } else { + 0 + }; + let empty = |s: &Section| s.toks.is_empty() && s.color.is_none() && s.cond.is_none(); + secs.get(slot..)?.iter().find(|s| !empty(s)) + } + fn format_text(&self, t: &str) -> Formatted { match self.inner.text_section.and_then(|i| self.inner.sections.get(i)) { Some(sec) => { diff --git a/crates/numfmt/src/render.rs b/crates/numfmt/src/render.rs index a610954c2f..bb7fd1514f 100644 --- a/crates/numfmt/src/render.rs +++ b/crates/numfmt/src/render.rs @@ -230,9 +230,31 @@ fn digit_indices(toks: &[Tok], range: std::ops::Range) -> Vec { range.filter(|&i| matches!(toks.get(i), Some(Tok::Digit(_)))).collect() } -/// Renders a non-negative number through a number section. -pub(crate) fn render_number(sec: &Section, v: f64) -> Out { - let mut x = v.abs(); +/// Where a number section's placeholders are: the decimal point, the exponent, and the digit +/// placeholders before the point (or exponent) and between the point and the exponent. +struct NumberLayout { + point: Option, + exp: Option, + int_idx: Vec, + frac_idx: Vec, +} + +fn number_layout(toks: &[Tok]) -> NumberLayout { + let n = toks.len(); + let point = toks.iter().position(|t| matches!(t, Tok::Point)); + let exp = toks.iter().position(|t| matches!(t, Tok::Exp { .. })); + let int_end = point.or(exp).unwrap_or(n); + let frac_end = exp.unwrap_or(n); + let int_idx = digit_indices(toks, 0..int_end); + let frac_idx = match point { + Some(p) => digit_indices(toks, p + 1..frac_end), + None => Vec::new(), + }; + NumberLayout { point, exp, int_idx, frac_idx } +} + +/// The number a section works on: each `%` multiplies by 100, each scaling comma divides by 1000. +fn scaled(sec: &Section, mut x: f64) -> f64 { // Observed: `%` in a scientific section is only a literal (`#%e+#` shows 123456.789 as // `1%e+5`). if sec.percent > 0 && !sec.exp { @@ -241,6 +263,75 @@ pub(crate) fn render_number(sec: &Section, v: f64) -> Out { if sec.scale > 0 { x /= 1000f64.powi(sec.scale.min(110)); } + x +} + +/// Scientific notation of a non-negative `x` with `int_count` integer and `frac_count` fraction +/// placeholders: the exponent (a multiple of the integer placeholder count, engineering style) +/// and the mantissa's integer and fraction digits. +fn scientific_parts(x: f64, int_count: usize, frac_count: usize) -> (i32, String, String) { + if x == 0.0 { + // Observed: zero shows `0` in every integer placeholder, `#` and `?` too + // (`#.#E+#` gives `0.E+0`, `####.####E+#` gives `0000.E+0`). + return (0, "0".repeat(int_count), "0".repeat(frac_count)); + } + let step = int_count.max(1) as i32; + let (digits, xe) = decimal_digits(x); + let mut e = xe - xe.rem_euclid(step); + let (mut i, mut f) = fixed_from_digits(&digits, xe - e, frac_count); + if i.len() > step as usize { + e += step; + (i, f) = fixed_from_digits(&digits, xe - e, frac_count); + } + (e, i, f) +} + +/// The number a number section shows for a non-negative `v`, as a value: what "Set precision as +/// displayed" stores. `None` when the section shows no digits (`"x"`) or the result isn't finite. +/// It uses the display's own rounding, so 1.005 with `0.00` gives 1.01, and 0.123456 with +/// `0.00%` gives 0.1235 (the nearest double to the decimal shown). +pub(crate) fn shown_value(sec: &Section, v: f64) -> Option { + if !sec.has_digits || !v.is_finite() { + return None; + } + let x = scaled(sec, v.abs()); + if !x.is_finite() { + return None; + } + if x == 0.0 { + return Some(0.0); + } + // `%` and scaling are undone by moving the decimal point in the digits shown, so the result + // is the nearest double to that decimal rather than a product with its own rounding error. + let pct = if sec.exp { 0 } else { sec.percent.min(20) }; + let shift = 3 * sec.scale.clamp(0, 110) - 2 * pct; + let shown = if sec.fraction { + let lay = fraction_layout(&sec.toks)?; + let (whole, num, den) = fraction_parts(&lay, x); + let den = den.max(1) as f64; + (whole * den + num) / den * 10f64.powi(shift) + } else { + let NumberLayout { exp, frac_idx, .. } = number_layout(&sec.toks); + let (e, int_s, frac_s) = match exp { + // Observed: the stored value keeps one digit plus the fraction digits, whatever the + // integer placeholders (`##0.0E+0` stores 123456.789 as 120000 though it shows + // `123.5E+3`; `###.00E+0` keeps three digits). A `%` in a scientific section stores a + // value that matches neither the display nor this rule: left as is. + Some(_) if sec.percent > 0 => return None, + Some(_) => scientific_parts(x, 1, frac_idx.len()), + None => { + let (i, f) = fixed(x, frac_idx.len()); + (0, i, f) + } + }; + format!("0{int_s}.{frac_s}0e{}", i64::from(e) + i64::from(shift)).parse::().ok()? + }; + shown.is_finite().then_some(shown) +} + +/// Renders a non-negative number through a number section. +pub(crate) fn render_number(sec: &Section, v: f64) -> Out { + let mut x = scaled(sec, v.abs()); if !x.is_finite() { x = f64::MAX; } @@ -256,32 +347,10 @@ pub(crate) fn render_number(sec: &Section, v: f64) -> Out { lits = vec![None; n]; render_fraction(sec, x, &mut pieces, &mut lits); } else { - let point = toks.iter().position(|t| matches!(t, Tok::Point)); - let exp = toks.iter().position(|t| matches!(t, Tok::Exp { .. })); - let int_end = point.or(exp).unwrap_or(n); - let frac_end = exp.unwrap_or(n); - let int_idx = digit_indices(toks, 0..int_end); - let frac_idx = match point { - Some(p) => digit_indices(toks, p + 1..frac_end), - None => Vec::new(), - }; + let NumberLayout { point, exp, int_idx, frac_idx } = number_layout(toks); let (int_s, frac_s) = if let Some(e_at) = exp { let exp_idx = digit_indices(toks, e_at + 1..n); - let step = int_idx.len().max(1) as i32; - let (mut e, int_s, frac_s) = if x == 0.0 { - // Observed: zero shows `0` in every integer placeholder, `#` and `?` too - // (`#.#E+#` gives `0.E+0`, `####.####E+#` gives `0000.E+0`). - (0i32, "0".repeat(int_idx.len()), "0".repeat(frac_idx.len())) - } else { - let (digits, xe) = decimal_digits(x); - let mut e = xe - xe.rem_euclid(step); - let (mut i, mut f) = fixed_from_digits(&digits, xe - e, frac_idx.len()); - if i.len() > step as usize { - e += step; - (i, f) = fixed_from_digits(&digits, xe - e, frac_idx.len()); - } - (e, i, f) - }; + let (mut e, int_s, frac_s) = scientific_parts(x, int_idx.len(), frac_idx.len()); // Exponent text. let (upper, plus) = match toks.get(e_at) { Some(Tok::Exp { upper, plus }) => (*upper, *plus), @@ -424,19 +493,23 @@ fn blank_range(toks: &[Tok], range: std::ops::Range, spaces: bool, pieces } } -/// A fraction section is `[whole] [sep] num [lit] / [lit] den`: the numerator is the run of -/// placeholders ending at the last one before the bar, the whole part is every placeholder -/// before it (literals between them stay), `sep` the literals between the two parts. -/// -/// Observed Excel behaviour: when the whole part shows no digit its separator disappears (or -/// becomes spaces when the whole part or the numerator has a `?`); when the fraction is zero and -/// the numerator has no `0` placeholder, the separator, numerator, bar and denominator disappear -/// (or become spaces when any part has a `?`) and the whole part shows at least `0`. -fn render_fraction(sec: &Section, x: f64, pieces: &mut [String], lits: &mut [Option]) { - let toks = &sec.toks; +/// Where a fraction section's parts are (see [`render_fraction`]). +struct FractionLayout { + slash: usize, + num_start: usize, + whole_idx: Vec, + num_idx: Vec, + sep_start: usize, + fixed_den: Option, + den_start: usize, + den_end: usize, + den_idx: Vec, +} + +fn fraction_layout(toks: &[Tok]) -> Option { let is_digit = |i: usize| matches!(toks.get(i), Some(Tok::Digit(_))); - let Some(slash) = toks.iter().position(|t| matches!(t, Tok::Slash)) else { return }; - let Some(num_last) = (0..slash).rev().find(|&i| is_digit(i)) else { return }; + let slash = toks.iter().position(|t| matches!(t, Tok::Slash))?; + let num_last = (0..slash).rev().find(|&i| is_digit(i))?; let mut num_start = num_last; while num_start > 0 && is_digit(num_start - 1) { num_start -= 1; @@ -463,16 +536,20 @@ fn render_fraction(sec: &Section, x: f64, pieces: &mut [String], lits: &mut [Opt } } let den_idx = digit_indices(toks, den_start..den_end); - let has_q = |idx: &[usize]| idx.iter().any(|&i| toks.get(i) == Some(&Tok::Digit('?'))); - let has_whole = !whole_idx.is_empty(); + Some(FractionLayout { slash, num_start, whole_idx, num_idx, sep_start, fixed_den, den_start, den_end, den_idx }) +} + +/// The whole part, numerator and denominator a fraction section shows for a non-negative `x`. +fn fraction_parts(lay: &FractionLayout, x: f64) -> (f64, f64, u64) { + let has_whole = !lay.whole_idx.is_empty(); let (mut whole, f) = if has_whole { (x.floor(), x - x.floor()) } else { (0.0, x) }; // Without a whole part the numerator carries the whole value and can pass u64::MAX, so it // stays an f64 (a float-to-u64 cast saturates). - let (mut num, den): (f64, u64) = match fixed_den { + let (mut num, den): (f64, u64) = match lay.fixed_den { Some(d) => ((f * d as f64).round(), d), None if f >= 1e15 => (f.round(), 1), None => { - let digits = den_idx.len().clamp(1, 7) as u32; + let digits = lay.den_idx.len().clamp(1, 7) as u32; let (n, d) = approximate(f, 10u64.pow(digits) - 1); (n as f64, d) } @@ -483,6 +560,24 @@ fn render_fraction(sec: &Section, x: f64, pieces: &mut [String], lits: &mut [Opt whole += (n / den) as f64; num = (n % den) as f64; } + (whole, num, den) +} + +/// A fraction section is `[whole] [sep] num [lit] / [lit] den`: the numerator is the run of +/// placeholders ending at the last one before the bar, the whole part is every placeholder +/// before it (literals between them stay), `sep` the literals between the two parts. +/// +/// Observed Excel behaviour: when the whole part shows no digit its separator disappears (or +/// becomes spaces when the whole part or the numerator has a `?`); when the fraction is zero and +/// the numerator has no `0` placeholder, the separator, numerator, bar and denominator disappear +/// (or become spaces when any part has a `?`) and the whole part shows at least `0`. +fn render_fraction(sec: &Section, x: f64, pieces: &mut [String], lits: &mut [Option]) { + let toks = &sec.toks; + let Some(lay) = fraction_layout(toks) else { return }; + let (whole, num, den) = fraction_parts(&lay, x); + let FractionLayout { slash, num_start, whole_idx, num_idx, sep_start, fixed_den, den_start, den_end, den_idx } = lay; + let has_q = |idx: &[usize]| idx.iter().any(|&i| toks.get(i) == Some(&Tok::Digit('?'))); + let has_whole = !whole_idx.is_empty(); let whole_s = if whole >= 1.0 { fixed(whole, 0).0 } else { String::new() }; let num_zero_ph = num_idx.iter().any(|&i| toks.get(i) == Some(&Tok::Digit('0'))); if has_whole && num == 0.0 && !num_zero_ph { diff --git a/crates/numfmt/src/tests.rs b/crates/numfmt/src/tests.rs index 4b2ee089d9..b2709b3209 100644 --- a/crates/numfmt/src/tests.rs +++ b/crates/numfmt/src/tests.rs @@ -901,3 +901,120 @@ fn closed_brackets_still_hold_their_semicolons() { assert_eq!(f("0\\[0", 5.0), "0[5"); assert_eq!(f("\"[\"0;0", 5.0), "[5"); } + +/// "Set precision as displayed": the value each format stores. Expected values observed in Excel +/// (COM, `Workbook.PrecisionAsDisplayed = True`) with synthetic values. +#[test] +fn round_as_displayed_matches_excel() { + let r = |code: &str, n: f64| NumberFormat::parse(code).round_as_displayed(n); + let cases: &[(&str, f64, f64)] = &[ + ("0", 527.91, 528.0), + ("0", 2.5, 3.0), + ("0", -2.5, -3.0), + ("0.00", 1.005, 1.01), + ("0.00", 1.23456, 1.23), + ("#.##", 1.23456, 1.23), + ("#.##", 1.2, 1.2), + ("?.??", 1.23456, 1.23), + ("0.0??", 1.23456, 1.235), + ("0%", 0.123456, 0.12), + ("0.0%", 0.123456, 0.123), + ("0.00%", 0.123456, 0.1235), + ("$#,##0.00", 1234.5678, 1234.57), + ("#,##0", 1234.5678, 1235.0), + ("0.0,,", 1234567.891, 1200000.0), + ("#,##0,", 1234567.891, 1235000.0), + ("0.0,", 1234567.891, 1234600.0), + ("# ?/?", 0.3333333, 1.0 / 3.0), + ("# ??/??", 0.3333333, 1.0 / 3.0), + ("# ?/8", 0.3, 0.25), + ("# ?/4", 2.71829, 2.75), + ("?/?", 0.123, 0.125), + ("0.00E+00", 123456.789, 123000.0), + ("##0.0E+0", 123456.789, 120000.0), + ("0.0E+0", 0.000123456, 0.00012), + ("##0.E+0", 98765.4, 100000.0), + ("###.00E+0", 98765.4, 98800.0), + ("000.0E+0", 0.0123456, 0.012), + ("0.00E+0\" u\"", 98765.4, 98800.0), + ("0.0%E+0", 12345.0, 12345.0), + ("0.00;(0.00)", -1.23456, -1.23), + ("0.00;(0.0)", -1.23456, -1.2), + ("0.0 \"kg\"", 1.23456, 1.2), + ("0.00;-0.00;\"zero\"", 0.001, 0.0), + ("0.00_);(0.00)", 1.23456, 1.23), + ("#,##0.0_);[Red](#,##0.0)", 2.345, 2.3), + // Kept at full precision. + ("General", 1.0 / 3.0, 1.0 / 3.0), + ("m/d/yyyy", 45000.75, 45000.75), + ("h:mm", 45000.123456, 45000.123456), + ("h:mm:ss", 45000.123456, 45000.123456), + ("[h]:mm", 1.2345678, 1.2345678), + ("mm:ss.0", 0.0001234567, 0.0001234567), + ("d", 45000.6, 45000.6), + ("@", 1.23456, 1.23456), + ("\"x\"", 1.23456, 1.23456), + (";;;", 1.23456, 1.23456), + // Conditions are ignored: the sign picks the section (first for positives, second for + // negatives), whatever section displays the number. + ("[<1]0.00;0", 1.0 / 3.0, 0.33), + ("[<1]0.00;0", 2.0 + 1.0 / 3.0, 2.33), + ("[<1]0.00;0", 12345.678, 12345.68), + ("[<1]0.00;0", -10.0 / 3.0, -3.0), + ("[<1]0.00;0", -1.0 / 3.0, 0.0), + ("[>1]0.0;0.000", 1.0 / 3.0, 0.3), + ("[>1]0.0;0.000", -10.0 / 3.0, -3.333), + ("[>=100]0;0.000", 2.0 + 1.0 / 3.0, 2.0), + ("[>=100]0;0.000", -200.0 - 1.0 / 3.0, -200.333), + ("[<0]0.0;0.000", -2.0 - 1.0 / 3.0, -2.333), + ("[>100]0;[<-100]0.0;0.000", -2.0 - 1.0 / 3.0, -2.3), + ("[<=-1]0.0;[>=1]0.000;0.00000", -2.0 - 1.0 / 3.0, -2.333), + ("0.0;[<-5]0.000", -2.0 - 1.0 / 3.0, -2.333), + ("[<1]0.00%;0", 2.0 + 1.0 / 3.0, 2.3333), + ("[<1]0.00;0.0,", -2345.6789, -2300.0), + ("[<1]0.0E+0;0", 1.0 / 3.0, 0.33), + ("[<1]# ?/?;0", 2.3, 16.0 / 7.0), + ("[<1]0.00;?/8", -2.0 - 1.0 / 3.0, -2.375), + ("[<1]0.00;0.0;0.000;@", -2.0 - 1.0 / 3.0, -2.3), + ("[<1]\"x\";0.0", 2.0 + 1.0 / 3.0, 2.0 + 1.0 / 3.0), + ("[<1]\"x\";0.0", -2.0 - 1.0 / 3.0, -2.3), + ("[<1]m/d/yyyy;0.0", 2.0 + 1.0 / 3.0, 2.0 + 1.0 / 3.0), + ("[<1]0.0;m/d/yyyy", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + // One section with a condition: negatives keep the full value, unless an `@` section + // follows (then the first section applies, as without a condition). + ("[<1]0.00", 2.0 + 1.0 / 3.0, 2.33), + ("[<1]0.00", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("[>=-100]0.0", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("[<1]0.00;@", -2.0 - 1.0 / 3.0, -2.33), + ("[<1]0.0%;@", -2.0 - 1.0 / 3.0, -2.333), + ("0.00;@", -2.0 - 1.0 / 3.0, -2.33), + // A completely empty section passes to the next; a colour or a literal doesn't. + ("0.0;;0.000", -2.0 - 1.0 / 3.0, -2.333), + ("[<1]0.0;;0.000", -2.0 - 1.0 / 3.0, -2.333), + ("[<1]0.0;;0.0%", -2.0 - 1.0 / 3.0, -2.333), + (";0.0", 2.0 + 1.0 / 3.0, 2.3), + (";;0.0", 2.0 + 1.0 / 3.0, 2.3), + (";;0.0", -2.0 - 1.0 / 3.0, -2.3), + ("0.0;;", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("0.0;;@", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("[<1]0.00;", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("0.0;[Red];0.000", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("[<1]0.0;\" \";0.000", -2.0 - 1.0 / 3.0, -2.0 - 1.0 / 3.0), + ("[<1];0.0;0.00", 2.0 + 1.0 / 3.0, 2.0 + 1.0 / 3.0), + ]; + for &(code, n, want) in cases { + assert_eq!(r(code, n), want, "{code} with {n}"); + } + // A negative that rounds to zero stores 0, not -0. + let z = r("0.00", -0.004); + assert!(z == 0.0 && z.is_sign_positive()); + // Non-finite and extreme inputs come back unchanged or finite, never a panic. + assert!(r("0.00", f64::NAN).is_nan()); + assert_eq!(r("0.00", f64::INFINITY), f64::INFINITY); + assert_eq!(r("0", 1e300 * 10.0), 1e301); + assert_eq!(r("0.0,,,,,,,,,,", 1.234e35), 1.234e35); + assert_eq!(r("0.000000000000000000000000000000", 1.0 / 3.0), 0.333333333333333); + assert_eq!(r("0%%%%%%%%%%%%%%%%%%%%%%%%", f64::MAX), f64::MAX); + assert_eq!(r("0", f64::MAX), f64::MAX); + assert_eq!(r("0.0E+0", f64::MIN_POSITIVE), 2.2e-308); +} diff --git a/docs/function-parity.md b/docs/function-parity.md index 97bd5401a0..87081e4603 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -89,7 +89,8 @@ This improves series preparation; it does not change the model-fitting or season | YEARFRAC basis 0, February-end start to day 31 | done: Excel 16.0 returns 31/360 for `YEARFRAC(2021-02-28,2021-03-31,0)` (0.08611111111111111); regression also covers leap day and reversed dates | | 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. A LAMBDA that calls itself more than 140 times, or a formula nested past the depth limit, gives `#NUM!` (the target app allows deeper recursion, #1581). Calling a defined name that holds an error value gives that error, not `#NAME?` | -| 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!`. Set in File › Options › Formulas (Enable iterative calculation, Maximum Iterations 1 to 32767, Maximum Change 0 or more; the two fields are disabled while iteration is off). Differences: GridCraft recalculates on open, so a loop that never settles (`=A1+1`) advances again each time the file is opened +| Set precision as displayed | done: with the option on (`formulas.calculationOptions` `{precisionAsDisplayed}`, read and saved as `` and the `.xls` CalcPrecision record), a formula result, each element of a spill, and a number typed or reformatted are stored as the cell's number format shows them, and other formulas read the rounded value. Fixed decimals, percent, thousands scaling (`0.0,,`), fractions and scientific formats round; General, date and time, text and digitless formats keep the full value, as observed in Excel. Conditions don't pick the section that rounds: the sign does, the first section for positives and the second for negatives, so `[<1]0.00;0` stores 2+1/3 as 2.33 though it shows `2`, and -10/3 as -3; with a condition and a single number section, negatives keep the full value; a completely empty section (`0.0;;0.000`) passes to the next. Turning it on rounds every number constant (permanently); turning it off restores formulas only. Differences: Excel also rounds General constants it shows in scientific notation when the option is turned on (GridCraft leaves General alone); a `%` inside a scientific format is left unrounded; no Options dialog checkbox yet (command only) | +| 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!`. Set in File › Options › Formulas (Enable iterative calculation, Maximum Iterations 1 to 32767, Maximum Change 0 or more; the two fields are disabled while iteration is off). Differences: GridCraft recalculates on open, so a loop that never settles (`=A1+1`) advances again each time the file is opened | | 15-significant-digit comparison semantics | done (#57): `=0.1+0.2=0.3` is TRUE, and MATCH and COUNTIF compare the same way. Arithmetic keeps full precision, as Excel does — `=(0.1+0.2)-0.3` is 5.55E-17 | | IMSQRT and the other IM* functions against Excel's text | IMSQRT follows Excel's polar route, so a negative real gives Excel's stray real part: `IMSQRT("-4")` is `1.22514845490862E-16+2i` (checked in Excel 16.0 on 79 inputs). Differences kept: IMSQRT of a number with a part above about 1E154 or below about 1E-155 gives the exact root (Excel gives `#NUM!` or 0); IMPOWER, IMEXP, IMSIN, IMCOS, IMSINH and IMCOSH keep exact results where Excel shows the same kind of noise (`IMPOWER("-4",2)` is `16-3.92047505570758E-15i`) or different trailing digits near multiples of pi/2; IMCSC and IMCSCH differ by one unit in the 15th digit; IMARGUMENT returns 16–17 digits where Excel returns 15; the text of IM* and COMPLEX results differs for some magnitudes (Excel writes `COMPLEX(1E-10,1)` as `0.0000000001+i` but `COMPLEX(0.000000123456789012345,1)` as `1.23456789012345E-07+i`, and an integer past 15 digits rounded and zero-padded) | | MOD quotient limit | done: Excel 16.0 returns `#NUM!` when `ABS(number/divisor) >= 1.1259E12`; lower quotients retain the remainder | @@ -171,6 +172,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | 2026-10-14 | minor | MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP and LOOKUP compare numbers exactly in every match and search mode, as Excel 365 does: `MATCH(0.1+0.2,{0.3},0)` is `#N/A` and 0.3 sorts below 0.30000000000000004 in approximate and binary search. `=`, SWITCH and the criteria functions (COUNTIF(S), SUMIF(S), AVERAGEIF(S), MAXIFS…) keep comparing at 15 significant digits, also as observed | | 2026-10-14 | minor | Analysis ToolPak value arguments (EOMONTH, WORKDAY, YEARFRAC, COUPDAYS, DISC, BIN2DEC, IM* and the rest, observed in Excel 365) give `#VALUE!` for a multi-cell reference instead of lifting it | | 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) | +| 2026-10-14 | minor | Set precision as displayed: results, spills and typed or reformatted numbers are stored as their format shows them when the option is on (#1343) | | 2026-10-14 | minor | Bounded references up to 1,048,576 cells (`D3:AZ400`) keep their full shape instead of stopping at the used range, so `SUMPRODUCT(D3:AZ400*B3:B400,(A3:A400=x)*(D1:AZ1=y))` broadcasts like Excel and `ROWS`, `COUNTBLANK` and `--(r="")` count the blanks; references that run to the edge of the sheet (`A:A`) still stop at the used range (#1010) | | 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) | From 21b64df0fe8c5cee99aa13dee578954a8c03114b Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:24:59 -0600 Subject: [PATCH 31/68] Paste of a whole-column or whole-row copy no longer aborts the app (#2018) * Paste: whole-column paste and validation without per-cell blowup edit.paste of a whole-column or whole-row copy walked every cell of the copied block (up to the whole sheet) and, for each one, re-cut every validation rule and pushed a one-cell rule. Over a 2M-cell block that is quadratic and the fuzz soak aborted on 34-68 GB allocations. - Paste visits only cells that hold something in the source or the destination; blank onto blank changes nothing (and with an operation stays blank, as in Excel, instead of becoming 0). - Validation pastes as ranges: the pasted rectangle is cut once out of the destination's rules and each source rule comes along as one rule over its translated parts (Skip Blanks or not, as Excel does). - Whole columns and rows paste whole, so destination content further down the columns is replaced, as in Excel. - A paste that does not fit on the sheet is refused, as Excel does, instead of pasting part of the block (whole columns below row 1, whole rows right of column A, a whole column transposed, a block at XFD). - Paste Link, the one paste that writes every cell, is capped at 1,048,576 cells; tiled validation at 100,000 ranges. Co-Authored-By: Claude Sonnet 5.5 * Paste: visit destination cells once per paste, add link, transpose and tiling tests Co-Authored-By: Claude Sonnet 5.5 * Paste: visit link-only cells so a cut keeps their hyperlink * Paste validation: Skip Blanks keeps the destination rule under a blank source cell with no rule * Paste validation: Skip Blanks collects clearing cuts only when a rule is under the paste, merges them into runs, and limits only generated areas * Paste validation: annotate the clearing cut list * Qualify paste validation context type * Fix paste-special clippy warnings * engine: batch validation range cuts * Fix range type inference * Annotate validation range index type * Avoid shadowing test session helper * Keep validation rows after the final cut --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/cmd/data/validation.rs | 80 ++- crates/engine/src/cmd/edit/paste_special.rs | 636 ++++++++++++-------- crates/engine/src/tests.rs | 230 +++++++ 3 files changed, 693 insertions(+), 253 deletions(-) diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs index 2217a372a7..e02ef06b37 100644 --- a/crates/engine/src/cmd/data/validation.rs +++ b/crates/engine/src/cmd/data/validation.rs @@ -18,21 +18,71 @@ fn op_param(s: Option<&str>) -> CfOperator { } } -/// `r` minus `cut`, as up to four non-overlapping rectangles. -fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec { - let Some(i) = r.intersection(cut) else { return vec![r] }; - let mut out = Vec::new(); - if i.start.row > r.start.row { - out.push(RangeRef::new(r.start, CellRef::new(i.start.row - 1, r.end.col))); +/// Removes a set of cuts from one validation range in a row sweep, updating the result once +/// instead of fragmenting it again for every cut. +fn subtract_ranges(r: RangeRef, cuts: &[RangeRef]) -> Vec { + let mut events = std::collections::BTreeMap::>::new(); + for cut in cuts { + let Some(i) = r.intersection(cut) else { continue }; + let columns = (i.start.col, i.end.col); + events.entry(u64::from(i.start.row)).or_default().push((columns, true)); + events.entry(u64::from(i.end.row) + 1).or_default().push((columns, false)); } - if i.end.row < r.end.row { - out.push(RangeRef::new(CellRef::new(i.end.row + 1, r.start.col), r.end)); + if events.is_empty() { + return vec![r]; } - if i.start.col > r.start.col { - out.push(RangeRef::new(CellRef::new(i.start.row, r.start.col), CellRef::new(i.end.row, i.start.col - 1))); - } - if i.end.col < r.end.col { - out.push(RangeRef::new(CellRef::new(i.start.row, i.end.col + 1), CellRef::new(i.end.row, r.end.col))); + events.entry(u64::from(r.end.row) + 1).or_default(); + + let mut active = std::collections::BTreeMap::<(u32, u32), usize>::new(); + let mut out: Vec = Vec::new(); + let mut last_by_columns = std::collections::BTreeMap::<(u32, u32), usize>::new(); + let mut previous_row = u64::from(r.start.row); + for (row, changes) in events { + if previous_row < row { + let start_row = previous_row as u32; + let end_row = (row - 1).min(u64::from(r.end.row)) as u32; + let mut covered = Vec::<(u32, u32)>::new(); + for &(start, end) in active.keys() { + match covered.last_mut() { + Some(last) if start <= last.1.saturating_add(1) => last.1 = last.1.max(end), + _ => covered.push((start, end)), + } + } + let mut next_col = u64::from(r.start.col); + let mut remaining = Vec::new(); + for (start, end) in covered { + if next_col < u64::from(start) { + remaining.push((next_col as u32, start - 1)); + } + next_col = u64::from(end) + 1; + } + if next_col <= u64::from(r.end.col) { + remaining.push((next_col as u32, r.end.col)); + } + for (start_col, end_col) in remaining { + let columns = (start_col, end_col); + if let Some(&index) = last_by_columns.get(&columns) + && out[index].end.row.saturating_add(1) == start_row + { + out[index].end.row = end_row; + } else { + let index = out.len(); + out.push(RangeRef::new(CellRef::new(start_row, start_col), CellRef::new(end_row, end_col))); + last_by_columns.insert(columns, index); + } + } + } + for (columns, add) in changes { + if add { + *active.entry(columns).or_default() += 1; + } else if let Some(count) = active.get_mut(&columns) { + *count -= 1; + if *count == 0 { + active.remove(&columns); + } + } + } + previous_row = row; } out } @@ -43,9 +93,7 @@ fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec { pub(in super::super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { for dv in validations.iter_mut() { let before = RangeRef::top_left(&dv.ranges); - for cut in cuts { - dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); - } + dv.ranges = dv.ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect(); if let (Some(from), Some(to)) = (before, RangeRef::top_left(&dv.ranges)) { dv.f1 = move_rule_formula(&dv.f1, from, to); dv.f2 = dv.f2.take().map(|f| move_rule_formula(&f, from, to)); diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index 352c8e2011..ab662642aa 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -4,74 +4,7 @@ use super::{ target_sheet, }; -fn tiled_cells(rows: u32, cols: u32, tiles_r: u32, tiles_c: u32) -> impl Iterator + Clone { - (0..tiles_r).flat_map(move |tr| (0..tiles_c).flat_map(move |tc| (0..rows).flat_map(move |r| (0..cols).map(move |c| (tr, tc, r, c))))) -} - -fn apply_operation(op: &str, old: &Cell, new: &mut Cell) { - let operand = new.value.clone(); - if let (Ok(x), Ok(y)) = (old.value.to_number(), operand.to_number()) - && (old.value.is_number() || old.value.is_empty() || old.value.is_text()) - && (operand.is_number() || operand.is_empty()) - { - new.value = match op { - "add" => Value::number(x + y), - "subtract" => Value::number(x - y), - "multiply" => Value::number(x * y), - "divide" if y == 0.0 => Value::Error(gridcraft_core::CellError::Div0), - "divide" => Value::number(x / y), - _ => operand.clone(), - }; - } else if (old.value.is_text() || old.value.is_error()) && (operand.is_number() || operand.is_empty()) { - new.value = old.value.clone(); - } - if let Some(formula) = &old.formula - && let Ok(y) = operand.to_number() - && (operand.is_number() || operand.is_empty()) - && let Some(symbol) = operation_symbol(op) - { - let text = format!("=({}){symbol}{}", formula.text, gridcraft_core::number_to_text(y)); - new.formula = Some(std::sync::Arc::new(Formula::new(&text))); - new.value = Value::Empty; - } -} - -fn operation_symbol(op: &str) -> Option { - match op { - "add" => Some('+'), - "subtract" => Some('-'), - "multiply" => Some('*'), - "divide" => Some('/'), - _ => None, - } -} - -fn copy_merges( - cx: &mut crate::cmd::Ctx, - dest_sheet: usize, - src_sheet: &gridcraft_model::Sheet, - src: RangeRef, - at: CellRef, - what: What, - transpose: bool, -) -> Result<()> { - if !matches!(what, What::All | What::Formats) || transpose { - return Ok(()); - } - let merges: Vec = src_sheet.merges.iter().filter(|merge| src.contains_range(merge)).copied().collect(); - for merge in merges { - let row_offset = at.row as i64 - src.start.row as i64; - let col_offset = at.col as i64 - src.start.col as i64; - if let (Some(start), Some(end)) = (merge.start.offset(row_offset, col_offset), merge.end.offset(row_offset, col_offset)) { - let moved = RangeRef::new(start, end); - let sheet = cx.sheet_mut(dest_sheet)?; - sheet.merges.retain(|existing| !existing.intersects(&moved)); - sheet.merges.push(moved); - } - } - Ok(()) -} - +#[allow(clippy::cognitive_complexity)] // The command applies the selected paste mode in one atomic edit. pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) }; let what = match str_param(p, "what").unwrap_or("all") { @@ -97,7 +30,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let dest_sheet = target_sheet(s, p)?; let sel = s.doc()?.selection.current(); let at = cell_param_on(s, p, "at", dest_sheet)?.unwrap_or(sel.start); - let src = clip.range; + // Whole columns or rows paste whole (the copy keeps only their used part as its text), so + // what the destination columns hold further down is replaced too, as in Excel. The cells are + // visited sparsely below, so this costs what the columns hold, not 1,048,576 rows. + let whole = clip.areas.is_empty() && (clip.selected.is_full_cols() || clip.selected.is_full_rows()) && clip.selected.contains_range(&clip.range); + let src = if whole { clip.selected } else { clip.range }; let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) }; // Tile the copy over a larger destination that is a multiple of its size. let tile = sel.height() % h == 0 @@ -108,17 +45,25 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { && !sel.is_full_rows() && sel.count() <= 4_000_000; let (tiles_r, tiles_c) = if tile { (sel.height() / h, sel.width() / w) } else { (1, 1) }; + // Excel refuses a paste that would run off the sheet (whole columns pasted below row 1, whole + // rows right of column A, a whole column transposed) instead of pasting part of it. + if at.offset(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1).is_none() { + return Err(EngineError::Other("The copied cells don't fit here: paste them where the whole copied area fits on the sheet.".into())); + } + // Paste Link writes a formula into every cell, blank ones included, so it is the one paste + // whose work grows with the area rather than with what the source holds. + let link_src = clip.range; + if link && link_src.count().saturating_mul(u64::from(tiles_r) * u64::from(tiles_c)) > MAX_PASTE_LINK_CELLS { + return Err(EngineError::Other("Too many cells to paste as links at once.".into())); + } let same_doc = s.doc()?.uid == clip.doc_uid; let cut_move = clip.cut && same_doc && what == What::All; let src_wb = clip.wb.clone(); let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) }; let src_sheet_name = src_sheet.name.clone(); - if cut_move && at.offset((tiles_r * h).saturating_sub(1) as i64, (tiles_c * w).saturating_sub(1) as i64).is_none() { - // Check the whole footprint before the source is emptied, so a move that overflows the grid loses nothing. - return Err(EngineError::Other("The cut area doesn't fit at this position; nothing was moved.".into())); - } edit(s, |cx| { // Styles from another workbook must be re-interned. + let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default(); let mut style_map = std::collections::HashMap::new(); let mut map_style = |id: StyleId, wb: &mut gridcraft_model::Workbook| -> StyleId { if same_doc { @@ -126,7 +71,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } *style_map.entry(id).or_insert_with(|| wb.styles.intern(src_wb.styles.get(id).clone())) }; - let mut moved_formulas = Vec::new(); + let mut moved_formulas = std::collections::BTreeMap::new(); let mut moved_pictures = std::collections::BTreeMap::new(); if cut_move { // Remove the source first (contents and formats), and fix references to it. @@ -143,190 +88,281 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { for (c, _) in &taken { cx.touch(clip.sheet, *c); } - moved_formulas = taken; + moved_formulas = taken.into_iter().collect(); } - let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default(); - for (tr, tc, r, c) in tiled_cells(src.height(), src.width(), tiles_r, tiles_c) { - let sc = CellRef::new(src.start.row + r, src.start.col + c); - let (dr, dc) = if transpose { (c, r) } else { (r, c) }; - let Some(dest) = at.offset((tr * h + dr) as i64, (tc * w + dc) as i64) else { continue }; - let src_cell = if cut_move { moved_formulas.iter().find(|(k, _)| *k == sc).map(|(_, v)| v.clone()) } else { src_sheet.cell(sc).cloned() }; - let src_val = src_sheet.value(sc); - let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned(); - if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none() && x.py.is_none()) { - continue; - } - let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default(); - let old_picture = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell_pictures.get(&dest)).cloned(); - let mut new_picture = old_picture.clone(); - let mut new = old.clone(); - let shift = |cell: &Cell| -> Option> { - let f = cell.formula.as_ref()?; - let e = f.expr()?; - if cut_move { - // A moved formula still reads cells on its original sheet. Qualify - // those references before the workbook-wide move adjustment below. - let e = if dest_sheet != clip.sheet { - e.map(&mut |x| match x { - gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { - r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); - gridcraft_formula::Expr::Ref(r) - } - other => other, - }) - } else { - e - }; - let mut moved = Formula::from_expr(e); - // The array range moves with its formula. - let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); - moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?))); - moved.dynamic = f.dynamic; - return Some(std::sync::Arc::new(moved)); - } - let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); - Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) })) - }; - // A Python cell's code travels with it. Cut to another sheet, it keeps reading the - // cells its `xl()` references named on its original sheet, as a moved formula does: - // they are qualified with that sheet before the workbook-wide move adjustment below. - let moved_py = |cell: &Cell| -> Result>> { - let Some(py) = cell.py.clone() else { return Ok(None) }; - if !cut_move || dest_sheet == clip.sheet { - return Ok(Some(py)); - } - let qualified = gridcraft_model::python::rewrite_xl(&py.code, |reference| { - let e = gridcraft_formula::parse(reference).ok()?.map(&mut |x| match x { - gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { - r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); - gridcraft_formula::Expr::Ref(r) - } - other => other, - }); - Some(gridcraft_formula::print(&e)) + // The cells of the copied block that hold something (or that a link reads), as offsets + // inside it. Blank source cells matter only where the destination holds something. + let source_offsets: std::collections::BTreeSet<(u32, u32)> = if link { + (0..link_src.height()).flat_map(|r| (0..link_src.width()).map(move |c| (r, c))).collect() + } else { + let offset = |c: CellRef| (c.row - src.start.row, c.col - src.start.col); + let mut held: std::collections::BTreeSet<(u32, u32)> = src_sheet.cells.iter_range(src).map(|(c, _)| offset(c)).collect(); + let side = + src_sheet.spill.keys().chain(src_sheet.cell_pictures.keys()).chain(src_sheet.comments.keys()).chain(src_sheet.hyperlinks.keys()); + held.extend(side.chain(moved_formulas.keys()).chain(moved_pictures.keys()).filter(|c| src.contains(**c)).map(|c| offset(*c))); + held + }; + let skip_cells = matches!(what, What::Validation | What::ColumnWidths); + // A blank source cell clears (or reformats) a destination cell that holds something, so + // those cells join the visit. One scan of the whole pasted area sorts them by tile. + let mut dest_held: std::collections::BTreeMap<(u32, u32), Vec<(u32, u32)>> = Default::default(); + if !link && !skip_cells { + let pasted = RangeRef::new(at, at.offset_clamped(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1)); + let held = + cx.wb.sheet(dest_sheet).into_iter().flat_map(|sh| { + sh.cells.iter_range(pasted).map(|(c, _)| c).chain(sh.cell_pictures.keys().copied().filter(|c| pasted.contains(*c))) }); - Ok(Some(match qualified { - Some(code) => { - let moved = gridcraft_model::PyCode { code, ..(*py).clone() }; - check_python_fits(&moved, &dest_name, dest)?; - std::sync::Arc::new(moved) + for d in held.collect::>() { + let (dr, dc) = (d.row - at.row, d.col - at.col); + let local = (dr % h, dc % w); + dest_held.entry((dr / h, dc / w)).or_default().push(if transpose { (local.1, local.0) } else { local }); + } + } + let no_cells = std::collections::BTreeSet::new(); + for tr in 0..tiles_r { + for tc in 0..tiles_c { + let merged; + let offsets = match dest_held.get(&(tr, tc)) { + Some(extra) => { + merged = source_offsets.iter().chain(extra).copied().collect::>(); + &merged } - None => py, - })) - }; - if link { - let sheet_prefix = if dest_sheet == clip.sheet && same_doc { - String::new() - } else { - format!("{}!", gridcraft_formula::quote_sheet(&src_sheet_name)) + None if skip_cells => &no_cells, + None => &source_offsets, }; - new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1())))); - new.value = Value::Empty; - new.py = None; - new_picture = None; - } else { - let sc_cell = src_cell.clone().unwrap_or_default(); - match what { - What::All | What::AllExceptBorders => { - new_picture = src_picture.clone(); - new.formula = shift(&sc_cell); - new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; - new.py = moved_py(&sc_cell)?; - let st = map_style(sc_cell.style, &mut cx.wb); - new.style = if what == What::AllExceptBorders { - let borders = cx.wb.styles.get(old.style).borders; - cx.wb.styles.derive(st, |s| s.borders = borders) + for &(r, c) in offsets { + let sc = CellRef::new(src.start.row + r, src.start.col + c); + let (dr, dc) = if transpose { (c, r) } else { (r, c) }; + let Some(dest) = at.offset((tr * h + dr) as i64, (tc * w + dc) as i64) else { continue }; + let src_cell = if cut_move { moved_formulas.get(&sc).cloned() } else { src_sheet.cell(sc).cloned() }; + let src_val = src_sheet.value(sc); + let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned(); + if skip_blanks + && src_picture.is_none() + && src_val.is_empty() + && src_cell.as_ref().is_none_or(|x| x.formula.is_none() && x.py.is_none()) + { + continue; + } + let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default(); + let old_picture = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell_pictures.get(&dest)).cloned(); + let mut new_picture = old_picture.clone(); + let mut new = old.clone(); + let shift = |cell: &Cell| -> Option> { + let f = cell.formula.as_ref()?; + let e = f.expr()?; + if cut_move { + // A moved formula still reads cells on its original sheet. Qualify + // those references before the workbook-wide move adjustment below. + let e = if dest_sheet != clip.sheet { + e.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }) + } else { + e + }; + let mut moved = Formula::from_expr(e); + // The array range moves with its formula. + let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); + moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?))); + moved.dynamic = f.dynamic; + return Some(std::sync::Arc::new(moved)); + } + let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); + Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) })) + }; + let moved_py = |cell: &Cell| -> Result>> { + let Some(py) = cell.py.clone() else { return Ok(None) }; + if !cut_move || dest_sheet == clip.sheet { + return Ok(Some(py)); + } + let qualified = gridcraft_model::python::rewrite_xl(&py.code, |reference| { + let e = gridcraft_formula::parse(reference).ok()?.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }); + Some(gridcraft_formula::print(&e)) + }); + Ok(Some(match qualified { + Some(code) => { + let moved = gridcraft_model::PyCode { code, ..(*py).clone() }; + check_python_fits(&moved, &dest_name, dest)?; + std::sync::Arc::new(moved) + } + None => py, + })) + }; + if link { + let sheet_prefix = if dest_sheet == clip.sheet && same_doc { + String::new() } else { - st + format!("{}!", gridcraft_formula::quote_sheet(&src_sheet_name)) }; - } - What::Formulas | What::FormulasAndNumberFormats => { - new_picture = src_picture.clone(); - new.formula = shift(&sc_cell); - new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; - new.py = moved_py(&sc_cell)?; - if what == What::FormulasAndNumberFormats { - let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); - new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); - } - } - What::Values | What::ValuesAndNumberFormats => { - new_picture = src_picture.clone(); - new.formula = None; + new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1())))); + new.value = Value::Empty; new.py = None; - new.value = src_val.clone(); - if what == What::ValuesAndNumberFormats { - let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); - new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); + new_picture = None; + } else { + let sc_cell = src_cell.clone().unwrap_or_default(); + match what { + What::All | What::AllExceptBorders => { + new_picture = src_picture.clone(); + new.formula = shift(&sc_cell); + new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; + let st = map_style(sc_cell.style, &mut cx.wb); + new.style = if what == What::AllExceptBorders { + let borders = cx.wb.styles.get(old.style).borders; + cx.wb.styles.derive(st, |s| s.borders = borders) + } else { + st + }; + } + What::Formulas | What::FormulasAndNumberFormats => { + new_picture = src_picture.clone(); + new.formula = shift(&sc_cell); + new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; + if what == What::FormulasAndNumberFormats { + let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); + new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); + } + } + What::Values | What::ValuesAndNumberFormats => { + new_picture = src_picture.clone(); + new.formula = None; + new.py = None; + new.value = src_val.clone(); + if what == What::ValuesAndNumberFormats { + let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); + new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); + } + } + What::Formats => new.style = map_style(sc_cell.style, &mut cx.wb), + What::Comments | What::Validation | What::ColumnWidths => {} + } + // Operations combine numbers with what is already there. + if op != "none" + && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) + && new.formula.is_none() + && new.py.is_none() + { + if old_picture.is_some() || new_picture.is_some() { + new_picture = None; + new.value = Value::Error(gridcraft_core::CellError::Value); + } + let a = old.value.clone(); + let b = new.value.clone(); + // Numbers stored as text take part (multiplying by 1 turns them into + // numbers); other text and errors stay as they are. + if let (Ok(x), Ok(y)) = (a.to_number(), b.to_number()) + && (a.is_number() || a.is_empty() || a.is_text()) + && (b.is_number() || b.is_empty()) + { + new.value = match op.as_str() { + "add" => Value::number(x + y), + "subtract" => Value::number(x - y), + "multiply" => Value::number(x * y), + "divide" => { + if y == 0.0 { + Value::Error(gridcraft_core::CellError::Div0) + } else { + Value::number(x / y) + } + } + _ => b.clone(), + }; + } else if (a.is_text() || a.is_error()) && (b.is_number() || b.is_empty()) { + new.value = a; + } + // A formula already there is kept and combined with the pasted number. + if let Some(f) = &old.formula + && let Ok(y) = b.to_number() + && (b.is_number() || b.is_empty()) + && let Some(sym) = match op.as_str() { + "add" => Some('+'), + "subtract" => Some('-'), + "multiply" => Some('*'), + "divide" => Some('/'), + _ => None, + } + { + let text = format!("=({}){sym}{}", f.text, gridcraft_core::number_to_text(y)); + new.formula = Some(std::sync::Arc::new(Formula::new(&text))); + new.value = Value::Empty; + } } } - What::Formats => new.style = map_style(sc_cell.style, &mut cx.wb), - What::Comments | What::Validation | What::ColumnWidths => {} - } - // Operations combine numbers with what is already there. - if op != "none" - && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) - && new.formula.is_none() - && new.py.is_none() - { - if old_picture.is_some() || new_picture.is_some() { - new_picture = None; - new.value = Value::Error(gridcraft_core::CellError::Value); + match what { + What::Comments => { + if let Some(cm) = src_sheet.comments.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); + } + } + What::All => { + if let Some(cm) = src_sheet.comments.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); + } + if let Some(h) = src_sheet.hyperlinks.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.hyperlinks.insert(dest, h); + } + cx.sheet_mut(dest_sheet)?.set_cell(dest, new); + } + _ => cx.sheet_mut(dest_sheet)?.set_cell(dest, new), } - // Numbers stored as text participate; other text and errors stay as they are. - apply_operation(&op, &old, &mut new); + if let Some(picture) = new_picture { + cx.sheet_mut(dest_sheet)?.cell_pictures.insert(dest, picture); + } + cx.touch(dest_sheet, dest); } } - // The copied cell's validation rule replaces whatever rule the destination had. - if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { - let rule = src_sheet.validations.iter().find(|dv| dv.ranges.iter().any(|r| r.contains(sc))).cloned(); - let sh = cx.sheet_mut(dest_sheet)?; - crate::cmd::data::remove_validation_cells(&mut sh.validations, &[RangeRef::new(dest, dest)]); - if let Some(mut dv) = rule { - // Relative references move with the rule, as pasted formulas do. - let first = RangeRef::top_left(&dv.ranges).unwrap_or(sc); - dv.f1 = crate::cmd::data::move_rule_formula(&dv.f1, first, dest); - dv.f2 = dv.f2.map(|f| crate::cmd::data::move_rule_formula(&f, first, dest)); - dv.ranges = vec![RangeRef::new(dest, dest)]; - sh.validations.push(dv); + } + let pasted = RangeRef::new(at, at.offset_clamped(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1)); + if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { + paste_validations(cx, src_sheet, src, dest_sheet, pasted, transpose, skip_blanks)?; + } + if what == What::ColumnWidths { + // Each pasted column takes the width of the column copied to it (transposed, the + // copied rows land in columns and all take the last copied column's width). + let cols = cx.sheet_mut(dest_sheet)?; + for dc in 0..pasted.width() { + let info = if transpose { + (0..src.width()).rev().find_map(|c| src_sheet.cols.get(&(src.start.col + c)).copied()) + } else { + src_sheet.cols.get(&(src.start.col + dc % w)).copied() + }; + if let Some(info) = info { + cols.cols.insert(pasted.start.col + dc, info); } } - match what { - What::Comments => { - if let Some(cm) = src_sheet.comments.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); - } - } - What::ColumnWidths => { - if let Some(info) = src_sheet.cols.get(&sc.col).copied() { - cx.sheet_mut(dest_sheet)?.cols.insert(dest.col, info); - } - } - What::All => { - if let Some(cm) = src_sheet.comments.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); - } - if let Some(h) = src_sheet.hyperlinks.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.hyperlinks.insert(dest, h); - } - cx.sheet_mut(dest_sheet)?.set_cell(dest, new); - } - _ => cx.sheet_mut(dest_sheet)?.set_cell(dest, new), - } - if let Some(picture) = new_picture { - cx.sheet_mut(dest_sheet)?.cell_pictures.insert(dest, picture); - } - cx.touch(dest_sheet, dest); } // Merged areas inside the copied block travel with it. - copy_merges(cx, dest_sheet, src_sheet, src, at, what, transpose)?; + if matches!(what, What::All | What::Formats) && !transpose { + let merges: Vec = src_sheet.merges.iter().filter(|m| src.contains_range(m)).copied().collect(); + for m in merges { + let dr = at.row as i64 - src.start.row as i64; + let dc = at.col as i64 - src.start.col as i64; + if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) { + let nm = RangeRef::new(a, b); + let sh = cx.sheet_mut(dest_sheet)?; + sh.merges.retain(|x| !x.intersects(&nm)); + sh.merges.push(nm); + } + } + } if cut_move { // References elsewhere to the moved block now point to its new place. - let dest_name = cx.wb.sheet(dest_sheet).map(|s| s.name.clone()).unwrap_or_default(); let e = if dest_sheet == clip.sheet { gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col } } else { - gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name, to_row: at.row, to_col: at.col } + gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name.clone(), to_row: at.row, to_col: at.col } }; rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e)?; cx.structural = true; @@ -351,6 +387,132 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { Ok(json!({"pasted": s.doc()?.selection.a1()})) } +/// Most cells one Paste Link writes (it writes a formula into every cell of the copied area, +/// blank ones included). +const MAX_PASTE_LINK_CELLS: u64 = 1_048_576; +/// Most validation ranges one paste adds (a rule covering part of a small block tiled over a huge +/// selection makes one range per tile). +const MAX_PASTE_VALIDATION_RANGES: usize = 100_000; + +/// Pasting validation works on ranges, as Excel stores it: the pasted rectangle is cut out of the +/// destination's rules (cells whose source had no rule end up with none), then each source rule +/// that covers part of the copied block `src` comes along as one rule over the translated parts. +/// `size` is one tile's (height, width) at the destination; `pasted` is all the tiles together. +fn paste_validations( + cx: &mut crate::cmd::Ctx<'_>, + src_sheet: &gridcraft_model::Sheet, + src: RangeRef, + dest_sheet: usize, + pasted: RangeRef, + transpose: bool, + skip_blanks: bool, +) -> Result<()> { + let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) }; + let (tiles_r, tiles_c) = (pasted.height() / h.max(1), pasted.width() / w.max(1)); + let mut rules = Vec::new(); + // Under Skip Blanks the destination keeps its rule below a blank source cell that has none, so + // only the destination of cells that hold something (and of the rules) is cleared. Nothing is + // collected when no destination rule is under the paste. + let mut cleared: Vec = Vec::new(); + let dest_rules = + cx.wb.sheet(dest_sheet).is_some_and(|sh| sh.validations.iter().any(|dv| dv.ranges.iter().any(|r| r.intersection(&pasted).is_some()))); + if skip_blanks && dest_rules { + let mut cells = Vec::new(); + for (sc, cell) in src_sheet.cells.iter_range(src) { + if cell.formula.is_none() && cell.py.is_none() && src_sheet.value(sc).is_empty() { + continue; + } + let (r, c) = (sc.row - src.start.row, sc.col - src.start.col); + let (r, c) = if transpose { (c, r) } else { (r, c) }; + for tr in 0..tiles_r { + for tc in 0..tiles_c { + if let Some(d) = pasted.start.offset(i64::from(tr * h + r), i64::from(tc * w + c)) { + cells.push((d.row, d.col)); + } + } + } + } + // Coalesce populated cells into horizontal runs, then join identical runs in adjacent + // rows. The range limit applies to the cuts, not the number of populated cells. + cells.sort_unstable(); + let mut runs: Vec = Vec::new(); + let mut i = 0; + while i < cells.len() { + let (row, start_col) = cells[i]; + let mut end_col = start_col; + i += 1; + while i < cells.len() && cells[i].0 == row && cells[i].1 <= end_col.saturating_add(1) { + end_col = end_col.max(cells[i].1); + i += 1; + } + runs.push(RangeRef::new(CellRef::new(row, start_col), CellRef::new(row, end_col))); + } + let mut last_run_by_columns = std::collections::BTreeMap::<(u32, u32), usize>::new(); + for run in runs { + let columns = (run.start.col, run.end.col); + if let Some(&index) = last_run_by_columns.get(&columns) + && cleared[index].end.row.saturating_add(1) == run.start.row + { + cleared[index].end.row = run.end.row; + } else { + let index = cleared.len(); + cleared.push(run); + last_run_by_columns.insert(columns, index); + } + } + } + let mut total = 0usize; + for dv in &src_sheet.validations { + let parts: Vec = dv.ranges.iter().filter_map(|r| r.intersection(&src)).collect(); + let Some(first) = dv.ranges.first().map(|r| r.start) else { continue }; + if parts.is_empty() { + continue; + } + let mut ranges = Vec::new(); + if parts.contains(&src) { + ranges.push(pasted); + } else { + total = total.saturating_add(parts.len().saturating_mul(tiles_r as usize).saturating_mul(tiles_c as usize)); + if total > MAX_PASTE_VALIDATION_RANGES { + return Err(EngineError::Other("Too many separate validation areas to paste at once.".into())); + } + for tr in 0..tiles_r { + for tc in 0..tiles_c { + let Some(origin) = pasted.start.offset(i64::from(tr * h), i64::from(tc * w)) else { continue }; + for p in &parts { + let (r0, c0) = (p.start.row - src.start.row, p.start.col - src.start.col); + let (r1, c1) = (p.end.row - src.start.row, p.end.col - src.start.col); + let ((r0, c0), (r1, c1)) = if transpose { ((c0, r0), (c1, r1)) } else { ((r0, c0), (r1, c1)) }; + let Some(a) = origin.offset(i64::from(r0), i64::from(c0)) else { continue }; + let b = origin.offset_clamped(i64::from(r1), i64::from(c1)); + ranges.push(RangeRef::new(a, b)); + } + } + } + } + let Some(anchor) = ranges.first().map(|r| r.start) else { continue }; + let mut rule = dv.clone(); + // Relative references move with the rule, as pasted formulas do: they are written for the + // rule's first cell. + rule.f1 = super::super::data::move_rule_formula(&dv.f1, first, anchor); + rule.f2 = dv.f2.as_ref().map(|f| super::super::data::move_rule_formula(f, first, anchor)); + rule.ranges = ranges; + rules.push(rule); + } + if cleared.len() > MAX_PASTE_VALIDATION_RANGES { + return Err(EngineError::Other("Too many separate validation areas to paste at once.".into())); + } + let sh = cx.sheet_mut(dest_sheet)?; + if skip_blanks { + cleared.extend(rules.iter().flat_map(|r| r.ranges.iter().copied())); + super::super::data::remove_validation_cells(&mut sh.validations, &cleared); + } else { + super::super::data::remove_validation_cells(&mut sh.validations, &[pasted]); + } + sh.validations.extend(rules); + Ok(()) +} + /// Applies a reference adjustment to every cell formula and defined name in the workbook. pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { use gridcraft_formula::adjust::Edit; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b83879c164..02c273e14c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4170,6 +4170,25 @@ fn a_cut_moves_the_sources_notes_hyperlinks_and_merges() { assert!(v(&s, "A1").is_empty() && v(&s, "B1").is_empty()); } +/// A cell that holds only a hyperlink (its content cleared) is still part of the block: a +/// cut must carry the link to the destination instead of dropping it with the source. +#[test] +fn a_cut_carries_a_link_only_cell() { + let mut s = s(); + s.execute("insert.link", json!({"cell": "A1", "target": "https://example.com"})).unwrap(); + let a1 = CellRef::parse("A1").unwrap(); + let sh = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.remove_cell(a1); + assert!(sh.cell(a1).is_none(), "A1 holds only the link"); + s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap(); + s.execute("edit.paste", json!({"at": "D1"})).unwrap(); + + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(!sh.hyperlinks.contains_key(&CellRef::parse("A1").unwrap()), "the link left the source"); + assert!(sh.hyperlinks.contains_key(&CellRef::parse("D1").unwrap()), "the link arrived at the destination"); +} + /// Page Layout ▸ Print Titles: naming one axis must not clear the other. `print_titles` read /// both `rows` and `cols` into `Option`s and assigned both unconditionally, so /// `{"rows":"2:2"}` silently dropped the repeated columns from every printed page. @@ -5014,6 +5033,217 @@ fn csv_as_text_keeps_identifier_columns_as_written() { assert_eq!(crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap(), csv.replace('\n', "\r\n").as_bytes()); } +fn validation_areas(s: &Session) -> Vec { + let sh = s.doc().unwrap().wb.active().unwrap(); + let mut out: Vec = sh.validations.iter().map(|dv| dv.ranges.iter().map(|r| r.a1()).collect::>().join(" ")).collect(); + out.sort(); + out +} + +/// ft-3ir.10.16: pasting whole columns walked every one of their 1,048,576 rows and added one +/// single-cell validation rule per pasted cell, re-cutting every rule each time (the fuzz run +/// aborted on a 34 GB allocation). Validation now pastes as ranges and only cells that hold +/// something are visited. +#[test] +fn whole_column_paste_with_validation_works_on_ranges() { + let mut s = s(); + let ok = |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == true; + s.execute("cell.set", json!({"cell": "C1", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "D1048576", "input": "2"})).unwrap(); + s.execute("cell.set", json!({"cell": "F100", "input": "old"})).unwrap(); + s.execute("data.validation", json!({"range": "C:C", "type": "whole", "operator": "greater", "formula1": "0"})).unwrap(); + s.execute("data.validation", json!({"range": "F:H", "type": "list", "formula1": "\"a,b\""})).unwrap(); + s.execute("edit.copy", json!({"range": "C:D"})).unwrap(); + s.execute("edit.paste", json!({"at": "F1"})).unwrap(); + assert_eq!(v(&s, "F1"), Value::Number(1.0)); + assert_eq!(v(&s, "G1048576"), Value::Number(2.0)); + assert_eq!(v(&s, "F100"), Value::Empty, "the whole column is replaced, below the copied text too"); + // One rule per copied rule, over whole columns; G (D had no rule) has none; H keeps the list. + assert_eq!(validation_areas(&s), ["C:C", "F:F", "H:H"]); + assert!(!ok(&mut s, "F500", "-1")); + assert!(ok(&mut s, "G500", "anything")); + assert!(!ok(&mut s, "H500", "c")); + assert_eq!(s.doc().unwrap().selection.a1(), "F:G"); + // Undo gives the list back over F:H. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(validation_areas(&s), ["C:C", "F:H"]); + assert_eq!(v(&s, "F100"), Value::Text("old".into())); +} + +/// Paste Link of whole columns links the cells the columns hold, wherever they start. +#[test] +fn paste_link_of_whole_columns_links_the_used_rows() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "C5", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C6", "input": "2"})).unwrap(); + s.execute("edit.copy", json!({"range": "C:C"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "link": true, "at": "F1"})).unwrap(); + assert_eq!(v(&s, "F1"), Value::Number(0.0), "a link to a blank cell reads 0"); + assert_eq!(v(&s, "F5"), Value::Number(1.0)); + assert_eq!(v(&s, "F6"), Value::Number(2.0)); + assert_eq!(s.execute("cell.get", json!({"cell": "F5"})).unwrap()["input"], json!("=C5")); +} + +/// A transposed paste clears the destination cells that line up with blank source cells. +#[test] +fn transposed_paste_clears_destination_cells_under_blank_source_cells() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "3"})).unwrap(); + s.execute("cell.set", json!({"cell": "B2", "input": "4"})).unwrap(); + s.execute("cell.set", json!({"cell": "E2", "input": "old"})).unwrap(); + s.execute("cell.set", json!({"cell": "F1", "input": "older"})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:B2"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E1"})).unwrap(); + assert_eq!(v(&s, "E1"), Value::Number(1.0)); + assert_eq!(v(&s, "E2"), Value::Empty, "B1 was blank"); + assert_eq!(v(&s, "F1"), Value::Number(3.0)); + assert_eq!(v(&s, "F2"), Value::Number(4.0)); +} + +/// A copy tiled over a larger selection clears the non-blank destination cells under its blanks, +/// in every tile. +#[test] +fn tiled_paste_clears_destination_cells_under_blank_source_cells() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C2", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "C4", "input": "y"})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A2"})).unwrap(); + s.execute("selection.set", json!({"range": "C1:C4"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(1.0)); + assert_eq!(v(&s, "C2"), Value::Empty); + assert_eq!(v(&s, "C3"), Value::Number(1.0)); + assert_eq!(v(&s, "C4"), Value::Empty); +} + +/// Excel refuses a paste that would run off the sheet rather than pasting part of it: whole +/// columns below row 1, whole rows right of column A, a whole column transposed, or a block at +/// the last row or column. +#[test] +fn paste_that_does_not_fit_on_the_sheet_is_refused() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "C1", "values": [[1, 2], [3, 4]]})).unwrap(); + s.execute("cell.set", json!({"cell": "A15", "input": "x"})).unwrap(); + let before = s.doc().unwrap().wb.clone(); + s.execute("edit.copy", json!({"range": "C:D"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "B8"})).is_err()); + assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "A1"})).is_err()); + s.execute("edit.copy", json!({"range": "15:15"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "AN17"})).is_err()); + s.execute("edit.copy", json!({"range": "C1:D2"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "XFD1"})).is_err()); + assert!(s.execute("edit.paste", json!({"at": "A1048576"})).is_err()); + s.execute("edit.cut", json!({"range": "C1:D2"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "XFD1"})).is_err()); + let after = s.doc().unwrap().wb.clone(); + assert_eq!(after.active().unwrap().cells.len(), before.active().unwrap().cells.len()); + assert_eq!(v(&s, "C1"), Value::Number(1.0)); + // Whole rows still paste at column A, whole columns at row 1. + s.execute("edit.copy", json!({"range": "15:15"})).unwrap(); + s.execute("edit.paste", json!({"at": "A20"})).unwrap(); + assert_eq!(v(&s, "A20"), Value::Text("x".into())); +} + +/// Paste visits only cells that hold something on either side: a blank copied cell still clears +/// (or reformats) a destination cell that holds something, and blank onto blank stays blank, even +/// with an operation (Excel leaves it empty rather than writing 0). +#[test] +fn paste_blank_cells_clear_destination_and_blank_onto_blank_stays_blank() { + let mut s = s(); + let has_cell = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).is_some(); + s.execute("cell.set", json!({"cell": "A1", "input": "5"})).unwrap(); + s.execute("cell.set", json!({"cell": "D2", "input": "7"})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A3"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "values", "operation": "add", "at": "D1"})).unwrap(); + assert_eq!(v(&s, "D1"), Value::Number(5.0)); + assert_eq!(v(&s, "D2"), Value::Number(7.0)); + assert!(!has_cell(&s, "D3"), "blank + blank stays blank"); + s.execute("cell.set", json!({"cell": "F2", "input": "old"})).unwrap(); + s.execute("edit.paste", json!({"at": "F1"})).unwrap(); + assert_eq!(v(&s, "F1"), Value::Number(5.0)); + assert!(!has_cell(&s, "F2"), "a blank copied cell clears the destination"); + s.execute("home.bold", json!({"range": "H2"})).unwrap(); + assert!(has_cell(&s, "H2")); + s.execute("edit.pasteSpecial", json!({"what": "formats", "at": "H1"})).unwrap(); + assert!(!has_cell(&s, "H2"), "a blank copied cell's format replaces the bold"); +} + +/// Validation pastes over the whole pasted area (a blank copied cell's rule included, as Excel +/// does), and cuts only the pasted cells out of a rule the block lands inside. +#[test] +fn paste_validation_covers_the_pasted_area_as_ranges() { + let mut s = s(); + let ok = |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == true; + s.execute("cell.set", json!({"cell": "A1", "input": "5"})).unwrap(); + s.execute("cell.set", json!({"cell": "A3", "input": "6"})).unwrap(); + s.execute("data.validation", json!({"range": "A1:A3", "type": "whole", "operator": "greater", "formula1": "0"})).unwrap(); + s.execute("data.validation", json!({"range": "D1:D3", "type": "list", "formula1": "\"x,y\""})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A3"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "D1"})).unwrap(); + assert!(!ok(&mut s, "D2", "-1"), "the blank copied cell's rule is pasted too"); + assert!(ok(&mut s, "D2", "3")); + assert_eq!(validation_areas(&s), ["A1:A3", "D1:D3"]); + + // A block with a rule on its middle cells pasted inside a bigger list rule. + let mut s = self::s(); + s.execute("data.validation", json!({"range": "A2:A3", "type": "whole", "operator": "greater", "formula1": "0"})).unwrap(); + s.execute("data.validation", json!({"range": "C1:E10", "type": "list", "formula1": "\"p,q\""})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "D4"})).unwrap(); + assert_eq!(validation_areas(&s), ["A2:A3", "C1:E3 C4:C7 E4:E7 C8:E10", "D5:D6"]); + assert!(ok(&mut s, "D4", "anything")); + assert!(!ok(&mut s, "D5", "-1")); + assert!(!ok(&mut s, "D3", "z")); + + // One copied cell tiled over a selection is one rule over the selection. + s.execute("edit.copy", json!({"range": "A2"})).unwrap(); + s.execute("selection.set", json!({"range": "G1:G4"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!(validation_areas(&s).contains(&"G1:G4".to_string())); +} + +/// Paste Special > Validation, checked against Excel 16.0: A1 has a list rule, A2 is blank with a +/// whole-number rule, A3 is blank with no rule, over C1:C3 that hold a decimal rule. With Skip +/// Blanks a blank source cell that has a rule still pastes it, and one without keeps the +/// destination's rule; without it the destination's rule is cleared. +#[test] +fn paste_validation_skip_blanks_keeps_rules_under_blank_cells_without_one() { + let ok = |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == true; + for skip in [true, false] { + let mut s = s(); + s.execute("data.validation", json!({"range": "A1", "type": "list", "formula1": "\"x,y\""})).unwrap(); + s.execute("data.validation", json!({"range": "A2", "type": "whole", "operator": "greater", "formula1": "0"})).unwrap(); + s.execute("data.validation", json!({"range": "C1:C3", "type": "decimal", "operator": "greater", "formula1": "0"})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A3"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "validation", "skipBlanks": skip, "at": "C1"})).unwrap(); + assert!(!ok(&mut s, "C1", "z"), "C1 gets A1's list rule (skip {skip})"); + assert!(!ok(&mut s, "C2", "1.5"), "C2 gets A2's whole-number rule (skip {skip})"); + assert_eq!(ok(&mut s, "C3", "-1"), !skip, "C3 keeps its decimal rule only when blanks are skipped"); + } +} + +/// A big populated Skip Blanks validation paste is not refused for its cell count: only +/// validation areas are limited, and with no rule under the paste nothing is cleared. +#[test] +fn paste_validation_skip_blanks_large_populated_paste() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:A100002", "values": (0..100_002).map(|i| vec![i]).collect::>()})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A100002"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "validation", "skipBlanks": true, "at": "C1"})).unwrap(); + assert!(validation_areas(&s).is_empty()); + + // A destination rule is cleared under every populated source cell. Count the resulting + // coalesced ranges, not the 100,002 cells that were considered for clearing. + let mut s = self::s(); + s.execute("range.setValues", json!({"range": "A1:A100002", "values": (0..100_002).map(|i| vec![i]).collect::>()})).unwrap(); + s.execute("data.validation", json!({"range": "C1:C100002", "type": "list", "formula1": "\"x,y\""})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A100002"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "validation", "skipBlanks": true, "at": "C1"})).unwrap(); + assert!(validation_areas(&s).is_empty()); +} + /// Open a workbook by path, and `CELL("filename")` names the file it came from, as Excel does; /// Save As makes the new file the one it names. The sheet-name formula of #1489 depends on it. #[test] From ff35c6b89db7c3572292579803da4b876af15ec7 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:52:53 -0500 Subject: [PATCH 32/68] xlsx: stop memory amplification from declared sizes (#2173) (#2197) * xlsx: stop memory amplification from declared sizes (#2173) Hyperlinks: drop targets over 8,192 bytes before copying them into each cell, cut ScreenTips to 255 characters, and count the 10,000-cell cap across all blocks of a sheet. Conditional formats: cap the sqref copies made by extra rules at 1M ranges per sheet. Styles: build each custom number format once and share its Arc; cut font names to 255 characters. Shared formulas: keep cached values for dependents of over-long masters, and charge each expansion against a 2 GiB per-workbook budget. Co-Authored-By: Claude Opus 5.5 * Import the hyperlink caps in sheet_read/parts after the merge Upstream switched parts.rs to an explicit super:: import list. Co-Authored-By: Claude Opus 5.5 * xlsx: charge conditional-format ranges per sheet; cap number format codes (#2173) - read_cf keeps a cumulative per-sheet count of the range cells retained rules hold, instead of multiplying the current block by the rule count, and charges only rules that are kept. - Custom and inline number format codes longer than 255 characters (Excel's limit) are dropped with a warning; their cells show General. - The shared NumFmt map is built only for ids a cell or differential format refers to. Co-Authored-By: Claude Opus 5.5 * xlsx: keep over-long number format codes as stored (#2173) an_overlong_number_format_code_does_not_stop_the_open requires a code past 255 characters to round-trip; sharing one NumFmt per referenced id already removes the amplification. Keep the referenced-id sharing. Co-Authored-By: Claude Opus 5.5 * xlsx: bound only what a shared formula costs beyond an ordinary cell; count characters for the length warning Review follow-up for #2197 (@skylartaylor): - Each dependent of a shared formula now pays only its cost beyond an ordinary formula cell (SHARED_FORMULA_FREE_COST, 4 KiB by shared_cost), and the per-workbook budget for that excess drops from 2 GiB to 256 MiB. Many ordinary shared formulas still all expand; a long master copied into thousands of cells stops at the budget and keeps the cached values. - The over-long-master warning now uses the parser's own test (bytes, then characters), so an unparseable multibyte master no longer gets a false length warning. Refs #2173 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps --- crates/xlsx/src/read.rs | 4 + crates/xlsx/src/sheet_read.rs | 119 ++++++++++++++++++++- crates/xlsx/src/sheet_read/parts.rs | 35 ++++--- crates/xlsx/src/sheet_read/rules.rs | 18 ++-- crates/xlsx/src/styles.rs | 49 +++++++-- crates/xlsx/src/tests/malformed.rs | 154 ++++++++++++++++++++++++++++ 6 files changed, 344 insertions(+), 35 deletions(-) diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 93efb7f024..5bdc982163 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -35,6 +35,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)>, + /// Bytes charged so far for shared formulas expanded into dependent cells (see + /// [`crate::sheet_read::MAX_SHARED_FORMULA_BYTES`]). + pub shared_formula_bytes: u64, /// Whether GridCraft calculates a function, when the caller says: cell formulas wrapped by /// Google Sheets' export are then read as the formula inside (see [`crate::read_xlsx_with`]). pub known_function: Option<&'a dyn Fn(&str) -> bool>, @@ -255,6 +258,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], known_function: Option<&'a dyn Fn(&str) -> num_fmts: Default::default(), cell_pictures: vec![], cf_ext_ids: vec![], + shared_formula_bytes: 0, known_function, python: Default::default(), }; diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index f2047b6ee8..e68d143892 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -31,6 +31,16 @@ struct Shared { anchor: CellRef, expr: Option, text: String, + /// Approximate bytes one dependent cell costs (its printed text plus its expression tree); + /// what exceeds [`SHARED_FORMULA_FREE_COST`] is charged against [`MAX_SHARED_FORMULA_BYTES`]. + cost: u64, +} + +/// What one sheet's hyperlinks have copied so far, across all its `` blocks. +#[derive(Default)] +struct LinkBudget { + cells: u64, + bytes: u64, } #[derive(Default)] @@ -120,10 +130,23 @@ fn settle_python_spills_past_budget(st: &RowState, sheet: &mut Sheet) { } } -const MAX_HYPERLINK_CELLS: u64 = 10_000; /// Target and tooltip bytes kept for hyperlinks of one sheet, over all cells: the same URL is /// copied for every cell of its range, so length × cells must stay bounded whatever the file. const MAX_HYPERLINK_BYTES: u64 = 8 * 1024 * 1024; +/// Most cells one sheet's hyperlinks may cover (each cell gets its own copy of the link). +const MAX_HYPERLINK_CELLS: u64 = 10_000; +/// Longest hyperlink target kept, in bytes (Excel's own limit is about 2,079 characters). +const MAX_HYPERLINK_TARGET: usize = 8_192; +/// Longest hyperlink ScreenTip kept, in characters (Excel's limit). +const MAX_TOOLTIP_CHARS: usize = 255; +/// What a dependent of a shared formula may cost for free: an ordinary formula cell's worth (by +/// [`shared_cost`], a formula of about 40 operators and operands), so a sheet of many ordinary +/// shared formulas is never cut short however many cells share them. +const SHARED_FORMULA_FREE_COST: u64 = 4096; +/// Budget, per workbook, for what shared formulas cost beyond [`SHARED_FORMULA_FREE_COST`] per +/// dependent cell: a long master copied into many cells is where the expansion multiplies the +/// file's bytes, and this bounds it to well within a web build's memory. +pub const MAX_SHARED_FORMULA_BYTES: u64 = 256 << 20; const MAX_COLUMN_ASSIGNMENTS: u64 = 1_000_000; /// Most dynamic-array and legacy-array ranges of one sheet. const MAX_DYNAMIC_RANGES: usize = 65_536; @@ -182,6 +205,8 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr drop(bytes); let mut fit_to_page = false; + let mut link_budget = LinkBudget::default(); + let mut cf_kept_cells = 0u64; let mut column_assignments_left = MAX_COLUMN_ASSIGNMENTS; cx.cf_ext_ids.clear(); for e in &root.children { @@ -208,7 +233,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "conditionalFormatting" => read_cf(cx, e, &mut sheet), + "conditionalFormatting" => read_cf(cx, e, &mut sheet, &mut cf_kept_cells), "dataValidations" => { for v in e.kids("dataValidation") { if let Some(v) = read_validation(v) { @@ -216,7 +241,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet), + "hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_budget), "autoFilter" => sheet.autofilter = read_autofilter(cx, e), "printOptions" => { sheet.print.gridlines = e.flag("gridLines", false); @@ -641,13 +666,30 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, let si = f.attr_u32("si")?; if !text.is_empty() { let expr = gridcraft_formula::parse(text).ok(); - st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string() }); + let cost = shared_cost(text, expr.as_ref()); + st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string(), cost }); Some(Formula::new(text)) } else { let Some(sh) = st.shared.get(&si) else { cx.warn("a shared formula refers to a missing master cell; kept the cached value"); return None; }; + // The parser's own test: bytes first (cheap), then characters, so a multibyte + // master that failed to parse for another reason gets no false length warning. + if sh.expr.is_none() + && sh.text.len() > gridcraft_formula::MAX_FORMULA_LEN + && sh.text.chars().count() > gridcraft_formula::MAX_FORMULA_LEN + { + cx.warn(format!( + "a shared formula is longer than {} characters; kept the cached values of the cells that share it", + gridcraft_formula::MAX_FORMULA_LEN + )); + return None; + } + if !charge(&mut cx.shared_formula_bytes, extra_shared_cost(sh.cost), MAX_SHARED_FORMULA_BYTES) { + cx.warn("shared formulas expand to too much data; kept the cached values of the remaining cells that share them"); + return None; + } Some(match &sh.expr { Some(e) => { let dr = pos.row as i64 - sh.anchor.row as i64; @@ -720,6 +762,41 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { Some(serial) } +/// What one dependent of a shared formula costs: its printed text plus its expression tree. +fn shared_cost(text: &str, expr: Option<&Expr>) -> u64 { + let mut nodes = 0u64; + if let Some(e) = expr { + e.walk(&mut |_| nodes = nodes.saturating_add(1)); + } + let node = std::mem::size_of::() as u64; + (text.len() as u64).saturating_mul(2).saturating_add(nodes.saturating_mul(node)).saturating_add(64) +} + +/// What one dependent of a shared formula costing `cost` is charged: its cost beyond an ordinary +/// formula cell's. +fn extra_shared_cost(cost: u64) -> u64 { + cost.saturating_sub(SHARED_FORMULA_FREE_COST) +} + +/// Adds `cost` to `used` when that stays within `cap`; `false` (and `used` unchanged) otherwise. +fn charge(used: &mut u64, cost: u64, cap: u64) -> bool { + match used.checked_add(cost) { + Some(total) if total <= cap => { + *used = total; + true + } + _ => false, + } +} + +/// The first `max` characters of `s`. +fn truncate_chars(s: &str, max: usize) -> String { + match s.char_indices().nth(max) { + Some((at, _)) => s.get(..at).unwrap_or(s).to_string(), + None => s.to_string(), + } +} + pub fn parse_sqref(s: Option<&str>) -> Vec { s.unwrap_or("").split_whitespace().filter_map(RangeRef::parse).collect() } @@ -780,6 +857,40 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { mod tests { use super::*; + #[test] + fn shared_formula_budget_stops_expansion() { + let expr = gridcraft_formula::parse("SUM(1,2,3)").ok(); + let cost = shared_cost("SUM(1,2,3)", expr.as_ref()); + assert!(cost > 64 + 4 * std::mem::size_of::() as u64); + let cap = cost * 3; + let mut used = 0; + assert!((0..3).all(|_| charge(&mut used, cost, cap))); + assert!(!charge(&mut used, cost, cap)); + assert_eq!(used, cap); + assert!(!charge(&mut used, u64::MAX, u64::MAX)); + } + + #[test] + fn ordinary_shared_formulas_are_free_and_long_ones_pay_their_excess() { + let text = r#"IF(AND(A1>0,B1<>""),VLOOKUP(C1,Sheet2!$A$1:$D$500,4,FALSE)*SUM(D1:D10)/COUNT(D1:D10),IFERROR(E1/F1,0))"#; + let expr = gridcraft_formula::parse(text).ok(); + assert!(expr.is_some()); + assert_eq!(extra_shared_cost(shared_cost(text, expr.as_ref())), 0, "an ordinary formula costs nothing extra"); + let long = vec![format!("SUM({}1)", "1,".repeat(199)); 10].join("+"); + let expr = gridcraft_formula::parse(&long).ok(); + assert!(expr.is_some()); + let cost = shared_cost(&long, expr.as_ref()); + assert_eq!(extra_shared_cost(cost), cost - SHARED_FORMULA_FREE_COST); + // A few thousand copies of a long master no longer fit the budget. + assert!(extra_shared_cost(cost).saturating_mul(10_000) > MAX_SHARED_FORMULA_BYTES); + } + + #[test] + fn truncate_keeps_whole_characters() { + assert_eq!(truncate_chars("ab\u{e9}d", 3), "ab\u{e9}"); + assert_eq!(truncate_chars("ab", 3), "ab"); + } + #[test] fn iso_dates() { assert_eq!(parse_iso_datetime("1900-01-01", DateSystem::D1900), Some(1.0)); diff --git a/crates/xlsx/src/sheet_read/parts.rs b/crates/xlsx/src/sheet_read/parts.rs index 3ff6722899..309ab4a025 100644 --- a/crates/xlsx/src/sheet_read/parts.rs +++ b/crates/xlsx/src/sheet_read/parts.rs @@ -1,17 +1,25 @@ use super::{ - AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS, MAX_ROWS, - NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr, from_file, xml, + AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, LinkBudget, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS, + MAX_HYPERLINK_TARGET, MAX_ROWS, MAX_TOOLTIP_CHARS, NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr, + from_file, truncate_chars, xml, }; -pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet) { - let mut cells = 0u64; - let mut bytes = 0u64; +/// `budget` counts the cells and bytes this sheet's hyperlinks have copied so far, across +/// `` blocks. +pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, budget: &mut LinkBudget) { for h in e.kids("hyperlink") { let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue }; - let mut target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.clone()).unwrap_or_default(); + let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or(""); + let location = h.attr("location").filter(|l| !l.is_empty()); + // Each covered cell gets its own copy of the link: refuse oversized targets before copying. + if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET { + cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped")); + continue; + } + let mut target = rel_target.to_string(); // A relationship is a file or web page; a bare `location` is a place in this workbook. let external = !target.is_empty(); - if let Some(loc) = h.attr("location").filter(|l| !l.is_empty()) { + if let Some(loc) = location { if target.is_empty() { target = loc.trim_start_matches('#').to_string(); } else { @@ -21,19 +29,20 @@ pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel] if target.is_empty() { continue; } - let link = Hyperlink { target: target.clone(), tooltip: h.attr("tooltip").map(str::to_string), external }; - let link_bytes = (target.len() + link.tooltip.as_ref().map_or(0, |t| t.len())) as u64; + let tooltip = h.attr("tooltip").map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS)); + let link_bytes = (target.len() + tooltip.as_ref().map_or(0, String::len)) as u64; + let link = Hyperlink { target, tooltip, external }; for c in range.iter() { - if cells >= MAX_HYPERLINK_CELLS { + if budget.cells >= MAX_HYPERLINK_CELLS { cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped")); return; } - if bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { + if budget.bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { cx.warn(format!("sheet \"{name}\": hyperlink targets past {MAX_HYPERLINK_BYTES} bytes were dropped")); return; } - cells += 1; - bytes += link_bytes; + budget.cells += 1; + budget.bytes += link_bytes; sheet.hyperlinks.insert(c, link.clone()); } } diff --git a/crates/xlsx/src/sheet_read/rules.rs b/crates/xlsx/src/sheet_read/rules.rs index 4e45007070..c3a3f04f65 100644 --- a/crates/xlsx/src/sheet_read/rules.rs +++ b/crates/xlsx/src/sheet_read/rules.rs @@ -45,11 +45,15 @@ fn cfvos(e: &El) -> Vec { .collect() } -pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { +/// One `conditionalFormatting` block. Every rule keeps its own copy of the block's ranges, so +/// `kept_cells` counts the range cells the sheet's retained rules hold so far, across blocks; a +/// rule that would take it past [`MAX_COND_CELLS`] is dropped. Unsupported rules cost nothing. +pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &mut u64) { let ranges = parse_sqref(e.attr("sqref")); if ranges.is_empty() { return; } + let block_cells = ranges.iter().map(RangeRef::count).fold(0u64, u64::saturating_add); for r in e.kids("cfRule") { let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default()); let formulas: Vec = r.kids("formula").map(|f| from_file(f.text.trim())).collect(); @@ -111,15 +115,15 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { continue; } }; - if let Some(id) = ext_id { - cx.cf_ext_ids.push((id, sheet.cond_formats.len())); - } - let rules = sheet.cond_formats.len(); - let area = ranges.iter().map(RangeRef::count).sum::().saturating_mul(1 + rules as u64); - if area > MAX_COND_CELLS { + let total = kept_cells.saturating_add(block_cells); + if total > MAX_COND_CELLS { cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped")); break; } + *kept_cells = total; + if let Some(id) = ext_id { + cx.cf_ext_ids.push((id, sheet.cond_formats.len())); + } sheet.cond_formats.push(CondFormat { ranges: ranges.clone(), rule, diff --git a/crates/xlsx/src/styles.rs b/crates/xlsx/src/styles.rs index c1f93aca9b..04c9fcdf2a 100644 --- a/crates/xlsx/src/styles.rs +++ b/crates/xlsx/src/styles.rs @@ -1,7 +1,7 @@ //! `styles.xml`: reading cell formats and differential formats into model styles, and writing //! the workbook's style table. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fmt::Write as _; use gridcraft_model::style::{DxfStated, Protection}; @@ -14,6 +14,9 @@ use crate::xml::{El, esc_attr, num}; // ---------------------------------------------------------------- reading +/// Longest font name kept, in characters (Excel's own limit is 31). +pub const MAX_FONT_NAME_CHARS: usize = 255; + /// Styles read from a file. #[derive(Debug, Default)] pub struct StylesIn { @@ -63,7 +66,11 @@ const MAX_FONT_FAMILY: u8 = 14; pub fn read_font(e: &El, palette: &[u32]) -> Font { let mut f = Font::default(); if let Some(n) = e.child("name").or_else(|| e.child("rFont")).and_then(|n| n.attr("val")) { - f.name = n.to_string(); + // Every cell format that uses the font copies its name: keep it short. + f.name = match n.char_indices().nth(MAX_FONT_NAME_CHARS) { + Some((at, _)) => n.get(..at).unwrap_or_default().to_string(), + None => n.to_string(), + }; } if let Some(sz) = e.child("sz").and_then(|s| s.attr_f64("val")) { f.size = sz.clamp(1.0, 409.0) as f32; @@ -277,14 +284,16 @@ fn read_protection(p: &El) -> Protection { Protection { locked: p.flag("locked", true), hidden: p.flag("hidden", false) } } -fn num_fmt_code(id: u32, custom: &HashMap) -> NumFmt { +/// A number format by id. Custom formats are built once and shared (`NumFmt` is an `Arc`), so +/// many cell formats naming one long code don't each copy it. +fn num_fmt_code(id: u32, custom: &HashMap) -> NumFmt { if let Some(c) = custom.get(&id) { - return NumFmt::new(c); + return c.clone(); } NumFmt::new(builtin_format(id).unwrap_or("General")) } -fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap, checkboxes: &[bool]) -> Style { +fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap, checkboxes: &[bool]) -> Style { let mut s = Style::default(); if let Some(f) = xf.attr_u32("fontId").and_then(|i| fonts.get(i as usize)) { s.font = f.clone(); @@ -336,6 +345,20 @@ pub fn read_styles(root: &El, checkboxes: &[bool], minor_font: &str) -> StylesIn } } } + // One shared `NumFmt` per custom id a cell format or differential format refers to (`NumFmt` + // is an `Arc`); declared but unused codes get no second copy. + let mut used: HashSet = HashSet::new(); + for list in ["cellXfs", "cellStyleXfs"] { + if let Some(x) = root.child(list) { + used.extend(x.kids("xf").map(|xf| xf.attr_u32("numFmtId").unwrap_or(0))); + } + } + if let Some(d) = root.child("dxfs") { + used.extend( + d.kids("dxf").filter_map(|x| x.child("numFmt")).filter(|n| n.attr("formatCode").is_none()).filter_map(|n| n.attr_u32("numFmtId")), + ); + } + let shared_fmts: HashMap = fmts.iter().filter(|(id, _)| used.contains(id)).map(|(&id, code)| (id, NumFmt::new(code))).collect(); // The scheme link only means something on a font in the body face; elsewhere it stays as a new font has it. let body_font = |e: &El| { let mut f = read_font(e, &palette); @@ -345,10 +368,14 @@ pub fn read_styles(root: &El, checkboxes: &[bool], minor_font: &str) -> StylesIn let fonts: Vec = root.child("fonts").map(|f| f.kids("font").map(body_font).collect()).unwrap_or_default(); let fills: Vec = root.child("fills").map(|f| f.kids("fill").map(|e| read_fill(e, &palette, false)).collect()).unwrap_or_default(); let borders: Vec = root.child("borders").map(|f| f.kids("border").map(|e| read_border(e, &palette)).collect()).unwrap_or_default(); - let xfs = - root.child("cellXfs").map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &fmts, checkboxes)).collect()).unwrap_or_default(); - let style_xfs: Vec