mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-04 03:26:49 -06:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86ba6b5138 | ||
|
|
5a850f6a72 | ||
|
|
0f2589bfef | ||
|
|
ba82b95ca0 | ||
|
|
41a5eb8a56 | ||
|
|
966b87337f | ||
|
|
2aa1ac4683 | ||
|
|
623061303f | ||
|
|
c05683be93 | ||
|
|
9622664cd5 | ||
|
|
1aef9a961d | ||
|
|
f528d1233f | ||
|
|
95d904dfe2 | ||
|
|
ed6f1852c6 | ||
|
|
1ce588b785 | ||
|
|
4efade7515 | ||
|
|
53403bc2dd | ||
|
|
62260e6e4b | ||
|
|
e7f9d0008b | ||
|
|
a72b9287f2 | ||
|
|
5b19af3c89 | ||
|
|
2a0183e3d2 | ||
|
|
230bf2304f | ||
|
|
bb0d997cfd | ||
|
|
c824ae702e | ||
|
|
63a9c928a2 | ||
|
|
8cc7cc4e38 | ||
|
|
74014cc850 | ||
|
|
5647e98048 | ||
|
|
2c04e06499 |
@@ -141,6 +141,11 @@ pub trait Host {
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
range.iter().map(|c| self.cell_value(sheet, c)).collect()
|
||||
}
|
||||
/// Finds the smallest rectangle covering the non-empty cells of a block without reading its
|
||||
/// full grid. The outer `None` leaves the read to `range_values`. `Some(None)` means all blank.
|
||||
fn range_nonempty_bounds(&mut self, _sheet: usize, _range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
None
|
||||
}
|
||||
/// The sheet's used range (`Sheet::used_range`, which walks every stored row). Hosts that
|
||||
/// keep the workbook unchanged while evaluating can remember it.
|
||||
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
|
||||
|
||||
@@ -915,6 +915,70 @@ pub(crate) mod tests {
|
||||
assert!(!index_spills(5_000, 5_000, [].iter()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_references_skip_the_dense_grid_for_sparse_stored_values() {
|
||||
use crate::eval::{Area, Ev, Evaluator};
|
||||
use gridcraft_core::CellError;
|
||||
use gridcraft_model::StyleId;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
sh.set_cell(at("C3"), Cell::value(Value::Number(0.0)));
|
||||
let mut cached = Cell::formula(Formula::new("\"\""));
|
||||
cached.value = Value::text("");
|
||||
sh.set_cell(at("N39999"), cached);
|
||||
sh.set_cell(at("Q40001"), Cell::styled(Value::Empty, StyleId(1)));
|
||||
// These cells keep the sheet's used extent wide and tall without being in the trim range.
|
||||
sh.set_cell(at("Q1"), Cell::value(Value::Number(1.0)));
|
||||
sh.set_cell(at("A40001"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let mut ev = Evaluator::new(&mut host, 0, at("S1"));
|
||||
for (src, expected) in [("B2.:.Q40001", "C3:N39999"), ("TRIMRANGE(B2:Q40001,1,2)", "B3:N40001")] {
|
||||
let expr = gridcraft_formula::parse(src).unwrap();
|
||||
let result = ev.eval(&expr);
|
||||
let area = Area { sheet: 0, range: RangeRef::parse(expected).unwrap() };
|
||||
assert!(matches!(&result, Ev::R(areas) if areas.as_slice() == [area]), "{src}: {result:?}");
|
||||
}
|
||||
let blank = gridcraft_formula::parse("TRIMRANGE(O2:Q40001)").unwrap();
|
||||
assert!(matches!(ev.eval(&blank), Ev::V(Value::Error(CellError::Calc))));
|
||||
assert_eq!(host.materialized_range_cells, 0, "bounds reads must not allocate a dense grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_range_includes_a_spill_from_outside_the_block() {
|
||||
use crate::eval::Evaluator;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
let anchor = (0, at("C1"));
|
||||
let target = at("I1");
|
||||
let source = Formula::new("SEQUENCE(2,5)");
|
||||
let consumer = Formula::new("COLUMNS(TRIMRANGE(C2:G4))");
|
||||
let exprs = [(anchor, source.expr_arc().unwrap()), ((0, target), consumer.expr_arc().unwrap())].into_iter().collect();
|
||||
sh.set_cell(anchor.1, Cell::formula(source));
|
||||
sh.set_cell(target, Cell::formula(consumer));
|
||||
// Extend the read area before the new spill has been committed to the sheet.
|
||||
sh.set_cell(at("H5"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
host.calculate(anchor);
|
||||
host.calculate((0, target));
|
||||
assert_eq!(host.results.get(&(0, target)), Some(&Value::Number(5.0)), "new spill in the current pass");
|
||||
|
||||
Calc::new().recalc_all(&mut wb);
|
||||
let exprs = HashMap::default();
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let consumer = gridcraft_formula::parse("COLUMNS(TRIMRANGE(C2:G4))").unwrap();
|
||||
let result = Evaluator::new(&mut host, 0, target).value(&consumer);
|
||||
assert_eq!(result, Value::Number(5.0), "stored spill from a completed recalculation");
|
||||
}
|
||||
|
||||
/// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already
|
||||
/// spilled on the sheet from the last calculation, as a full recalculation finds them.
|
||||
fn big_python_spill() -> (Workbook, HashMap<Key, Value>) {
|
||||
|
||||
@@ -57,6 +57,9 @@ pub(super) struct PassHost<'a> {
|
||||
/// looks at none of it).
|
||||
#[cfg(test)]
|
||||
pub(super) spill_visits: usize,
|
||||
/// Number of value slots allocated by dense range reads.
|
||||
#[cfg(test)]
|
||||
pub(super) materialized_range_cells: usize,
|
||||
/// The formulas in `cycles`.
|
||||
cycle_seen: HashSet<Key>,
|
||||
/// Iterative calculation: a circular reference reads the cell's previous value instead of
|
||||
@@ -114,6 +117,8 @@ impl<'a> PassHost<'a> {
|
||||
suspensions: 0,
|
||||
#[cfg(test)]
|
||||
spill_visits: 0,
|
||||
#[cfg(test)]
|
||||
materialized_range_cells: 0,
|
||||
cycle_seen: HashSet::default(),
|
||||
iterate: false,
|
||||
prev: HashMap::default(),
|
||||
@@ -238,6 +243,25 @@ fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &m
|
||||
}
|
||||
|
||||
impl PassHost<'_> {
|
||||
fn range_has_spill(&mut self, sheet: usize, range: RangeRef) -> bool {
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
if !arrays.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return false };
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would
|
||||
/// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is
|
||||
/// calculated from here, then the suspended ones again (reading the results kept so far).
|
||||
@@ -609,6 +633,10 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
let (h, w) = (range.height() as usize, range.width() as usize);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.materialized_range_cells += h * w;
|
||||
}
|
||||
let mut out = vec![Value::Empty; h * w];
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return out };
|
||||
// Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go
|
||||
@@ -698,18 +726,7 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
// Spilled values sit between the stored cells (and the formulas just calculated may have
|
||||
// produced some): leave such blocks to `range_values`.
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
if !arrays.is_empty() || stored {
|
||||
if self.range_has_spill(sheet, range) {
|
||||
return false;
|
||||
}
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
@@ -720,6 +737,32 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
if self.iterate || self.range_has_spill(sheet, range) {
|
||||
return None;
|
||||
}
|
||||
let sh = self.wb.sheet(sheet)?;
|
||||
// When fewer calculations are in play than cells to inspect, check their coordinates
|
||||
// first. A formula near the bottom of a dense range would otherwise cost two walks.
|
||||
let pass_cells = self.pending.len() + self.results.len();
|
||||
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
|
||||
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
|
||||
return None;
|
||||
}
|
||||
let mut bounds: Option<RangeRef> = None;
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
// With no pending or computed results in the block, formula and Python readers
|
||||
// see the stored values as well. Otherwise leave their evaluation to range_values.
|
||||
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
|
||||
return None;
|
||||
}
|
||||
if !cell.value.is_empty() {
|
||||
let cell_range = RangeRef::cell(c);
|
||||
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
|
||||
}
|
||||
}
|
||||
Some(bounds)
|
||||
}
|
||||
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
|
||||
// Constants can't change during a pass, so a block's result stays valid for it. Spills
|
||||
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
|
||||
|
||||
@@ -2497,6 +2497,21 @@ fn blank_lookup_values_match_excel_windows_observation() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_blank_lookup_argument_is_numeric_zero() {
|
||||
// #4044: `XMATCH(, array)` writes a blank argument, which Excel reads as numeric zero. Only a
|
||||
// reference to a blank cell (B1 here) is a blank lookup value.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=XMATCH(,{0,1,3})");
|
||||
t.set("A2", "=XMATCH(B1,{0,1,3})");
|
||||
t.set("A3", "=XLOOKUP(,{0,1,3},{10,20,30})");
|
||||
t.set("A4", "=XLOOKUP(B1,{0,1,3},{10,20,30},\"none\")");
|
||||
assert_eq!(t.get("A1"), Value::Number(1.0));
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::NA));
|
||||
assert_eq!(t.get("A3"), Value::Number(10.0));
|
||||
assert_eq!(t.get("A4"), Value::from("none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_width_is_the_column_width_dialog_value_rounded() {
|
||||
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
|
||||
|
||||
@@ -95,8 +95,15 @@ impl Evaluator<'_> {
|
||||
if (h as u64) * (w as u64) > MAX_CELLS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
|
||||
let ((r0, r1), (c0, c1)) = if let Some(nonempty) = self.host.range_nonempty_bounds(a.sheet, part) {
|
||||
let nonempty = nonempty.ok_or(CellError::Calc)?;
|
||||
let row = |c: CellRef| (c.row - part.start.row) as usize;
|
||||
let col = |c: CellRef| (c.col - part.start.col) as usize;
|
||||
((row(nonempty.start), row(nonempty.end)), (col(nonempty.start), col(nonempty.end)))
|
||||
} else {
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
bounds(&values, w).ok_or(CellError::Calc)?
|
||||
};
|
||||
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
|
||||
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
|
||||
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
|
||||
|
||||
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use axis::{Scale, format_number, nice_scale};
|
||||
pub use raster::rasterize;
|
||||
pub use render::{Swatch, legend_entries, render, supports_trendline};
|
||||
pub use render::{ChartLabels, Swatch, legend_entries, legend_entries_with, render, render_with_labels, supports_trendline};
|
||||
pub use resolve::{default_palette, has_volatile_series, resolve, series_color};
|
||||
pub use sparkline::render_sparkline;
|
||||
|
||||
|
||||
@@ -20,9 +20,9 @@ mod trend;
|
||||
|
||||
use cartesian::{cartesian, scatter};
|
||||
use frame::{Bx, axis_titles, chart_title};
|
||||
use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall};
|
||||
use kinds::{box_whisker, doughnut, funnel, histogram, pareto, pie, radar, stock, treemap, waterfall};
|
||||
use legend::draw_legend;
|
||||
pub use legend::{Swatch, legend_entries};
|
||||
pub use legend::{ChartLabels, Swatch, legend_entries, legend_entries_with};
|
||||
pub use trend::supports_trendline;
|
||||
|
||||
pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF];
|
||||
@@ -40,9 +40,9 @@ const AXIS_TITLE_SIZE: f32 = 10.0;
|
||||
/// Most categories drawn by category-axis charts.
|
||||
const MAX_CATS: usize = 20_000;
|
||||
/// Lines with more points than this are decimated (min/max per pixel column).
|
||||
const MAX_LINE_PTS: usize = 2000;
|
||||
pub(crate) const MAX_LINE_PTS: usize = 2000;
|
||||
/// Most markers per series (after de-duplicating by pixel).
|
||||
const MAX_MARKERS: usize = 5000;
|
||||
pub(crate) 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.
|
||||
@@ -217,6 +217,11 @@ pub(crate) fn sanitized(d: &ChartData) -> Cow<'_, ChartData> {
|
||||
|
||||
/// Lays out and draws a chart into a `w`×`h` box at the origin. Empty for a degenerate box.
|
||||
pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) -> Vec<Prim> {
|
||||
render_with_labels(chart, data, w, h, m, &ChartLabels::default())
|
||||
}
|
||||
|
||||
/// [`render`] with interface strings supplied by the UI.
|
||||
pub fn render_with_labels(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure, labels: &ChartLabels<'_>) -> Vec<Prim> {
|
||||
if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e7 || h > 1e7 {
|
||||
return vec![];
|
||||
}
|
||||
@@ -233,7 +238,7 @@ pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure)
|
||||
area.y += used;
|
||||
area.h -= used;
|
||||
}
|
||||
let entries = legend_entries(chart, &data);
|
||||
let entries = legend_entries_with(chart, &data, labels);
|
||||
if !entries.is_empty() && area.ok() {
|
||||
area = draw_legend(&mut ctx, &entries, chart.legend, area);
|
||||
}
|
||||
@@ -261,6 +266,7 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
BarClustered | BarStacked | BarStacked100 => cartesian(ctx, chart, data, area, true),
|
||||
Scatter | ScatterLines | Bubble => scatter(ctx, chart, data, area),
|
||||
Histogram => histogram(ctx, chart, data, area),
|
||||
Pareto => pareto(ctx, chart, data, area),
|
||||
Waterfall => waterfall(ctx, chart, data, area),
|
||||
BoxWhisker => box_whisker(ctx, chart, data, area),
|
||||
Stock => stock(ctx, chart, data, area),
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range};
|
||||
use super::legend::{cat_label, point_color};
|
||||
use super::legend::{cat_label, pareto_line_color, point_color};
|
||||
use super::lines::decimate;
|
||||
use super::{
|
||||
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
|
||||
QuartileMethod, Rgba, STOCK, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
|
||||
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
|
||||
QuartileMethod, Rgba, STOCK, Scale, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- histogram
|
||||
|
||||
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let Some((lo, hi)) = value_range(vals.iter().copied()) else { return };
|
||||
/// Histogram bins for `vals`: right-inclusive labels and counts, as Excel's histogram and the
|
||||
/// numeric-only form of a Pareto chart use.
|
||||
fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
|
||||
let (lo, hi) = value_range(vals.iter().copied())?;
|
||||
let n = vals.len();
|
||||
let span = hi - lo;
|
||||
let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100);
|
||||
@@ -22,13 +25,12 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
// equal to an edge belongs to the bin that ends there.
|
||||
let edges: Vec<f64> = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect();
|
||||
let mut counts = vec![0usize; bins];
|
||||
for v in &vals {
|
||||
for v in vals {
|
||||
let b = edges.partition_point(|e| e < v).min(bins - 1);
|
||||
if let Some(c) = counts.get_mut(b) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let f = Fmt::new(&s.number_format);
|
||||
let labels: Vec<String> = (0..bins)
|
||||
.map(|b| {
|
||||
let a = lo + b as f64 * width;
|
||||
@@ -37,6 +39,15 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0)))
|
||||
})
|
||||
.collect();
|
||||
Some((labels, counts))
|
||||
}
|
||||
|
||||
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let f = Fmt::new(&s.number_format);
|
||||
let Some((labels, counts)) = histogram_bins(&vals, &f) else { return };
|
||||
let bins = counts.len();
|
||||
let maxc = counts.iter().copied().max().unwrap_or(0) as f64;
|
||||
let ys = nice_scale(0.0, maxc, true);
|
||||
let fc = Fmt::new("General");
|
||||
@@ -55,6 +66,111 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pareto
|
||||
|
||||
/// Sorted columns and a cumulative-percentage line on a secondary 0–100% axis.
|
||||
pub(super) fn pareto(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let f = Fmt::new(&s.number_format);
|
||||
// With no category range Excel charts a Pareto's numbers in histogram bins (the Pareto page:
|
||||
// "If you select two columns of numbers ... Excel charts your data in bins").
|
||||
let binned = chart.series.first().is_some_and(|x| x.categories.is_none());
|
||||
let (labels, vals): (Vec<String>, Vec<f64>) = if binned {
|
||||
let raw: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let Some((labels, counts)) = histogram_bins(&raw, &f) else { return };
|
||||
let mut items: Vec<(String, f64)> = labels.into_iter().zip(counts.into_iter().map(|c| c as f64)).collect();
|
||||
items.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
items.into_iter().unzip()
|
||||
} else {
|
||||
let n = data.categories.len().max(s.values.len()).min(MAX_CATS);
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
// Excel groups equal categories and sums their values before sorting (the Pareto doc's
|
||||
// "groups the same categories and sums the corresponding numbers").
|
||||
let mut groups: Vec<(String, f64)> = Vec::new();
|
||||
let mut index: HashMap<String, usize> = HashMap::new();
|
||||
for j in 0..n {
|
||||
let label = cat_label(data, j);
|
||||
let v = s.values.get(j).copied().flatten().unwrap_or(0.0);
|
||||
match index.get(&label) {
|
||||
Some(&i) => {
|
||||
if let Some(g) = groups.get_mut(i) {
|
||||
g.1 += v;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
index.insert(label.clone(), groups.len());
|
||||
groups.push((label, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Largest first; a stable sort keeps first-appearance order for equal sums.
|
||||
groups.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
(groups.iter().map(|(l, _)| l.clone()).collect(), groups.iter().map(|(_, v)| *v).collect())
|
||||
};
|
||||
let n = labels.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let hi = vals.iter().copied().fold(0.0f64, f64::max);
|
||||
let lo = vals.iter().copied().fold(0.0f64, f64::min);
|
||||
let ys = nice_scale(lo, hi, true);
|
||||
let pct = Fmt::new("0%");
|
||||
let value_fmt = if binned { Fmt::new("General") } else { Fmt::new(&s.number_format) };
|
||||
// A cumulative percentage axis is fixed at 0–100%: Excel shows it that way, and the line
|
||||
// below maps each cumulative share straight onto the plot height.
|
||||
let ys2 = Scale { min: 0.0, max: 1.0, step: 0.2 };
|
||||
let plot = frame(
|
||||
ctx,
|
||||
area,
|
||||
CatAxis::Labels(&labels, &[]),
|
||||
&ValAxis { scale: ys, fmt: &value_fmt },
|
||||
Some(&ValAxis { scale: ys2, fmt: &pct }),
|
||||
false,
|
||||
chart.gridlines,
|
||||
);
|
||||
if !plot.ok() {
|
||||
return;
|
||||
}
|
||||
let total: f64 = vals.iter().copied().sum();
|
||||
// A cumulative percentage is only meaningful when every category is nonnegative. The binned
|
||||
// path counts values, so its counts always are.
|
||||
let cumulative = total.is_finite() && total != 0.0 && (binned || vals.iter().all(|v| *v >= 0.0));
|
||||
let cw = plot.w / n as f32;
|
||||
let bw = (cw * 0.72).clamp(1.0, 120.0);
|
||||
let y0 = plot.bottom() - ys.frac(0.0) * plot.h;
|
||||
let mut pts = Vec::with_capacity(n);
|
||||
let mut cum = 0.0;
|
||||
for (j, v) in vals.iter().enumerate() {
|
||||
let x = plot.x + (j as f32 + 0.5) * cw;
|
||||
let yv = plot.bottom() - ys.frac(*v) * plot.h;
|
||||
ctx.rect(x - bw / 2.0, yv.min(y0), bw, (y0 - yv).abs().max(0.5), s.color, None);
|
||||
if chart.data_labels && n <= MAX_LABELS {
|
||||
let t = value_fmt.format(*v, None);
|
||||
if *v >= 0.0 {
|
||||
ctx.text(x, yv.min(y0) - 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom));
|
||||
} else {
|
||||
ctx.text(x, yv.max(y0) + 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Top));
|
||||
}
|
||||
}
|
||||
if cumulative {
|
||||
cum += *v;
|
||||
let frac = (cum / total).clamp(0.0, 1.0) as f32;
|
||||
pts.push([x, plot.bottom() - frac * plot.h]);
|
||||
}
|
||||
}
|
||||
if pts.len() >= 2 {
|
||||
let color = pareto_line_color(data);
|
||||
// Keep the line and markers bounded on category-heavy charts, as the other renderers do.
|
||||
let markers: Vec<[f32; 2]> = if cw >= 3.0 { pts.iter().take(MAX_MARKERS).copied().collect() } else { Vec::new() };
|
||||
ctx.line(decimate(pts, MAX_LINE_PTS), color, 1.5);
|
||||
for p in markers {
|
||||
ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r: 2.0, fill: Some(color), stroke: Some((WHITE, 0.75)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- waterfall
|
||||
|
||||
pub(super) fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
|
||||
@@ -31,8 +31,32 @@ pub(super) fn cat_label(data: &ChartData, j: usize) -> String {
|
||||
data.categories.get(j).cloned().unwrap_or_else(|| (j + 1).to_string())
|
||||
}
|
||||
|
||||
/// The cumulative line's colour: the second palette colour, so it stands apart from the bars.
|
||||
pub(super) fn pareto_line_color(data: &ChartData) -> Rgba {
|
||||
data.palette.get(1).copied().or_else(|| data.series.first().map(|_| series_color(&Theme::default(), 1))).unwrap_or(TEXT)
|
||||
}
|
||||
|
||||
/// Interface strings a chart legend can need. The UI passes translated text; the default is
|
||||
/// English for callers without an interface language (PDF export, tests).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ChartLabels<'a> {
|
||||
/// Legend name of a Pareto chart's cumulative line.
|
||||
pub cumulative: &'a str,
|
||||
}
|
||||
|
||||
impl Default for ChartLabels<'_> {
|
||||
fn default() -> Self {
|
||||
Self { cumulative: "Cumulative %" }
|
||||
}
|
||||
}
|
||||
|
||||
/// Legend entries (text, colour, swatch) `render` draws for this chart; empty when hidden.
|
||||
pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swatch)> {
|
||||
legend_entries_with(chart, data, &ChartLabels::default())
|
||||
}
|
||||
|
||||
/// [`legend_entries`] with interface strings supplied by the UI.
|
||||
pub fn legend_entries_with(chart: &Chart, data: &ChartData, labels: &ChartLabels<'_>) -> Vec<(String, Rgba, Swatch)> {
|
||||
if chart.legend == LegendPos::None {
|
||||
return vec![];
|
||||
}
|
||||
@@ -44,6 +68,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
|
||||
(0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect()
|
||||
}
|
||||
ChartKind::Histogram | ChartKind::Funnel | ChartKind::Stock => vec![],
|
||||
ChartKind::Pareto => match data.series.first() {
|
||||
Some(s) => vec![(s.name.clone(), s.color, Swatch::Box), (labels.cumulative.to_string(), pareto_line_color(data), Swatch::Line)],
|
||||
None => vec![],
|
||||
},
|
||||
ChartKind::Waterfall => {
|
||||
if data.series.is_empty() {
|
||||
return vec![];
|
||||
|
||||
+196
-1
@@ -3,12 +3,13 @@ use std::sync::Arc;
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, SparklineKind, Style, Workbook};
|
||||
|
||||
use crate::render::MAX_MARKERS;
|
||||
use crate::*;
|
||||
|
||||
mod budget;
|
||||
mod data_table;
|
||||
|
||||
const ALL_KINDS: [ChartKind; 28] = [
|
||||
const ALL_KINDS: [ChartKind; 29] = [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
@@ -30,6 +31,7 @@ const ALL_KINDS: [ChartKind; 28] = [
|
||||
ChartKind::Bubble,
|
||||
ChartKind::Radar,
|
||||
ChartKind::Histogram,
|
||||
ChartKind::Pareto,
|
||||
ChartKind::Waterfall,
|
||||
ChartKind::Funnel,
|
||||
ChartKind::Treemap,
|
||||
@@ -154,6 +156,198 @@ fn every_kind_renders_sanely() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_sorts_categories_and_draws_the_cumulative_line() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
// A appears twice: Excel groups equal categories and sums them (A = 15).
|
||||
let cats = ["A", "B", "A", "C"];
|
||||
let vals = [10.0, 40.0, 5.0, 20.0];
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats.iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
let x_of = |label: &str| {
|
||||
prims.iter().find_map(|p| match p {
|
||||
Prim::Text { x, text, .. } if text == label => Some(*x),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let (a, b, cc) = (x_of("A").unwrap(), x_of("B").unwrap(), x_of("C").unwrap());
|
||||
assert!(b < cc && cc < a, "grouped and sorted largest first: B C A");
|
||||
// Three cumulative markers and the line itself.
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3);
|
||||
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
|
||||
let t = texts(&prims);
|
||||
assert!(t.contains(&"100%"), "right percentage axis labels: {t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_secondary_axis_is_fixed_at_100_percent() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let cats = ["A", "B", "C", "D", "E"];
|
||||
let vals = [50.0, 20.0, 10.0, 5.0, 15.0];
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats.iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
// The secondary axis runs 0–100%, so the cumulative line can use the plot's full height.
|
||||
let mut ticks: Vec<(f32, &str)> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Text { y, text, .. } if text.ends_with('%') => Some((*y, text.as_str())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
ticks.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let labels: Vec<&str> = ticks.iter().map(|(_, t)| *t).collect();
|
||||
// Top of the plot first: 100% down to 0%, with no 120% headroom.
|
||||
assert_eq!(labels, ["100%", "80%", "60%", "40%", "20%", "0%"], "fixed 0–100% axis with a 20% step");
|
||||
// Evenly spaced: 0.2 of the scale per step.
|
||||
let first = ticks.first().map(|(y, _)| *y).unwrap_or_default();
|
||||
let last = ticks.last().map(|(y, _)| *y).unwrap_or_default();
|
||||
let step = (last - first) / 5.0;
|
||||
for (i, (y, label)) in ticks.iter().enumerate() {
|
||||
assert!((first + step * i as f32 - y).abs() < 0.5, "{label} sits on its 0.2 step: {ticks:?}");
|
||||
}
|
||||
// The cumulative line's last point (100%) lands on the 100% tick, and A's 50% midway.
|
||||
let line = prims
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Line { pts, .. } if pts.len() == 5 => Some(pts.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("cumulative line");
|
||||
let top = first;
|
||||
let mid = (first + last) / 2.0;
|
||||
assert!((line[4][1] - top).abs() < 0.01, "line top {} on the 100% tick {top}", line[4][1]);
|
||||
assert!((line[0][1] - mid).abs() < 0.01, "A's 50% {} halfway up the axis ({mid})", line[0][1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_bins_numbers_when_there_is_no_category_range() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
c.series.push(Series { name: Some("Values".into()), values: "Data!$A$1:$A$6".into(), ..Default::default() });
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: vec![],
|
||||
series: vec![series("Values", &[1.0, 1.0, 1.0, 2.0, 2.0, 3.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3, "three bins");
|
||||
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
|
||||
let t = texts(&prims);
|
||||
assert!(t.iter().any(|s| s.starts_with('[') && s.contains(", ")), "bin labels: {t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_skips_cumulative_line_for_signed_categories() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: vec!["A".into(), "B".into()],
|
||||
series: vec![series("Count", &[10.0, -5.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
// A negative category makes the cumulative percentage meaningless, so no line or markers.
|
||||
// The cumulative line is the only 1.5 px polyline a Pareto draws (bars are rects, axes 0.75).
|
||||
let line = |prims: &[Prim]| prims.iter().any(|p| matches!(p, Prim::Line { pts, width, .. } if *width == 1.5 && pts.len() >= 2));
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
|
||||
assert!(!line(&prims), "signed categories draw no cumulative line");
|
||||
// The same chart with nonnegative values does draw it, so the check above can fail.
|
||||
let d = ChartData { series: vec![series("Count", &[10.0, 5.0], [20, 96, 130, 255], ChartKind::Pareto)], ..d };
|
||||
assert!(line(&render(&c, &d, 640.0, 400.0, &ApproxMeasure)), "nonnegative categories draw the cumulative line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_caps_cumulative_line_and_markers() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let n = MAX_MARKERS + 1000;
|
||||
let cats: Vec<String> = (0..n).map(|i| format!("C{i}")).collect();
|
||||
let vals: Vec<f64> = (0..n).map(|i| (i % 7 + 1) as f64).collect();
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats,
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
// Wide enough for markers: they stop at MAX_MARKERS.
|
||||
let wide = render(&c, &d, 30_000.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(wide.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), MAX_MARKERS);
|
||||
// Narrow columns carry no marker information; the line is decimated instead.
|
||||
let narrow = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(narrow.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
|
||||
let longest = narrow.iter().filter_map(|p| match p {
|
||||
Prim::Line { pts, .. } if pts.len() > 2 => Some(pts.len()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(longest.max().unwrap_or(0) < n, "the cumulative line is decimated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_legend_uses_the_supplied_label() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.legend = LegendPos::Bottom;
|
||||
let d = sample(ChartKind::Pareto);
|
||||
let entries = legend_entries_with(&c, &d, &ChartLabels { cumulative: "Kumuliert %" });
|
||||
assert!(entries.iter().any(|(name, _, sw)| name == "Kumuliert %" && *sw == Swatch::Line), "{entries:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_line_falls_back_to_the_second_theme_accent() {
|
||||
let c = chart(ChartKind::Pareto);
|
||||
// A resolved short palette (one series) has no second colour: the line must still stand
|
||||
// apart from the bars instead of reusing the first series colour.
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &[4.0, 3.0, 2.0, 1.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let accent = series_color(&gridcraft_model::Theme::default(), 1);
|
||||
assert_ne!(accent, d.series[0].color);
|
||||
let entries = legend_entries(&c, &d);
|
||||
assert_eq!(entries.get(1).map(|e| e.1), Some(accent), "the legend swatch matches the line");
|
||||
let lines: Vec<Rgba> = render(&c, &d, 640.0, 400.0, &ApproxMeasure)
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Line { color, width, .. } if *width == 1.5 => Some(*color),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(lines.contains(&accent), "{lines:?}");
|
||||
// A second palette colour still takes precedence.
|
||||
let d = ChartData { palette: vec![[1, 2, 3, 255], [9, 8, 7, 255]], ..d };
|
||||
assert_eq!(legend_entries(&c, &d).get(1).map(|e| e.1), Some([9, 8, 7, 255]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doughnut_draws_each_series_as_a_ring() {
|
||||
let mut c = chart(ChartKind::Doughnut);
|
||||
@@ -472,6 +666,7 @@ fn legend_counts() {
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Pie), &d).len(), 6);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Waterfall), &d).len(), 3);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Histogram), &d).len(), 0);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Pareto), &d).len(), 2);
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.legend = LegendPos::None;
|
||||
assert!(legend_entries(&c, &d).is_empty());
|
||||
|
||||
@@ -2,13 +2,32 @@
|
||||
//!
|
||||
//! Internally rows and columns are 0-based (`A1` = row 0, col 0). The sheet is 1,048,576 rows by
|
||||
//! 16,384 columns (`XFD1048576`), like Excel.
|
||||
//!
|
||||
//! # Excel's limits
|
||||
//!
|
||||
//! The constants below are Excel's documented limits (Microsoft's "Excel specifications and
|
||||
//! limits" page, the "Worksheet and workbook specifications" table). They are the size of the grid
|
||||
//! and the readers' bound of legitimate input: a file Excel wrote never exceeds them, so a part
|
||||
//! that does is malformed or crafted. The XLSX reader drops what the grid can't hold with a
|
||||
//! warning, and keeps text longer than a cell allows whole with one, since cutting it would lose
|
||||
//! data (the XLSB reader still refuses such text). Excel has raised
|
||||
//! these over the years (65,536 × 256 before Excel 2007) and may again; a new value goes here, and
|
||||
//! the places that still spell a number out (warning texts, a few function bounds) are pointed at
|
||||
//! these constants as they are touched. The old limits need no entry: a file written under them
|
||||
//! fits the current ones.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Rows in a sheet (`1048576` is the last row number).
|
||||
pub const MAX_ROWS: u32 = 1_048_576;
|
||||
/// Columns in a sheet (`XFD` is the last column).
|
||||
pub const MAX_COLS: u32 = 16_384;
|
||||
/// Characters in one cell's text, counted in UTF-16 units (a character outside the Basic
|
||||
/// Multilingual Plane counts as two). [`MAX_TEXT_CHARS`](crate::value::MAX_TEXT_CHARS), which
|
||||
/// `cap_text` and the functions use, is this value as a `usize`.
|
||||
pub const MAX_CELL_CHARS: u32 = 32_767;
|
||||
|
||||
/// A cell position (0-based).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
|
||||
|
||||
@@ -12,8 +12,8 @@ pub mod region;
|
||||
pub mod value;
|
||||
|
||||
pub use addr::{
|
||||
CategoryLevels, CellRef, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet, sheet_needs_quotes,
|
||||
split_areas, split_sheet, unquote_sheet,
|
||||
CategoryLevels, CellRef, MAX_CELL_CHARS, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet,
|
||||
sheet_needs_quotes, split_areas, split_sheet, unquote_sheet,
|
||||
};
|
||||
pub use date::DateSystem;
|
||||
pub use region::Region;
|
||||
|
||||
@@ -522,8 +522,9 @@ pub fn sci_text(n: f64, sig: usize) -> String {
|
||||
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
|
||||
}
|
||||
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub const MAX_TEXT_CHARS: usize = 32_767;
|
||||
/// Longest text a cell can hold, in UTF-16 code units: Excel's limit,
|
||||
/// [`MAX_CELL_CHARS`](crate::addr::MAX_CELL_CHARS), as a `usize`.
|
||||
pub const MAX_TEXT_CHARS: usize = crate::addr::MAX_CELL_CHARS as usize;
|
||||
|
||||
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
|
||||
pub fn cap_text(mut s: String) -> String {
|
||||
|
||||
@@ -326,6 +326,20 @@ impl<'a> Binder<'a> {
|
||||
return true;
|
||||
}
|
||||
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
|
||||
// `DATEADD`'s, `DATESINPERIOD`'s and `PARALLELPERIOD`'s interval is catalogued as
|
||||
// `Text` but is a documented enumeration, so neither a variable nor a model table
|
||||
// or measure named `MONTH` may replace the written keyword: `DATEADD(d, 1, MONTH)`,
|
||||
// `DATESINPERIOD(d, s, -1, MONTH)` and `PARALLELPERIOD(d, -1, MONTH)` shift by the
|
||||
// written interval. `WEEK` and `DAY` are not every function's interval vocabulary.
|
||||
let interval_keyword = match (spec.name, index) {
|
||||
("DATEADD", 2) => ["DAY", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
("DATESINPERIOD", 3) => ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
("PARALLELPERIOD", 2) => ["MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
_ => false,
|
||||
};
|
||||
if interval_keyword {
|
||||
return true;
|
||||
}
|
||||
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
|
||||
!named && !variable
|
||||
});
|
||||
|
||||
@@ -39,19 +39,19 @@ mod support;
|
||||
// marker line in both lists, in `ALL_FAMILIES` order, so a family branch replaces exactly its own
|
||||
// line instead of inserting at a shared anchor and conflicting with its siblings.
|
||||
mod aggregation;
|
||||
// date_time
|
||||
mod date_time;
|
||||
// filter
|
||||
// financial
|
||||
mod information;
|
||||
mod logical;
|
||||
// math_trig
|
||||
mod math_trig;
|
||||
mod model_info;
|
||||
// other
|
||||
// parent_child
|
||||
// statistical
|
||||
// table_manipulation
|
||||
// text
|
||||
// time_intelligence
|
||||
mod time_intelligence;
|
||||
// visual
|
||||
|
||||
use std::cmp::Ordering;
|
||||
@@ -108,19 +108,19 @@ pub const ALL_FAMILIES: &[&str] = &[
|
||||
/// own marker line below with its `Family` entry.
|
||||
const FAMILIES: &[Family] = &[
|
||||
Family { name: "aggregation", scalar: aggregation::call, table: aggregation::call_table },
|
||||
// date_time
|
||||
Family { name: "date_time", scalar: date_time::call, table: date_time::call_table },
|
||||
// filter
|
||||
// financial
|
||||
Family { name: "information", scalar: information::call, table: information::call_table },
|
||||
Family { name: "logical", scalar: logical::call, table: logical::call_table },
|
||||
// math_trig
|
||||
Family { name: "math_trig", scalar: math_trig::call, table: math_trig::call_table },
|
||||
Family { name: "model_info", scalar: model_info::call, table: model_info::call_table },
|
||||
// other
|
||||
// parent_child
|
||||
// statistical
|
||||
// table_manipulation
|
||||
// text
|
||||
// time_intelligence
|
||||
Family { name: "time_intelligence", scalar: time_intelligence::call, table: time_intelligence::call_table },
|
||||
// visual
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
//! Date and time functions.
|
||||
//!
|
||||
//! Dates are OLE/Excel serials (`Scalar::DateTime`), the same values Excel stores: whole days
|
||||
//! since 1899-12-30 plus a fraction for the time of day. The scalar functions follow Excel's
|
||||
//! documented results (`WEEKNUM` return types, `YEARFRAC` day-count bases, `NETWORKDAYS` weekend
|
||||
//! codes), and the table functions build date tables from literal bounds or from the model's
|
||||
//! DateTime columns.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::time_intelligence::is_date_type;
|
||||
use super::*;
|
||||
|
||||
/// Last serial Excel/DAX accepts as a date: 9999-12-31.
|
||||
const MAX_DATE_SERIAL: f64 = 2_958_465.0;
|
||||
|
||||
/// Hard ceiling for date tables built row-by-row by `CALENDAR`/`CALENDARAUTO`. It mirrors the
|
||||
/// `MAX_GENERATED_ROWS` limit in `eval::table_manipulation` (which is private to that module),
|
||||
/// so a pathological date span fails like every other oversized generated table instead of
|
||||
/// exhausting memory.
|
||||
const MAX_GENERATED_ROWS: i64 = 1_000_000;
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let upper = name.to_ascii_uppercase();
|
||||
let result = match upper.as_str() {
|
||||
"DATEDIFF" => datediff(ev, args, ctx),
|
||||
"DATEVALUE" => datevalue(ev, args, ctx),
|
||||
"TIME" => time(ev, args, ctx),
|
||||
"WEEKDAY" => weekday(ev, args, ctx),
|
||||
"NETWORKDAYS" => networkdays(ev, args, ctx),
|
||||
"NOW" => now(),
|
||||
"QUARTER" => quarter(ev, args, ctx),
|
||||
"TIMEVALUE" => timevalue(ev, args, ctx),
|
||||
"TODAY" => today(),
|
||||
"UTCNOW" => utc_now(),
|
||||
"UTCTODAY" => utc_today(),
|
||||
"WEEKNUM" => weeknum(ev, args, ctx),
|
||||
"YEARFRAC" => yearfrac(ev, args, ctx),
|
||||
// Table functions only make sense where a table is expected. Returning an explanatory
|
||||
// error beats reporting them as unimplemented when they appear in a scalar context.
|
||||
"CALENDAR" | "CALENDARAUTO" => Err(EvalError::new(format!("{upper} returns a table, not a scalar value"))),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
let upper = name.to_ascii_uppercase();
|
||||
let result = match upper.as_str() {
|
||||
"CALENDAR" => calendar(ev, args, ctx),
|
||||
"CALENDARAUTO" => calendar_auto(ev, args, ctx),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Argument coercion
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Coerces a scalar to a date serial. BLANK is 0 like every other DAX numeric coercion, text is
|
||||
/// read with the shared date/time parser first (so `DATEDIFF` keeps the time of day a text
|
||||
/// argument carries) and with `DATEVALUE`'s whole-day forms only for the shapes that parser
|
||||
/// rejects, and numbers are already serials.
|
||||
fn coerce_date(value: &Scalar) -> Option<f64> {
|
||||
match value {
|
||||
Scalar::Blank => Some(0.0),
|
||||
Scalar::String(text) => support::parse_date_text(text)
|
||||
.or_else(|| parse_date_serial(text))
|
||||
.or_else(|| text.trim().parse::<f64>().ok().filter(|serial| serial.is_finite())),
|
||||
other => other.to_number().filter(|serial| serial.is_finite()),
|
||||
}
|
||||
}
|
||||
|
||||
fn date_arg(name: &str, values: &[Scalar], index: usize) -> Result<f64, EvalError> {
|
||||
let value = values.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let serial = coerce_date(value).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))?;
|
||||
// Validating the range bounds every date loop (NETWORKDAYS, YEARFRAC) by the calendar.
|
||||
if !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
|
||||
return Err(EvalError::new(format!("{name} argument {} is outside the supported date range", index + 1)));
|
||||
}
|
||||
Ok(serial)
|
||||
}
|
||||
|
||||
fn optional_int(name: &str, values: &[Scalar], index: usize, default: i64) -> Result<i64, EvalError> {
|
||||
match values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
|
||||
Ok(number as i64)
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text parsing
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Splits `DATE[ T]TIME` text at the first `T` or space. A string without a separator is all
|
||||
/// date (or all time); the caller decides which.
|
||||
fn split_date_time(text: &str) -> (&str, Option<&str>) {
|
||||
match text.split_once(['T', ' ']) {
|
||||
Some((date, time)) => (date.trim(), Some(time.trim())),
|
||||
None => (text.trim(), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the date forms `DATEVALUE` accepts on a US-locale client: `YYYY-MM-DD`, `YYYY/MM/DD`,
|
||||
/// `MM/DD/YYYY` (two-digit years add 2000 below 30 and 1900 otherwise) and the same dates with a
|
||||
/// trailing time. Returns whole-day serials; the time of day is ignored.
|
||||
fn parse_date_serial(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date_part, _) = split_date_time(text);
|
||||
let parts: Vec<&str> = date_part.split(['-', '/']).filter(|part| !part.is_empty()).collect();
|
||||
if parts.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
let numbers: Option<Vec<i64>> = parts.iter().map(|part| part.parse::<i64>().ok()).collect();
|
||||
let numbers = numbers?;
|
||||
let leading_year = parts[0].len() >= 4 && parts[0].chars().all(|c| c.is_ascii_digit());
|
||||
if leading_year {
|
||||
// ISO order. The shared parser already knows this shape; re-reading the parts rejects
|
||||
// impossible dates (2024-02-30) that its serial rollover would silently accept.
|
||||
let serial = support::parse_date_text(date_part)?;
|
||||
if support::date_parts(serial) != (numbers[0], numbers[1], numbers[2]) || !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
|
||||
return None;
|
||||
}
|
||||
return Some(serial.floor());
|
||||
}
|
||||
// Month-first order, the default of the documented en-US client.
|
||||
let (mut year, month, day) = (numbers[2], numbers[0], numbers[1]);
|
||||
if year < 100 {
|
||||
year += if year < 30 { 2000 } else { 1900 };
|
||||
}
|
||||
if !(1..=12).contains(&month) || day < 1 || day > support::days_in_month(year, month) {
|
||||
return None;
|
||||
}
|
||||
let serial = support::date_serial(year, month, day, 0, 0, 0);
|
||||
(0.0..=MAX_DATE_SERIAL).contains(&serial).then_some(serial)
|
||||
}
|
||||
|
||||
/// Parses a clock time into a day fraction: `HH:MM`, `HH:MM:SS`, fractional seconds optional, and
|
||||
/// an `AM`/`PM` suffix on a 12-hour clock.
|
||||
fn parse_clock(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let upper = text.to_ascii_uppercase();
|
||||
let (clock, meridiem) = if let Some(rest) = upper.strip_suffix("PM") {
|
||||
(rest.trim(), Some(true))
|
||||
} else if let Some(rest) = upper.strip_suffix("AM") {
|
||||
(rest.trim(), Some(false))
|
||||
} else {
|
||||
(text, None)
|
||||
};
|
||||
let parts: Vec<&str> = clock.split(':').collect();
|
||||
if parts.len() < 2 || parts.len() > 3 {
|
||||
return None;
|
||||
}
|
||||
let hour: i64 = parts[0].trim().parse().ok()?;
|
||||
let minute: i64 = parts[1].trim().parse().ok()?;
|
||||
let second: f64 = match parts.get(2) {
|
||||
Some(part) => part.trim().parse().ok()?,
|
||||
None => 0.0,
|
||||
};
|
||||
if !(0..=59).contains(&minute) || !(0.0..60.0).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
let hour = match meridiem {
|
||||
Some(pm) => {
|
||||
if !(1..=12).contains(&hour) {
|
||||
return None;
|
||||
}
|
||||
match (hour, pm) {
|
||||
(12, true) => 12,
|
||||
(12, false) => 0,
|
||||
(hour, true) => hour + 12,
|
||||
(hour, false) => hour,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !(0..=23).contains(&hour) {
|
||||
return None;
|
||||
}
|
||||
hour
|
||||
}
|
||||
};
|
||||
Some((hour as f64 * 3600.0 + minute as f64 * 60.0 + second) / 86_400.0)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Scalars
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `DATEVALUE ( <DateText> )` — the date part of a text date as a whole-day serial.
|
||||
fn datevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let value = values.first().ok_or_else(|| EvalError::new("DATEVALUE is missing argument 1"))?;
|
||||
if let Scalar::DateTime(serial) = value {
|
||||
return Ok(Scalar::DateTime(serial.floor()));
|
||||
}
|
||||
let text = value.to_text();
|
||||
let serial = parse_date_serial(&text).ok_or_else(|| EvalError::new(format!("DATEVALUE cannot convert `{text}` to a date")))?;
|
||||
Ok(Scalar::DateTime(serial))
|
||||
}
|
||||
|
||||
/// `DATEDIFF ( <Date1>, <Date2>, <Interval> )`: the number of interval boundaries crossed between
|
||||
/// the two dates, positively when Date2 is later. `Interval` is a keyword (the binder keeps it as
|
||||
/// a keyword expression, which evaluates to its text).
|
||||
fn datediff(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("DATEDIFF", &values, 0)?;
|
||||
let end = date_arg("DATEDIFF", &values, 1)?;
|
||||
let interval = values.get(2).ok_or_else(|| EvalError::new("DATEDIFF is missing argument 3"))?.to_text();
|
||||
let (start_year, start_month, _) = support::date_parts(start);
|
||||
let (end_year, end_month, _) = support::date_parts(end);
|
||||
// Sub-day intervals count boundaries, not elapsed time: floor each serial to the unit and
|
||||
// subtract, so `10:59:59` to `11:00:01` is one HOUR even though only two seconds passed.
|
||||
// Snap to whole seconds first: serial construction can land a hair below an exact second,
|
||||
// and flooring that would count one boundary too few.
|
||||
let boundaries = |serial: f64, per_day: f64| {
|
||||
let seconds = (serial * 86_400.0).round();
|
||||
(seconds / (86_400.0 / per_day)).floor()
|
||||
};
|
||||
// A week starts on Sunday; serial 1 (1900-01-01) is Excel's first Sunday, so week 0 starts
|
||||
// there and every seven days is another boundary.
|
||||
let week = |serial: f64| (serial.floor() - 1.0).div_euclid(7.0);
|
||||
let count = match interval.trim().to_ascii_uppercase().as_str() {
|
||||
"SECOND" => boundaries(end, 86_400.0) - boundaries(start, 86_400.0),
|
||||
"MINUTE" => boundaries(end, 1_440.0) - boundaries(start, 1_440.0),
|
||||
"HOUR" => boundaries(end, 24.0) - boundaries(start, 24.0),
|
||||
"DAY" => end.floor() - start.floor(),
|
||||
"WEEK" => week(end) - week(start),
|
||||
"MONTH" => ((end_year - start_year) * 12 + (end_month - start_month)) as f64,
|
||||
"QUARTER" => ((end_year - start_year) * 4 + (end_month - 1) / 3 - (start_month - 1) / 3) as f64,
|
||||
"YEAR" => (end_year - start_year) as f64,
|
||||
other => {
|
||||
return Err(EvalError::new(format!("DATEDIFF interval `{other}` must be SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR")));
|
||||
}
|
||||
};
|
||||
if !count.is_finite() || count.abs() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("DATEDIFF result is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(Scalar::Integer(count as i64))
|
||||
}
|
||||
|
||||
/// `TIME ( <Hour>, <Minute>, <Second> )`: a time on the 1899-12-30 epoch. Each argument is capped
|
||||
/// at 32,767 and the total wraps inside one day, as the catalog documents (`TIME ( 50, 0, 0 )` is
|
||||
/// 02:00, not 02:00 the next day).
|
||||
fn time(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
const MAX_TIME_PART: f64 = 32_767.0;
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let mut parts = [0.0f64; 3];
|
||||
for (index, part) in parts.iter_mut().enumerate() {
|
||||
let value = values.get(index).ok_or_else(|| EvalError::new(format!("TIME is missing argument {}", index + 1)))?.to_number();
|
||||
let value = value.filter(|value| value.is_finite()).ok_or_else(|| EvalError::new(format!("TIME argument {} must be numeric", index + 1)))?;
|
||||
if !(0.0..=MAX_TIME_PART).contains(&value) {
|
||||
return Err(EvalError::new(format!("TIME argument {} must be between 0 and 32767", index + 1)));
|
||||
}
|
||||
*part = value;
|
||||
}
|
||||
let seconds = parts[0] * 3_600.0 + parts[1] * 60.0 + parts[2];
|
||||
Ok(Scalar::DateTime(seconds.rem_euclid(86_400.0) / 86_400.0))
|
||||
}
|
||||
|
||||
/// `WEEKDAY ( <Date> [, <ReturnType>] )`: return type 1 numbers Sunday 1 through Saturday 7,
|
||||
/// 2 numbers Monday 1 through Sunday 7, 3 numbers Monday 0 through Sunday 6, and 11-17 start the
|
||||
/// week on Monday through Sunday with the first day numbered 1.
|
||||
fn weekday(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("WEEKDAY", &values, 0)?;
|
||||
let return_type = optional_int("WEEKDAY", &values, 1, 1)?;
|
||||
// Days since the epoch, 1899-12-30 was a Saturday, so serial 0 is Saturday and the
|
||||
// zero-based day of week with Sunday first is (days + 6) mod 7.
|
||||
let days = serial.floor() as i64;
|
||||
let sunday_first = (days + 6).rem_euclid(7);
|
||||
let index = match return_type {
|
||||
1 => sunday_first + 1,
|
||||
2 => (sunday_first + 6).rem_euclid(7) + 1,
|
||||
3 => (sunday_first + 6).rem_euclid(7),
|
||||
11..=17 => {
|
||||
// The first day of the week is Monday for 11 through Sunday for 17.
|
||||
let first = (return_type - 10).rem_euclid(7);
|
||||
(sunday_first - first).rem_euclid(7) + 1
|
||||
}
|
||||
other => {
|
||||
return Err(EvalError::new(format!("WEEKDAY return type `{other}` must be 1, 2, 3 or 11 to 17")));
|
||||
}
|
||||
};
|
||||
Ok(Scalar::Integer(index))
|
||||
}
|
||||
|
||||
/// `TIMEVALUE ( <TimeText> )` — the time of day as a fraction, ignoring any date portion.
|
||||
fn timevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let value = values.first().ok_or_else(|| EvalError::new("TIMEVALUE is missing argument 1"))?;
|
||||
if let Scalar::DateTime(serial) = value {
|
||||
return Ok(Scalar::DateTime(serial.rem_euclid(1.0)));
|
||||
}
|
||||
let text = value.to_text();
|
||||
let fraction = parse_time_text(&text).ok_or_else(|| EvalError::new(format!("TIMEVALUE cannot convert `{text}` to a time")))?;
|
||||
Ok(Scalar::DateTime(fraction))
|
||||
}
|
||||
|
||||
fn parse_time_text(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date_part, time_part) = split_date_time(text);
|
||||
if parse_date_serial(date_part).is_some() {
|
||||
// A full date-time string keeps only its time; a date alone is midnight.
|
||||
return match time_part {
|
||||
Some(time) => parse_clock(time),
|
||||
None => Some(0.0),
|
||||
};
|
||||
}
|
||||
parse_clock(text)
|
||||
}
|
||||
|
||||
/// `QUARTER ( <Date> )` — 1 (January-March) through 4 (October-December).
|
||||
fn quarter(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("QUARTER", &values, 0)?;
|
||||
let (_, month, _) = support::date_parts(serial);
|
||||
Ok(Scalar::Integer((month - 1).div_euclid(3) + 1))
|
||||
}
|
||||
|
||||
/// `WEEKNUM ( <Date> [, <ReturnType>] )`.
|
||||
///
|
||||
/// Return types 1 and 2-17 use week system 1 (the week containing January 1 is week 1) with the
|
||||
/// week starting on Sunday (1), Monday (2, 11), Tuesday (12), Wednesday (13), Thursday (14),
|
||||
/// Friday (15), Saturday (16) or Sunday (17). Return type 21 is ISO 8601, where the week with the
|
||||
/// first Thursday is week 1 and the result follows the ISO week even across a year boundary.
|
||||
fn weeknum(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("WEEKNUM", &values, 0)?.floor();
|
||||
let return_type = optional_int("WEEKNUM", &values, 1, 1)?;
|
||||
let week = match return_type {
|
||||
21 => iso_week(serial),
|
||||
1 => week_system1(serial, 7),
|
||||
2 | 11 => week_system1(serial, 1),
|
||||
12 => week_system1(serial, 2),
|
||||
13 => week_system1(serial, 3),
|
||||
14 => week_system1(serial, 4),
|
||||
15 => week_system1(serial, 5),
|
||||
16 => week_system1(serial, 6),
|
||||
17 => week_system1(serial, 7),
|
||||
other => return Err(EvalError::new(format!("WEEKNUM return type {other} is not supported"))),
|
||||
};
|
||||
Ok(Scalar::Integer(week))
|
||||
}
|
||||
|
||||
/// Week number in week system 1 for a week starting on `week_start` (Monday 1 .. Sunday 7).
|
||||
fn week_system1(serial: f64, week_start: i64) -> i64 {
|
||||
let (year, _, _) = support::date_parts(serial);
|
||||
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0);
|
||||
let day_of_year = (serial - jan1) as i64 + 1;
|
||||
let lead = (iso_weekday(jan1) - week_start).rem_euclid(7);
|
||||
(day_of_year + lead - 1).div_euclid(7) + 1
|
||||
}
|
||||
|
||||
/// ISO 8601 week number. Dates that belong to the neighbouring ISO year report that year's week
|
||||
/// number (2021-01-01 is week 53, 2018-12-31 is week 1), matching Excel's return type 21.
|
||||
fn iso_week(serial: f64) -> i64 {
|
||||
// The Thursday of the week decides the ISO year: week 1 is the week that contains it.
|
||||
let thursday = serial as i64 - iso_weekday(serial) + 4;
|
||||
let year = if thursday < 1 { 1900 } else { support::date_parts(thursday as f64).0 };
|
||||
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0) as i64;
|
||||
(thursday - jan1).div_euclid(7) + 1
|
||||
}
|
||||
|
||||
/// Weekday with Monday 1 .. Sunday 7. The shared helper returns Excel's default Sunday-first
|
||||
/// numbering (`date_weekday`), which week-number arithmetic and NETWORKDAYS do not use.
|
||||
fn iso_weekday(serial: f64) -> i64 {
|
||||
((support::date_weekday(serial) + 5) % 7) + 1
|
||||
}
|
||||
|
||||
/// `YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] )`.
|
||||
///
|
||||
/// Basis 0 is US (NASD) 30/360, 1 actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360,
|
||||
/// matching Excel's `YEARFRAC` (the same rules the worksheet engine in `crates/functions` uses).
|
||||
/// Excel ignores the argument order and returns the positive fraction for a reversed pair.
|
||||
fn yearfrac(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("YEARFRAC", &values, 0)?.floor();
|
||||
let end = date_arg("YEARFRAC", &values, 1)?.floor();
|
||||
let basis = optional_int("YEARFRAC", &values, 2, 0)?;
|
||||
if !(0..=4).contains(&basis) {
|
||||
return Err(EvalError::new(format!("YEARFRAC basis {basis} is not supported")));
|
||||
}
|
||||
let (start, end) = if start <= end { (start, end) } else { (end, start) };
|
||||
let (year1, month1, day1) = support::date_parts(start);
|
||||
let (year2, month2, day2) = support::date_parts(end);
|
||||
let days = end - start;
|
||||
let fraction = match basis {
|
||||
0 => {
|
||||
let mut day1 = day1;
|
||||
let mut day2 = day2;
|
||||
let start_feb_end = month1 == 2 && day1 == support::days_in_month(year1, 2);
|
||||
let end_feb_end = month2 == 2 && day2 == support::days_in_month(year2, 2);
|
||||
if day1 == 31 && day2 == 31 {
|
||||
day1 = 30;
|
||||
day2 = 30;
|
||||
} else if day1 == 31 {
|
||||
day1 = 30;
|
||||
} else if day1 == 30 && day2 == 31 {
|
||||
day2 = 30;
|
||||
} else if start_feb_end && end_feb_end {
|
||||
day1 = 30;
|
||||
day2 = 30;
|
||||
} else if start_feb_end {
|
||||
day1 = 30;
|
||||
}
|
||||
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
|
||||
}
|
||||
1 => {
|
||||
let within_year = year1 == year2 || (year2 == year1 + 1 && (month1 > month2 || (month1 == month2 && day1 >= day2)));
|
||||
let year_length = if within_year {
|
||||
let leap_day_between =
|
||||
(year1..=year2).any(|year| support::is_leap_year(year) && (start..=end).contains(&support::date_serial(year, 2, 29, 0, 0, 0)));
|
||||
if (year1 == year2 && support::is_leap_year(year1)) || leap_day_between || (month2 == 2 && day2 == 29) { 366.0 } else { 365.0 }
|
||||
} else {
|
||||
let years = (year2 - year1 + 1) as f64;
|
||||
let span = support::date_serial(year2 + 1, 1, 1, 0, 0, 0) - support::date_serial(year1, 1, 1, 0, 0, 0);
|
||||
span / years
|
||||
};
|
||||
days / year_length
|
||||
}
|
||||
2 => days / 360.0,
|
||||
3 => days / 365.0,
|
||||
_ => {
|
||||
let day1 = day1.min(30);
|
||||
let day2 = day2.min(30);
|
||||
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
|
||||
}
|
||||
};
|
||||
Ok(Scalar::Decimal(fraction))
|
||||
}
|
||||
|
||||
/// `NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] )` — whole working days,
|
||||
/// both ends included. Weekend codes are 1 (Saturday/Sunday, the default), 2-7 for the pairs
|
||||
/// starting on Sunday through Friday, and 11-17 for a single day starting on Sunday. A reversed
|
||||
/// range returns the negative count, as Excel does.
|
||||
fn networkdays(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
// The optional holidays argument is a table, so it cannot go through eager scalar evaluation.
|
||||
let scalars = args.iter().take(3).map(|arg| ev.eval(arg, ctx)).collect::<Result<Vec<_>, EvalError>>()?;
|
||||
let start = date_arg("NETWORKDAYS", &scalars, 0)?.floor();
|
||||
let end = date_arg("NETWORKDAYS", &scalars, 1)?.floor();
|
||||
let code = optional_int("NETWORKDAYS", &scalars, 2, 1)?;
|
||||
let weekends = weekend_days(code)?;
|
||||
let holidays = match args.get(3) {
|
||||
Some(expr) => {
|
||||
let table = support::eval_table(ev, expr, ctx)?;
|
||||
holiday_days(&table)?
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
};
|
||||
let (start, end, sign) = if start <= end { (start, end, 1) } else { (end, start, -1) };
|
||||
let mut count = 0i64;
|
||||
let mut day = start as i64;
|
||||
let last = end as i64;
|
||||
while day <= last {
|
||||
let weekday = iso_weekday(day as f64) as usize;
|
||||
if !weekends[weekday] && !holidays.contains(&day) {
|
||||
count += 1;
|
||||
}
|
||||
day += 1;
|
||||
}
|
||||
Ok(Scalar::Integer(sign * count))
|
||||
}
|
||||
|
||||
/// Weekend lookup indexed by weekday (Monday 1 .. Sunday 7).
|
||||
fn weekend_days(code: i64) -> Result<[bool; 8], EvalError> {
|
||||
let mut days = [false; 8];
|
||||
match code {
|
||||
1..=7 => {
|
||||
let first = ((code + 4) % 7) + 1;
|
||||
days[first as usize] = true;
|
||||
days[(first % 7 + 1) as usize] = true;
|
||||
}
|
||||
11..=17 => {
|
||||
days[(((code - 11 + 6) % 7) + 1) as usize] = true;
|
||||
}
|
||||
other => return Err(EvalError::new(format!("NETWORKDAYS weekend code {other} is not supported"))),
|
||||
}
|
||||
Ok(days)
|
||||
}
|
||||
|
||||
fn holiday_days(table: &TableValue) -> Result<BTreeSet<i64>, EvalError> {
|
||||
let mut days = BTreeSet::new();
|
||||
if table.columns.is_empty() {
|
||||
return Ok(days);
|
||||
}
|
||||
for row in &table.rows {
|
||||
let Some(value) = row.first() else { continue };
|
||||
if value.is_blank() {
|
||||
continue;
|
||||
}
|
||||
let serial = coerce_date(value).ok_or_else(|| EvalError::new("NETWORKDAYS holidays must be dates"))?;
|
||||
days.insert(serial.floor() as i64);
|
||||
}
|
||||
Ok(days)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Clock
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `NOW ()` — the current date and time. The clock is read once per evaluation and uses the
|
||||
/// host's local timezone, as Excel does.
|
||||
fn now() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::now_serial()))
|
||||
}
|
||||
|
||||
/// `TODAY ()` — the current local date at midnight.
|
||||
fn today() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::today_serial()))
|
||||
}
|
||||
|
||||
/// `UTCNOW ()` — the current Coordinated Universal Time date and time.
|
||||
fn utc_now() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::utc_now_serial()))
|
||||
}
|
||||
|
||||
/// `UTCTODAY ()` — the current UTC date at midnight.
|
||||
fn utc_today() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::utc_today_serial()))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Tables
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `CALENDAR ( <StartDate>, <EndDate> )` — one `Date` column with every day in the closed range.
|
||||
fn calendar(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("CALENDAR", &values, 0)?.floor();
|
||||
let end = date_arg("CALENDAR", &values, 1)?.floor();
|
||||
date_table(start, end, "CALENDAR")
|
||||
}
|
||||
|
||||
/// `CALENDARAUTO ( [<FiscalYearEndMonth>] )` — a contiguous date table covering the whole fiscal
|
||||
/// years spanned by the model's DateTime columns.
|
||||
fn calendar_auto(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let fiscal_end = optional_int("CALENDARAUTO", &values, 0, 12)?;
|
||||
if !(1..=12).contains(&fiscal_end) {
|
||||
return Err(EvalError::new("CALENDARAUTO FiscalYearEndMonth must be between 1 and 12"));
|
||||
}
|
||||
let mut bounds: Option<(f64, f64)> = None;
|
||||
for table in &ev.model().tables {
|
||||
for (index, column) in table.columns.iter().enumerate() {
|
||||
let is_datetime = column.data_type.as_deref().is_some_and(is_date_type);
|
||||
if !is_datetime {
|
||||
continue;
|
||||
}
|
||||
for row in &table.rows {
|
||||
let Some(value) = row.get(index) else { continue };
|
||||
if value.is_blank() {
|
||||
continue;
|
||||
}
|
||||
let Some(serial) = coerce_date(value) else { continue };
|
||||
let serial = serial.floor();
|
||||
bounds = Some(match bounds {
|
||||
Some((min, max)) => (min.min(serial), max.max(serial)),
|
||||
None => (serial, serial),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((min, max)) = bounds else {
|
||||
return Err(EvalError::new("CALENDARAUTO requires a model with at least one DateTime column"));
|
||||
};
|
||||
let start = fiscal_year_start(min, fiscal_end);
|
||||
let end = fiscal_year_end(max, fiscal_end);
|
||||
date_table(start, end, "CALENDARAUTO")
|
||||
}
|
||||
|
||||
/// First day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
|
||||
fn fiscal_year_start(serial: f64, end_month: i64) -> f64 {
|
||||
let (year, month, _) = support::date_parts(serial);
|
||||
let fiscal_year = if month <= end_month { year } else { year + 1 };
|
||||
support::date_serial(fiscal_year - 1, end_month + 1, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Last day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
|
||||
fn fiscal_year_end(serial: f64, end_month: i64) -> f64 {
|
||||
let (year, month, _) = support::date_parts(serial);
|
||||
let fiscal_year = if month <= end_month { year } else { year + 1 };
|
||||
support::date_serial(fiscal_year, end_month, support::days_in_month(fiscal_year, end_month), 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Builds the one-column `Date` table shared by CALENDAR and CALENDARAUTO.
|
||||
fn date_table(start: f64, end: f64, name: &str) -> Result<TableValue, EvalError> {
|
||||
if end < start {
|
||||
return Err(EvalError::new(format!("{name} requires the start date to be on or before the end date")));
|
||||
}
|
||||
if start < 0.0 || end > MAX_DATE_SERIAL {
|
||||
return Err(EvalError::new(format!("{name} dates must be between 1899-12-30 and 9999-12-31")));
|
||||
}
|
||||
let count = (end - start) as i64 + 1;
|
||||
if count > MAX_GENERATED_ROWS {
|
||||
return Err(EvalError::new(format!("{name} result is too large")));
|
||||
}
|
||||
let rows = (0..count).map(|offset| vec![Scalar::DateTime(start + offset as f64)]).collect();
|
||||
Ok(TableValue::new(vec![TableColumn { name: "Date".into() }], rows))
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! Math and trigonometry functions.
|
||||
//!
|
||||
//! The inverse trigonometric and hyperbolic families follow Excel's domains: a value outside the
|
||||
//! documented range raises an error instead of returning NaN. `CONVERT` follows the catalog and
|
||||
//! dax.guide, i.e. `CONVERT ( <Expression>, <DataType> )` with a bare type keyword.
|
||||
//!
|
||||
//! `RAND`/`RANDBETWEEN` use a local xorshift64* generator seeded from the clock (`js_sys::Date` on
|
||||
//! wasm, where `SystemTime::now` traps) and a per-call salt; the catalog already flags both
|
||||
//! functions as volatile.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::support::{args as arg_values, eval_all, parse_date_text, round_direction};
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
match name.as_str() {
|
||||
"ACOS" | "ACOSH" | "ACOT" | "ACOTH" | "ASIN" | "ASINH" | "ATAN" | "ATANH" | "CONVERT" | "COSH" | "COT" | "COTH" | "CURRENCY" | "EVEN"
|
||||
| "MOD" | "MROUND" | "ODD" | "QUOTIENT" | "RAND" | "RANDBETWEEN" | "ROUNDDOWN" | "SINH" | "SQRTPI" | "TANH" => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(evaluate(&name, ev, args, ctx))
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn evaluate(name: &str, ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values(name, &values);
|
||||
match name {
|
||||
"ACOS" => {
|
||||
let x = domain_number(&a, -1.0, 1.0)?;
|
||||
Ok(Scalar::Decimal(x.acos()))
|
||||
}
|
||||
"ACOSH" => {
|
||||
let x = domain_number(&a, 1.0, f64::INFINITY)?;
|
||||
Ok(Scalar::Decimal(x.acosh()))
|
||||
}
|
||||
"ACOT" => {
|
||||
// Principal value in (0, pi), unlike ATAN's (-pi/2, pi/2).
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(std::f64::consts::FRAC_PI_2 - x.atan()))
|
||||
}
|
||||
"ACOTH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x.abs() <= 1.0 {
|
||||
return Err(EvalError::new("ACOTH argument must have an absolute value greater than 1"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(0.5 * ((x + 1.0) / (x - 1.0)).ln(), name)?))
|
||||
}
|
||||
"ASIN" => {
|
||||
let x = domain_number(&a, -1.0, 1.0)?;
|
||||
Ok(Scalar::Decimal(x.asin()))
|
||||
}
|
||||
"ASINH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.asinh()))
|
||||
}
|
||||
"ATAN" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.atan()))
|
||||
}
|
||||
"ATANH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x <= -1.0 || x >= 1.0 {
|
||||
return Err(EvalError::new("ATANH argument must be greater than -1 and less than 1"));
|
||||
}
|
||||
Ok(Scalar::Decimal(x.atanh()))
|
||||
}
|
||||
"CONVERT" => convert(&values),
|
||||
"COSH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(finite(x.cosh(), name)?))
|
||||
}
|
||||
"COT" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
let tangent = x.tan();
|
||||
if tangent == 0.0 {
|
||||
return Err(EvalError::new("COT is undefined at multiples of pi"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
|
||||
}
|
||||
"COTH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
let tangent = x.tanh();
|
||||
if tangent == 0.0 {
|
||||
return Err(EvalError::new("COTH is undefined at zero"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
|
||||
}
|
||||
"CURRENCY" => currency(a.arg(0)?),
|
||||
"EVEN" => Ok(Scalar::Integer(round_away_to_even(finite(a.number(0)?, name)?)?)),
|
||||
"MROUND" => {
|
||||
let number = finite(a.number(0)?, name)?;
|
||||
let multiple = finite(a.number(1)?, name)?;
|
||||
Ok(Scalar::Decimal(mround(number, multiple)?))
|
||||
}
|
||||
"MOD" => modulo(a.arg(0)?, a.arg(1)?),
|
||||
// ROUNDDOWN rounds toward zero (support::round_direction), so negatives go up.
|
||||
"ROUNDDOWN" => Ok(Scalar::Decimal(round_direction(finite(a.number(0)?, name)?, a.number(1)? as i32, false))),
|
||||
"ODD" => Ok(Scalar::Integer(round_away_to_odd(finite(a.number(0)?, name)?)?)),
|
||||
"QUOTIENT" => {
|
||||
let numerator = finite(a.number(0)?, name)?;
|
||||
let denominator = finite(a.number(1)?, name)?;
|
||||
if denominator == 0.0 {
|
||||
return Err(EvalError::new("QUOTIENT denominator must not be zero"));
|
||||
}
|
||||
Ok(Scalar::Integer(truncate_i64(finite(numerator / denominator, name)?)?))
|
||||
}
|
||||
"RAND" => Ok(Scalar::Decimal(next_random_fraction())),
|
||||
"RANDBETWEEN" => {
|
||||
let bottom = truncate_i64(finite(a.number(0)?, name)?)?;
|
||||
let top = truncate_i64(finite(a.number(1)?, name)?)?;
|
||||
if bottom > top {
|
||||
return Err(EvalError::new("RANDBETWEEN bottom must not be greater than top"));
|
||||
}
|
||||
let span = (top as i128) - (bottom as i128) + 1;
|
||||
let offset = (next_random_u64() as u128 % span as u128) as i128;
|
||||
Ok(Scalar::Integer((bottom as i128 + offset) as i64))
|
||||
}
|
||||
"SINH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(finite(x.sinh(), name)?))
|
||||
}
|
||||
"SQRTPI" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x < 0.0 {
|
||||
return Err(EvalError::new("SQRTPI argument must not be negative"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite((x * std::f64::consts::PI).sqrt(), name)?))
|
||||
}
|
||||
"TANH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.tanh()))
|
||||
}
|
||||
_ => Err(EvalError::new(format!("{name} is not a math function"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn finite(value: f64, function: &str) -> Result<f64, EvalError> {
|
||||
if value.is_finite() { Ok(value) } else { Err(EvalError::new(format!("{function} result is not a finite number"))) }
|
||||
}
|
||||
|
||||
/// Reads the first argument as a finite number inside `[low, high]`.
|
||||
fn domain_number(a: &super::support::Args<'_>, low: f64, high: f64) -> Result<f64, EvalError> {
|
||||
let x = finite(a.number(0)?, a.name)?;
|
||||
if x < low || x > high {
|
||||
return Err(EvalError::new(format!("{} argument is outside the valid domain", a.name)));
|
||||
}
|
||||
Ok(x)
|
||||
}
|
||||
|
||||
fn truncate_i64(value: f64) -> Result<i64, EvalError> {
|
||||
if !value.is_finite() || value.trunc() < -9_223_372_036_854_775_808.0 || value.trunc() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("value is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(value.trunc() as i64)
|
||||
}
|
||||
|
||||
/// CURRENCY rounds half away from zero to four decimals and stores the fixed-point integer.
|
||||
fn currency(value: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CURRENCY argument must be convertible to a number"))?;
|
||||
let scaled = (number * 10_000.0).round();
|
||||
if !scaled.is_finite() || scaled.abs() > i64::MAX as f64 {
|
||||
return Err(EvalError::new("CURRENCY value is outside the representable range"));
|
||||
}
|
||||
Ok(Scalar::Currency(scaled as i64))
|
||||
}
|
||||
|
||||
fn round_away_to_even(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = magnitude_i64(number)?;
|
||||
let rounded = if magnitude % 2 == 0 {
|
||||
magnitude
|
||||
} else {
|
||||
magnitude.checked_add(1).ok_or_else(|| EvalError::new("EVEN result is outside the 64-bit integer range"))?
|
||||
};
|
||||
Ok(with_sign(rounded, number))
|
||||
}
|
||||
|
||||
fn round_away_to_odd(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = magnitude_i64(number)?;
|
||||
let rounded = if magnitude % 2 == 1 {
|
||||
magnitude
|
||||
} else {
|
||||
magnitude.checked_add(1).ok_or_else(|| EvalError::new("ODD result is outside the 64-bit integer range"))?
|
||||
};
|
||||
Ok(with_sign(rounded, number))
|
||||
}
|
||||
|
||||
/// Absolute value rounded away from zero to an integer that still fits in an `i64`.
|
||||
fn magnitude_i64(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = number.abs().ceil();
|
||||
if !magnitude.is_finite() || magnitude >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("number is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(magnitude as i64)
|
||||
}
|
||||
|
||||
fn with_sign(magnitude: i64, number: f64) -> i64 {
|
||||
if number < 0.0 { -magnitude } else { magnitude }
|
||||
}
|
||||
|
||||
fn mround(number: f64, multiple: f64) -> Result<f64, EvalError> {
|
||||
if multiple == 0.0 {
|
||||
return Ok(0.0);
|
||||
}
|
||||
if (number > 0.0 && multiple < 0.0) || (number < 0.0 && multiple > 0.0) {
|
||||
return Err(EvalError::new("MROUND number and multiple must have the same sign"));
|
||||
}
|
||||
finite((number / multiple).round() * multiple, "MROUND")
|
||||
}
|
||||
|
||||
/// `MOD ( <Number>, <Divisor> )`: the remainder whose sign follows the *divisor*
|
||||
/// (`number - divisor * FLOOR ( number / divisor )`), unlike Rust's `%`, which follows the
|
||||
/// dividend. A zero divisor is a division-by-zero error in DAX, not BLANK. Two integer operands
|
||||
/// keep the Integer type the catalog documents; anything else returns a Decimal.
|
||||
fn modulo(number: &Scalar, divisor: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let divisor_number = finite(divisor.to_number().ok_or_else(|| EvalError::new("MOD argument 2 must be numeric"))?, "MOD")?;
|
||||
if divisor_number == 0.0 {
|
||||
return Err(EvalError::new("MOD divisor must not be zero"));
|
||||
}
|
||||
if let (Scalar::Integer(number), Scalar::Integer(divisor)) = (number, divisor) {
|
||||
let divisor = *divisor;
|
||||
let remainder = number.checked_rem(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?;
|
||||
if remainder != 0 && (remainder < 0) != (divisor < 0) {
|
||||
return Ok(Scalar::Integer(
|
||||
remainder.checked_add(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?,
|
||||
));
|
||||
}
|
||||
return Ok(Scalar::Integer(remainder));
|
||||
}
|
||||
let number = finite(number.to_number().ok_or_else(|| EvalError::new("MOD argument 1 must be numeric"))?, "MOD")?;
|
||||
Ok(Scalar::Decimal(finite(number - divisor_number * (number / divisor_number).floor(), "MOD")?))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Random numbers
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Clock entropy for the PRNG seed. `SystemTime::now` traps on wasm, so it is only compiled for
|
||||
/// native targets; wasm falls back to the counter that the caller mixes in.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn clock_nanos() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|duration| duration.as_nanos() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The browser's wall clock in nanoseconds. `SystemTime::now` traps on wasm, and a fixed seed
|
||||
/// would make every page load produce the same `RAND()` sequence, so the shared `js_sys::Date`
|
||||
/// clock that `support.rs` already uses seeds the generator instead.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn clock_nanos() -> u64 {
|
||||
(js_sys::Date::now() * 1_000_000.0) as u64
|
||||
}
|
||||
|
||||
fn next_random_u64() -> u64 {
|
||||
static STATE: AtomicU64 = AtomicU64::new(0);
|
||||
static SALT: AtomicU64 = AtomicU64::new(0);
|
||||
let mut state = STATE.load(Ordering::Relaxed);
|
||||
if state == 0 {
|
||||
let salt = SALT.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed);
|
||||
state = clock_nanos() ^ salt;
|
||||
if state == 0 {
|
||||
state = 0x9E37_79B9_7F4A_7C15;
|
||||
}
|
||||
}
|
||||
// xorshift64*: full-period, small and dependency-free.
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
STATE.store(state, Ordering::Relaxed);
|
||||
state.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
fn next_random_fraction() -> f64 {
|
||||
// 53 random mantissa bits give a uniform value in [0, 1).
|
||||
(next_random_u64() >> 11) as f64 / 9_007_199_254_740_992.0
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// CONVERT
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
fn convert(values: &[Scalar]) -> Result<Scalar, EvalError> {
|
||||
match values {
|
||||
[value, target] => convert_type(value, target),
|
||||
_ => Err(EvalError::new("CONVERT expects an expression and a data type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_type(value: &Scalar, target: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let target = target.to_text().trim().to_ascii_uppercase();
|
||||
match target.as_str() {
|
||||
"BOOLEAN" | "LOGICAL" => {
|
||||
let boolean = value.to_bool().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to BOOLEAN"))?;
|
||||
Ok(Scalar::Boolean(boolean))
|
||||
}
|
||||
// "DECIMAL" is the DAX synonym for the fixed-decimal Currency type, not a double.
|
||||
"CURRENCY" | "DECIMAL" | "FIXEDDECIMAL" => currency(value),
|
||||
"DATETIME" => convert_datetime(value),
|
||||
"DOUBLE" => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DOUBLE"))?;
|
||||
Ok(Scalar::Decimal(finite(number, "CONVERT")?))
|
||||
}
|
||||
"INTEGER" | "INT64" => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to INTEGER"))?;
|
||||
Ok(Scalar::Integer(truncate_i64(number)?))
|
||||
}
|
||||
"STRING" | "TEXT" => Ok(Scalar::String(value.to_dax_text())),
|
||||
other => Err(EvalError::new(format!("CONVERT does not recognize the data type `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_datetime(value: &Scalar) -> Result<Scalar, EvalError> {
|
||||
match value {
|
||||
Scalar::DateTime(_) => Ok(value.clone()),
|
||||
Scalar::String(text) => {
|
||||
let serial = parse_date_text(text).ok_or_else(|| EvalError::new("CONVERT cannot parse the text as DATETIME"))?;
|
||||
Ok(Scalar::DateTime(serial))
|
||||
}
|
||||
other => {
|
||||
let number = other.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DATETIME"))?;
|
||||
Ok(Scalar::DateTime(finite(number, "CONVERT")?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Time-intelligence functions.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
mod ranges;
|
||||
mod totals;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Whether `data_type` names one of the two date types. `CALENDARAUTO`, the range functions and
|
||||
/// the total functions share this test, so a column the model declares as `Date` counts as a date
|
||||
/// everywhere instead of only in some of them.
|
||||
pub(super) fn is_date_type(data_type: &str) -> bool {
|
||||
data_type.eq_ignore_ascii_case("DateTime") || data_type.eq_ignore_ascii_case("Date")
|
||||
}
|
||||
|
||||
/// [`is_date_type`] for a column's optional declared type: an undeclared type is not judged.
|
||||
pub(super) fn is_date_column(data_type: Option<&str>) -> bool {
|
||||
data_type.is_none_or(is_date_type)
|
||||
}
|
||||
|
||||
/// The month and day a `YearEndDate` argument names. The range functions (`DATESYTD`, ...) and the
|
||||
/// total functions (`TOTALYTD`, ...) both parse that argument here, so the documented `"6/30/2008"`
|
||||
/// and `"6/30"` forms behave the same in both families and an impossible day (`"2/30"`) is rejected
|
||||
/// by both instead of being clamped in one and rejected in the other. A month/day-only form is
|
||||
/// checked against a leap year, so `"2/29"` stays valid.
|
||||
pub(super) fn year_end_parts(value: &Scalar) -> Option<(i64, i64)> {
|
||||
let (year, month, day) = match value {
|
||||
Scalar::String(text) => {
|
||||
let parts: Vec<&str> = text.trim().split(['/', '-']).map(str::trim).collect();
|
||||
// An empty component (`"6/-30"`, `"6/"`) is not a date: reject it instead of letting
|
||||
// the remaining parts parse as a valid month and day.
|
||||
if parts.iter().any(|part| part.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let numbers: Vec<i64> = parts.iter().map(|part| part.parse::<i64>().ok()).collect::<Option<Vec<i64>>>()?;
|
||||
match numbers.as_slice() {
|
||||
// `M/D`: only the month and day matter, and the year is never read back.
|
||||
[month, day] => (2000, *month, *day),
|
||||
// `Y/M/D` and `M/D/Y` are both documented shapes; a two-digit year is ignored.
|
||||
[first, second, third] if *first > 31 => (*first, *second, *third),
|
||||
[month, day, year] => (if *year > 99 { *year } else { 2000 }, *month, *day),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let (year, month, day) = super::support::date_parts(super::support::date_value(other)?);
|
||||
(year, month, day)
|
||||
}
|
||||
};
|
||||
((1..=12).contains(&month) && day >= 1 && day <= super::support::days_in_month(year, month)).then_some((month, day))
|
||||
}
|
||||
|
||||
/// The column a table argument contributes to the range and total functions, chosen by one rule so
|
||||
/// `DATESWTD(Calendar)` and `TOTALWTD(…, Calendar)` never disagree: a column whose declared type is
|
||||
/// a date type, then a column named `Date` that is not declared as another type, then — only when it
|
||||
/// cannot be ambiguous — the table's single untyped column.
|
||||
pub(super) fn table_date_column(table: &crate::model::ModelTable) -> Option<usize> {
|
||||
if let Some(index) = table.columns.iter().position(|column| column.data_type.as_deref().is_some_and(is_date_type)) {
|
||||
return Some(index);
|
||||
}
|
||||
if let Some(index) =
|
||||
table.columns.iter().position(|column| column.name.eq_ignore_ascii_case("Date") && is_date_column(column.data_type.as_deref()))
|
||||
{
|
||||
return Some(index);
|
||||
}
|
||||
let untyped: Vec<usize> = table.columns.iter().enumerate().filter(|(_, column)| column.data_type.is_none()).map(|(index, _)| index).collect();
|
||||
match untyped.as_slice() {
|
||||
[index] => Some(*index),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
totals::call(ev, name, args, ctx).or_else(|| ranges::call(ev, name, args, ctx))
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
totals::call_table(ev, name, args, ctx).or_else(|| ranges::call_table(ev, name, args, ctx))
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
//! Time-intelligence range functions (period tables).
|
||||
//!
|
||||
//! Every function here works the same way: it reads the dates visible in the current filter
|
||||
//! context for a DateTime column, derives a calendar window from them, and materializes the
|
||||
//! window as a one-column table whose rows are the *model's own* date values (so the result keeps
|
||||
//! the date table's lineage and `CALCULATE` can use it as a filter).
|
||||
//!
|
||||
//! * The visible range comes from the filter context when the date column (or the date table) is
|
||||
//! filtered, otherwise from the whole table. The window is anchored on the first visible date
|
||||
//! (`PREVIOUS*`), the last visible date (`NEXT*`, `START*`, `END*`, `DATES*TD`), or both
|
||||
//! (`DATEADD`, `DATESBETWEEN`, ...).
|
||||
//! * The window is intersected with the dates that exist in the column, so a non-contiguous date
|
||||
//! table only loses the missing days.
|
||||
//! * The table forms replace any filter on the date column, per the documented time-intelligence
|
||||
//! contract; the scalar conveniences (`FIRSTDATE` used as a value, ...) only accept a
|
||||
//! single-row result.
|
||||
//!
|
||||
//! Week-based functions (`DATESWTD`, `STARTOFWEEK`, `ENDOFWEEK`, `NEXTWEEK`, `PREVIOUSWEEK`) take
|
||||
//! a calendar reference in the catalog. GridCraft has no calendar objects, so the reference is
|
||||
//! resolved to the calendar table's date column and weeks are Sunday-based, which is the Excel /
|
||||
//! `WEEKDAY` default.
|
||||
//!
|
||||
//! https://dax.guide/datesinperiod/ (boundary date excluded), https://dax.guide/dateadd/
|
||||
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, derived_row_frame, edate};
|
||||
use super::*;
|
||||
|
||||
/// Every function that this module answers for.
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"DATEADD",
|
||||
"DATESBETWEEN",
|
||||
"DATESINPERIOD",
|
||||
"DATESMTD",
|
||||
"DATESQTD",
|
||||
"DATESWTD",
|
||||
"DATESYTD",
|
||||
"ENDOFMONTH",
|
||||
"ENDOFQUARTER",
|
||||
"ENDOFWEEK",
|
||||
"ENDOFYEAR",
|
||||
"FIRSTDATE",
|
||||
"FIRSTNONBLANK",
|
||||
"LASTDATE",
|
||||
"LASTNONBLANK",
|
||||
"NEXTDAY",
|
||||
"NEXTMONTH",
|
||||
"NEXTQUARTER",
|
||||
"NEXTWEEK",
|
||||
"NEXTYEAR",
|
||||
"PARALLELPERIOD",
|
||||
"PREVIOUSDAY",
|
||||
"PREVIOUSMONTH",
|
||||
"PREVIOUSQUARTER",
|
||||
"PREVIOUSWEEK",
|
||||
"PREVIOUSYEAR",
|
||||
"SAMEPERIODLASTYEAR",
|
||||
"STARTOFMONTH",
|
||||
"STARTOFQUARTER",
|
||||
"STARTOFWEEK",
|
||||
"STARTOFYEAR",
|
||||
];
|
||||
|
||||
/// Sanity bound for interval counts: the arithmetic stays exact and the loops over the date
|
||||
/// table stay bounded by the model, so only absurd inputs need rejecting.
|
||||
const MAX_INTERVALS: f64 = 1_000_000.0;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Interval {
|
||||
Day,
|
||||
Week,
|
||||
Month,
|
||||
Quarter,
|
||||
Year,
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
if !FUNCTIONS.contains(&name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let result = match name.as_str() {
|
||||
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true).and_then(|table| scalar_result(&name, table)),
|
||||
"LASTNONBLANK" => nonblank(ev, args, ctx, false).and_then(|table| scalar_result(&name, table)),
|
||||
_ => compute_table(ev, &name, args, ctx).and_then(|table| scalar_result(&name, table)),
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
if !FUNCTIONS.contains(&name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(match name.as_str() {
|
||||
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true),
|
||||
"LASTNONBLANK" => nonblank(ev, args, ctx, false),
|
||||
_ => compute_table(ev, &name, args, ctx),
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts a one-row, one-column result to its value; anything else cannot be used as a scalar.
|
||||
fn scalar_result(name: &str, table: TableValue) -> Result<Scalar, EvalError> {
|
||||
match table.rows.as_slice() {
|
||||
[] => Ok(Scalar::Blank),
|
||||
[row] => Ok(row.first().cloned().unwrap_or(Scalar::Blank)),
|
||||
rows => Err(EvalError::new(format!("{name} returns a table with {} rows; use it as a CALCULATE filter instead of a scalar", rows.len()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The date column a time-intelligence call is anchored on.
|
||||
struct DateAxis {
|
||||
table: usize,
|
||||
name: String,
|
||||
/// Every date that exists in the column, ascending, as (day serial, original value).
|
||||
dates: Vec<(f64, Scalar)>,
|
||||
/// First and last visible date, absent when the filter context selects no date.
|
||||
min: Option<f64>,
|
||||
max: Option<f64>,
|
||||
/// The distinct visible dates, ascending. Used to tell a selection that actually contains the
|
||||
/// month's last two days from one that merely ends near its boundary.
|
||||
visible_dates: Vec<f64>,
|
||||
/// The visible cells themselves, as (day serial, original value): `FIRSTDATE`/`LASTDATE` pick
|
||||
/// an exact cell, so they must choose among the values the filter context selects, not among
|
||||
/// every timestamp the day happens to hold.
|
||||
visible_values: Vec<(f64, Scalar)>,
|
||||
}
|
||||
|
||||
impl DateAxis {
|
||||
fn empty(&self) -> TableValue {
|
||||
TableValue::new(vec![TableColumn { name: self.name.clone() }], Vec::new()).with_lineage(self.table)
|
||||
}
|
||||
|
||||
/// The dates of the column between two inclusive boundaries.
|
||||
fn table(&self, start: f64, end: f64) -> TableValue {
|
||||
let start = start.floor();
|
||||
let end = end.floor();
|
||||
let rows = if start > end {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.dates.iter().filter(|(serial, _)| (start..=end).contains(serial)).map(|(_, value)| vec![value.clone()]).collect()
|
||||
};
|
||||
TableValue::new(vec![TableColumn { name: self.name.clone() }], rows).with_lineage(self.table)
|
||||
}
|
||||
|
||||
/// `DATEADD` documents a contiguous dates argument: shifting a selection with a missing day
|
||||
/// would sweep in the blocked date, so it is an error rather than a silently wider result.
|
||||
fn require_contiguous(&self, name: &str) -> Result<(), EvalError> {
|
||||
let Some(pair) = self.visible_dates.windows(2).find(|pair| pair[1] != pair[0] + 1.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
// Report the gap by calendar day: a serial alone does not tell the reader which day the
|
||||
// selection skipped.
|
||||
let day = |serial: f64| Scalar::DateTime(serial).to_dax_text().split(' ').next().unwrap_or_default().to_owned();
|
||||
Err(EvalError::new(format!(
|
||||
"{name} needs a contiguous range of visible dates; the selection skips from {} to {}",
|
||||
day(pair[0]),
|
||||
day(pair[1])
|
||||
)))
|
||||
}
|
||||
|
||||
/// One cell of `date` as a one-row table: the earliest cell of the day, or the latest when
|
||||
/// `last` is set. Single-date operations (`FIRSTDATE`, `LASTDATE`, `PREVIOUSDAY`, ...) must stay
|
||||
/// scalar, so they pick one exact cell value even when the day holds several timestamps; the
|
||||
/// range tables keep every cell.
|
||||
fn single(&self, date: f64, last: bool) -> TableValue {
|
||||
let day = date.floor();
|
||||
let visible: Vec<&Scalar> = self.visible_values.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect();
|
||||
// A day the filter context selects contributes its visible cells; a day outside the
|
||||
// selection (a `NEXTDAY` probe, say) falls back to every cell the column holds.
|
||||
let cells =
|
||||
if visible.is_empty() { self.dates.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect() } else { visible };
|
||||
let ordering = |value: &&Scalar| date_value(value).unwrap_or(f64::NEG_INFINITY);
|
||||
let picked = if last {
|
||||
cells.into_iter().max_by(|a, b| ordering(a).total_cmp(&ordering(b)))
|
||||
} else {
|
||||
cells.into_iter().min_by(|a, b| ordering(a).total_cmp(&ordering(b)))
|
||||
};
|
||||
match picked {
|
||||
Some(value) => TableValue::new(vec![TableColumn { name: self.name.clone() }], vec![vec![value.clone()]]).with_lineage(self.table),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first date that exists in `[start, end]`, as a one-row table.
|
||||
fn first_in(&self, start: f64, end: f64) -> TableValue {
|
||||
let mut table = self.table(start, end);
|
||||
table.rows.truncate(1);
|
||||
table
|
||||
}
|
||||
|
||||
/// The last date that exists in `[start, end]`, as a one-row table.
|
||||
fn last_in(&self, start: f64, end: f64) -> TableValue {
|
||||
let mut table = self.table(start, end);
|
||||
let last = table.rows.pop();
|
||||
table.rows = last.into_iter().collect();
|
||||
table
|
||||
}
|
||||
|
||||
fn first(&self) -> TableValue {
|
||||
match self.min {
|
||||
Some(min) => self.single(min, false),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn last(&self) -> TableValue {
|
||||
match self.max {
|
||||
Some(max) => self.single(max, true),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn visible(&self) -> Option<(f64, f64)> {
|
||||
Some((self.min?, self.max?))
|
||||
}
|
||||
|
||||
/// Whether the selection contains both of the last two days of `max`'s month. `max` is the
|
||||
/// selection's last visible date; the two days have to be on the axis itself, so a selection
|
||||
/// that stops on the month-end date alone (or on its penultimate day) does not qualify.
|
||||
fn includes_last_two_days(&self, max: f64) -> bool {
|
||||
let last = month_end(max);
|
||||
let penultimate = last - 1.0;
|
||||
let contains = |date: f64| self.visible_dates.binary_search_by(|visible| visible.total_cmp(&date)).is_ok();
|
||||
contains(penultimate) && contains(last)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the `Dates` argument (a DateTime column, or a calendar table for the week-based
|
||||
/// functions) and reads the dates visible in the current filter context.
|
||||
fn date_axis(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &Context, name: &str) -> Result<DateAxis, EvalError> {
|
||||
let model = ev.model();
|
||||
let (table, column) = match expr {
|
||||
BoundExpr::Column { table, column } => (*table, *column),
|
||||
BoundExpr::UnqualifiedColumn { name: column } => {
|
||||
let tables = model.tables_with_column(column);
|
||||
let table = match tables.as_slice() {
|
||||
[table] => *table,
|
||||
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column}]`"))),
|
||||
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column}]` is ambiguous"))),
|
||||
};
|
||||
let index = model.column_index(table, column).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column}]`")))?;
|
||||
(table, index)
|
||||
}
|
||||
BoundExpr::Table(table) => {
|
||||
let model_table = model.tables.get(*table).ok_or_else(|| EvalError::new(format!("{name} needs a date table")))?;
|
||||
let index = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("{name} needs a calendar with a date column")))?;
|
||||
(*table, index)
|
||||
}
|
||||
_ => return Err(EvalError::new(format!("{name} needs a date column reference"))),
|
||||
};
|
||||
|
||||
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid date table")))?;
|
||||
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid date column")))?;
|
||||
if let Some(data_type) = &model_column.data_type
|
||||
&& !is_date_type(data_type)
|
||||
{
|
||||
return Err(EvalError::new(format!("{name} needs a DateTime column; `{}[{}]` is {data_type}", model_table.name, model_column.name)));
|
||||
}
|
||||
|
||||
// `date_value` rather than `to_number`: BLANK is not the serial 0 (1899-12-30), and a
|
||||
// non-finite number is not a date, so neither may enter the axis.
|
||||
let mut dates: Vec<(f64, Scalar)> = model_table
|
||||
.rows
|
||||
.iter()
|
||||
.filter_map(|row| row.get(column))
|
||||
.filter_map(|value| date_value(value).filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
|
||||
.collect();
|
||||
dates.sort_by(|left, right| {
|
||||
left.0
|
||||
.total_cmp(&right.0)
|
||||
.then_with(|| date_value(&left.1).unwrap_or(f64::NEG_INFINITY).total_cmp(&date_value(&right.1).unwrap_or(f64::NEG_INFINITY)))
|
||||
});
|
||||
// Deduplicate exact cell values, never whole days: a column can hold several timestamps that
|
||||
// share a day, and the window's filter keys are those exact values, so dropping one would
|
||||
// silently exclude its row from every range table.
|
||||
let mut seen = BTreeSet::new();
|
||||
dates.retain(|(_, value)| seen.insert(ScalarKey::from(value)));
|
||||
|
||||
// The visible dates honour the filter context. Only filters on the date table itself count:
|
||||
// a filter on a fact table does not restrict the dimension it points at.
|
||||
let mut min: Option<f64> = None;
|
||||
let mut max: Option<f64> = None;
|
||||
let mut visible_dates: Vec<f64> = Vec::new();
|
||||
let mut visible_values: Vec<(f64, Scalar)> = Vec::new();
|
||||
for row in visible_rows(ev, table, ctx) {
|
||||
if let Some(value) = row.get(column)
|
||||
&& let Some(serial) = date_value(value).filter(|serial| serial.is_finite())
|
||||
{
|
||||
let serial = serial.floor();
|
||||
min = Some(min.map_or(serial, |value| value.min(serial)));
|
||||
max = Some(max.map_or(serial, |value| value.max(serial)));
|
||||
visible_dates.push(serial);
|
||||
visible_values.push((serial, value.clone()));
|
||||
}
|
||||
}
|
||||
visible_dates.sort_by(|left, right| left.total_cmp(right));
|
||||
visible_dates.dedup_by(|left, right| left.total_cmp(right).is_eq());
|
||||
|
||||
Ok(DateAxis { table, name: model_column.name.clone(), dates, min, max, visible_dates, visible_values })
|
||||
}
|
||||
|
||||
/// The model rows of a table that survive the filters currently in effect, in model column order.
|
||||
///
|
||||
/// Filtering goes through [`Evaluator::table`] so filters that reach the table through an active
|
||||
/// relationship (a snowflaked dimension on the one side, or a bidirectional relationship) apply
|
||||
/// too, not just filters set on the table's own columns.
|
||||
fn visible_rows(ev: &Evaluator<'_>, table: usize, ctx: &Context) -> Vec<Vec<Scalar>> {
|
||||
// A range function's column argument takes the current row: the row context transitions to
|
||||
// filters, exactly as `CALCULATE` does, instead of the whole date column being visible.
|
||||
ev.table(table, &ev.transitioned_filters(ctx)).rows
|
||||
}
|
||||
|
||||
/// Resolves a `ColumnName` argument to (table, column, column name).
|
||||
fn column_target(ev: &Evaluator<'_>, expr: &BoundExpr, name: &str) -> Result<(usize, usize, String), EvalError> {
|
||||
let model = ev.model();
|
||||
let (table, column) = match expr {
|
||||
BoundExpr::Column { table, column } => (*table, *column),
|
||||
BoundExpr::UnqualifiedColumn { name: column_name } => {
|
||||
let tables = model.tables_with_column(column_name);
|
||||
let table = match tables.as_slice() {
|
||||
[table] => *table,
|
||||
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column_name}]`"))),
|
||||
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column_name}]` is ambiguous"))),
|
||||
};
|
||||
let index =
|
||||
model.column_index(table, column_name).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column_name}]`")))?;
|
||||
(table, index)
|
||||
}
|
||||
_ => return Err(EvalError::new(format!("{name} needs a column reference"))),
|
||||
};
|
||||
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid table")))?;
|
||||
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid column")))?;
|
||||
Ok((table, column, model_column.name.clone()))
|
||||
}
|
||||
|
||||
fn number_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<f64, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))
|
||||
}
|
||||
|
||||
fn interval_count(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<i64, EvalError> {
|
||||
let value = number_arg(ev, args, index, ctx, name)?;
|
||||
if !value.is_finite() || value.abs() > MAX_INTERVALS {
|
||||
return Err(EvalError::new(format!("{name} interval count is out of range")));
|
||||
}
|
||||
Ok(value.trunc() as i64)
|
||||
}
|
||||
|
||||
fn interval_arg(
|
||||
ev: &Evaluator<'_>,
|
||||
args: &[BoundExpr],
|
||||
index: usize,
|
||||
ctx: &mut Context,
|
||||
name: &str,
|
||||
allow_day: bool,
|
||||
allow_week: bool,
|
||||
) -> Result<Interval, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
let text = value.to_text();
|
||||
match text.trim().to_ascii_uppercase().as_str() {
|
||||
"DAY" if allow_day => Ok(Interval::Day),
|
||||
"WEEK" if allow_week => Ok(Interval::Week),
|
||||
"MONTH" => Ok(Interval::Month),
|
||||
"QUARTER" => Ok(Interval::Quarter),
|
||||
"YEAR" => Ok(Interval::Year),
|
||||
other => Err(EvalError::new(format!("{name} does not support the interval `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A date argument that accepts BLANK (meaning "use the visible boundary").
|
||||
fn optional_date(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<f64>, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
if value.is_blank() {
|
||||
return Ok(None);
|
||||
}
|
||||
date_value(&value).map(|serial| Some(serial.floor())).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))
|
||||
}
|
||||
|
||||
fn year_end_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<(i64, i64)>, EvalError> {
|
||||
let Some(expr) = args.get(index) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
if value.is_blank() {
|
||||
return Ok(None);
|
||||
}
|
||||
year_end_parts(&value).map(Some).ok_or_else(|| EvalError::new(format!("{name} YearEndDate must be a date such as \"6/30/2024\"")))
|
||||
}
|
||||
|
||||
fn month_start(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
date_serial(year, month, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn month_end(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
date_serial(year, month, days_in_month(year, month), 0, 0, 0)
|
||||
}
|
||||
|
||||
fn quarter_start(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let first = (month - 1).div_euclid(3) * 3 + 1;
|
||||
date_serial(year, first, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn quarter_end(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let last = (month - 1).div_euclid(3) * 3 + 3;
|
||||
date_serial(year, last, days_in_month(year, last), 0, 0, 0)
|
||||
}
|
||||
|
||||
fn year_start(serial: f64) -> f64 {
|
||||
date_serial(date_parts(serial).0, 1, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn week_start(serial: f64) -> f64 {
|
||||
// `date_weekday` uses the Excel WEEKDAY convention: Sunday = 1 ... Saturday = 7.
|
||||
serial.floor() - (date_weekday(serial) - 1) as f64
|
||||
}
|
||||
|
||||
fn week_end(serial: f64) -> f64 {
|
||||
week_start(serial) + 6.0
|
||||
}
|
||||
|
||||
/// End of the period (month/quarter/year) containing a date; day and week intervals are whole
|
||||
/// numbers of days, so their aligned end is the date itself.
|
||||
fn align_end(serial: f64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day | Interval::Week => serial.floor(),
|
||||
Interval::Month => month_end(serial),
|
||||
Interval::Quarter => quarter_end(serial),
|
||||
Interval::Year => year_end_default(serial),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start of the period (month/quarter/year) containing a date.
|
||||
fn align_start(serial: f64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day | Interval::Week => serial.floor(),
|
||||
Interval::Month => month_start(serial),
|
||||
Interval::Quarter => quarter_start(serial),
|
||||
Interval::Year => year_start(serial),
|
||||
}
|
||||
}
|
||||
|
||||
fn year_end_default(serial: f64) -> f64 {
|
||||
date_serial(date_parts(serial).0, 12, 31, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn shift(serial: f64, count: i64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day => serial + count as f64,
|
||||
Interval::Week => serial + 7.0 * count as f64,
|
||||
Interval::Month => edate(serial, count),
|
||||
Interval::Quarter => edate(serial, count.saturating_mul(3)),
|
||||
Interval::Year => edate(serial, count.saturating_mul(12)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last day of a fiscal year that starts the day after the previous year's end date.
|
||||
fn fiscal_end(year: i64, month: i64, day: i64) -> f64 {
|
||||
date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0)
|
||||
}
|
||||
|
||||
/// The (start, end) of the fiscal year containing `serial`; the default year ends December 31.
|
||||
fn fiscal_bounds(serial: f64, year_end: Option<(i64, i64)>) -> (f64, f64) {
|
||||
let (month, day) = year_end.unwrap_or((12, 31));
|
||||
let (year, _, _) = date_parts(serial);
|
||||
let end_this_year = fiscal_end(year, month, day);
|
||||
let end_year = if serial.floor() <= end_this_year { year } else { year + 1 };
|
||||
let end = fiscal_end(end_year, month, day);
|
||||
let start = fiscal_end(end_year - 1, month, day) + 1.0;
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// The previous calendar month's window.
|
||||
fn previous_month(serial: f64) -> (f64, f64) {
|
||||
let last = month_start(serial) - 1.0;
|
||||
(month_start(last), last)
|
||||
}
|
||||
|
||||
fn next_month(serial: f64) -> (f64, f64) {
|
||||
let first = month_end(serial) + 1.0;
|
||||
(first, month_end(first))
|
||||
}
|
||||
|
||||
fn previous_quarter(serial: f64) -> (f64, f64) {
|
||||
let last = quarter_start(serial) - 1.0;
|
||||
(quarter_start(last), last)
|
||||
}
|
||||
|
||||
fn next_quarter(serial: f64) -> (f64, f64) {
|
||||
let first = quarter_end(serial) + 1.0;
|
||||
(first, quarter_end(first))
|
||||
}
|
||||
|
||||
fn previous_week(serial: f64) -> (f64, f64) {
|
||||
let last = week_start(serial) - 1.0;
|
||||
(week_start(last), last)
|
||||
}
|
||||
|
||||
fn next_week(serial: f64) -> (f64, f64) {
|
||||
let first = week_end(serial) + 1.0;
|
||||
(first, week_end(first))
|
||||
}
|
||||
|
||||
fn compute_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let dates_expr = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a date column")))?;
|
||||
let axis = date_axis(ev, dates_expr, ctx, name)?;
|
||||
|
||||
match name {
|
||||
"FIRSTDATE" => Ok(axis.first()),
|
||||
"LASTDATE" => Ok(axis.last()),
|
||||
"DATEADD" => {
|
||||
// Arguments 4/5 (Extension/Truncation) exist only for model calendars. GridCraft has
|
||||
// no calendar objects, so the date-column rules always apply: a selection that ends on
|
||||
// the last day of a period extends to the end of the shifted period, and day positions
|
||||
// that do not exist in the target month move to its last day (dax.guide/DATEADD).
|
||||
let count = interval_count(ev, args, 1, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 2, ctx, name, true, false)?;
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
axis.require_contiguous(name)?;
|
||||
let start = shift(min, count, interval);
|
||||
let mut end = shift(max, count, interval);
|
||||
// A selection that covers a whole period selects the whole target period. A selection
|
||||
// that contains both of the last two days of its month (but not the whole period)
|
||||
// still reaches the end of the shifted month, so a full February shifted by a year
|
||||
// keeps February 29: "if the Dates argument includes all the days in April (30 rows),
|
||||
// the result for the previous month includes all the days in March (31 days)"
|
||||
// (dax.guide/DATEADD).
|
||||
let month_edge = axis.includes_last_two_days(max);
|
||||
if align_start(min, interval) == min && align_end(max, interval).floor() == max {
|
||||
// The selection covers a whole period: the shift covers the whole target period.
|
||||
end = align_end(end, interval);
|
||||
} else if month_edge && matches!(interval, Interval::Month | Interval::Quarter | Interval::Year) {
|
||||
// It runs to the end of its month instead: the shift reaches the end of the
|
||||
// target month (a full February shifted by a year keeps February 29).
|
||||
end = month_end(end);
|
||||
}
|
||||
Ok(axis.table(start.min(end), start.max(end)))
|
||||
}
|
||||
"DATESBETWEEN" => {
|
||||
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
|
||||
let end = optional_date(ev, args, 2, ctx, name)?.or(axis.max);
|
||||
match (start, end) {
|
||||
(Some(start), Some(end)) => Ok(axis.table(start, end)),
|
||||
_ => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"DATESINPERIOD" => {
|
||||
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
|
||||
let count = interval_count(ev, args, 2, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 3, ctx, name, true, true)?;
|
||||
let aligned = match args.get(4) {
|
||||
Some(expr) => {
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
match value.to_text().trim().to_ascii_uppercase().as_str() {
|
||||
"ENDALIGNED" => true,
|
||||
"" | "PRECISE" => false,
|
||||
other => return Err(EvalError::new(format!("{name} does not support the EndBehavior `{other}`"))),
|
||||
}
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
let Some(start) = start else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
if count == 0 {
|
||||
return Ok(axis.empty());
|
||||
}
|
||||
let mut boundary = shift(start, count, interval);
|
||||
if aligned && align_end(start, interval).floor() == start.floor() {
|
||||
boundary = align_end(boundary, interval);
|
||||
}
|
||||
let (low, high) = if count > 0 { (start, boundary - 1.0) } else { (boundary + 1.0, start) };
|
||||
Ok(axis.table(low, high))
|
||||
}
|
||||
"DATESMTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(month_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESQTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(quarter_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESWTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(week_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESYTD" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, _) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.table(start, max))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"ENDOFMONTH" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(month_start(max), month_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFQUARTER" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(quarter_start(max), quarter_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFWEEK" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(week_start(max), week_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.last_in(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"NEXTDAY" => match axis.max {
|
||||
Some(max) => Ok(axis.single(max + 1.0, true)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSDAY" => match axis.min {
|
||||
Some(min) => Ok(axis.single(min - 1.0, true)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTMONTH" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_month(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSMONTH" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_month(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTQUARTER" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_quarter(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSQUARTER" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_quarter(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTWEEK" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_week(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSWEEK" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_week(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (_, end) = fiscal_bounds(max, year_end);
|
||||
let (start, next_end) = fiscal_bounds(end + 1.0, year_end);
|
||||
Ok(axis.table(start, next_end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"PREVIOUSYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.min {
|
||||
Some(min) => {
|
||||
let (start, _) = fiscal_bounds(min, year_end);
|
||||
let (previous_start, previous_end) = fiscal_bounds(start - 1.0, year_end);
|
||||
Ok(axis.table(previous_start, previous_end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"PARALLELPERIOD" => {
|
||||
let count = interval_count(ev, args, 1, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 2, ctx, name, false, false)?;
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
let start = align_start(shift(min, count, interval), interval);
|
||||
let end = align_end(shift(max, count, interval), interval);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
"SAMEPERIODLASTYEAR" => {
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
let start = edate(min, -12);
|
||||
let mut end = edate(max, -12);
|
||||
// It is `DATEADD(Dates, -1, YEAR)`: a selection containing the last two days of its
|
||||
// month reaches the end of the shifted month, leap day included.
|
||||
if axis.includes_last_two_days(max) {
|
||||
end = month_end(end);
|
||||
}
|
||||
Ok(axis.table(start.min(end), start.max(end)))
|
||||
}
|
||||
"STARTOFMONTH" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(month_start(max), month_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFQUARTER" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(quarter_start(max), quarter_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFWEEK" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(week_start(max), week_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.first_in(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
_ => Err(EvalError::new(format!("DAX function `{name}` is not implemented by this evaluator"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_blank_scalar(value: &Scalar) -> bool {
|
||||
value.is_blank() || matches!(value, Scalar::String(text) if text.is_empty())
|
||||
}
|
||||
|
||||
/// `FIRSTNONBLANK`/`LASTNONBLANK`: walk the visible values of the column in sort order and return
|
||||
/// the value whose accompanying expression is not blank.
|
||||
fn nonblank(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<TableValue, EvalError> {
|
||||
let name = if first { "FIRSTNONBLANK" } else { "LASTNONBLANK" };
|
||||
let target = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
|
||||
let expression = args.get(1).ok_or_else(|| EvalError::new(format!("{name} needs a value expression")))?;
|
||||
let (table, column, column_name) = column_target(ev, target, name)?;
|
||||
|
||||
let visible = visible_rows(ev, table, ctx);
|
||||
let mut entries: Vec<(ScalarKey, Scalar)> = Vec::new();
|
||||
let mut seen: BTreeSet<ScalarKey> = BTreeSet::new();
|
||||
for row in &visible {
|
||||
if let Some(value) = row.get(column) {
|
||||
let key = ScalarKey::from(value);
|
||||
if seen.insert(key.clone()) {
|
||||
entries.push((key, value.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
entries.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
if !first {
|
||||
entries.reverse();
|
||||
}
|
||||
|
||||
for (key, value) in entries {
|
||||
let previous = ctx.filters.filters.get(&(table, column)).cloned();
|
||||
// `FilterContext::set` folds the key the same way the filter's `matches` does, so a
|
||||
// mixed-case text candidate still selects its rows.
|
||||
ctx.filters.set(table, column, [key]);
|
||||
// The row context is `VALUES(column)`, not one model row: a measure's context transition
|
||||
// must keep every row that shares the candidate value.
|
||||
ctx.rows.push(derived_row_frame(Some(table), vec![column_name.clone()], vec![value.clone()], vec![Some(column)]));
|
||||
let evaluated = ev.eval(expression, ctx);
|
||||
ctx.rows.pop();
|
||||
match previous {
|
||||
Some(values) => {
|
||||
ctx.filters.set(table, column, values);
|
||||
}
|
||||
None => {
|
||||
ctx.filters.filters.remove(&(table, column));
|
||||
}
|
||||
}
|
||||
if !is_blank_scalar(&evaluated?) {
|
||||
return Ok(TableValue::new(vec![TableColumn { name: column_name }], vec![vec![value]]).with_lineage(table));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(TableValue::new(vec![TableColumn { name: column_name }], Vec::new()).with_lineage(table))
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Time-intelligence scalar totals and balance functions.
|
||||
//!
|
||||
//! `TOTAL*` are CALCULATE sugar: the expression is evaluated over a period-to-date window
|
||||
//! derived from the last date visible on the date column. `OPENINGBALANCE*`/`CLOSINGBALANCE*`
|
||||
//! evaluate the expression on the period's boundary date (the last date, or the day before the
|
||||
//! first), matching Excel's `CALCULATE(<expr>, ENDOF.../PREVIOUSDAY(STARTOF...))` definitions.
|
||||
//!
|
||||
//! The window is applied as a filter on the date column. Like the table filter produced by
|
||||
//! `DATESMTD`/`ENDOFMONTH` inside CALCULATE, it replaces the existing filters on the date table
|
||||
//! (otherwise a matrix row filtered by month could never accumulate a quarter or a year) while
|
||||
//! filters on other tables keep applying. When the date column is a fact table's own date rather
|
||||
//! than a date dimension key, only that column's filter is replaced and the fact table's other
|
||||
//! filters keep applying — the same rows `CALCULATE (<expr>, DATESYTD (<date>))` would see.
|
||||
//!
|
||||
//! Week periods follow DAX's Sunday-first convention (`STARTOFWEEK`); the optional
|
||||
//! `YearEndDate` argument only contributes its month and day, as documented for `TOTALYTD`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::value::ScalarKey;
|
||||
|
||||
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, eomonth};
|
||||
use super::*;
|
||||
|
||||
/// The calendar period a total or a balance slice is anchored to.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Period {
|
||||
Month,
|
||||
Quarter,
|
||||
Week,
|
||||
Year,
|
||||
}
|
||||
|
||||
/// A resolved date column: the table it belongs to and its column index.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DateColumn {
|
||||
table: usize,
|
||||
column: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let result = match name.to_ascii_uppercase().as_str() {
|
||||
"TOTALMTD" => total(ev, name, args, ctx, Period::Month),
|
||||
"TOTALQTD" => total(ev, name, args, ctx, Period::Quarter),
|
||||
"TOTALWTD" => total(ev, name, args, ctx, Period::Week),
|
||||
"TOTALYTD" => total(ev, name, args, ctx, Period::Year),
|
||||
"OPENINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, true),
|
||||
"OPENINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, true),
|
||||
"OPENINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, true),
|
||||
"OPENINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, true),
|
||||
"CLOSINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, false),
|
||||
"CLOSINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, false),
|
||||
"CLOSINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, false),
|
||||
"CLOSINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, false),
|
||||
"FIRSTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, true),
|
||||
"LASTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, false),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// `TOTALMTD`/`TOTALQTD`/`TOTALWTD`/`TOTALYTD`.
|
||||
fn total(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period) -> Result<Scalar, EvalError> {
|
||||
let max = if period == Period::Year { 4 } else { 3 };
|
||||
if args.len() < 2 || args.len() > max {
|
||||
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
|
||||
}
|
||||
// These functions are CALCULATE sugar: the row context transitions to filters first, and the
|
||||
// expression then runs without row frames, so a measure argument cannot re-transition the
|
||||
// window away.
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let dates = date_column(ev, &args[1])?;
|
||||
let visible = visible_dates(ev, dates, &base);
|
||||
let Some(last) = visible.last().copied() else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
|
||||
let (start, _) = period_bounds(period, last, year_end);
|
||||
|
||||
let mut filters = date_table_filters(ev, &base, dates);
|
||||
if let Some(filter) = args.get(2) {
|
||||
apply_filter_arg(ev, filter, &mut filters, ctx)?;
|
||||
}
|
||||
// The window only keeps dates that exist in the date column, exactly like DATESMTD/YTD; the
|
||||
// keys use the column's own values so an untyped date column still matches its rows.
|
||||
let window = dates_between(ev, dates, start, last);
|
||||
// `TOTALYTD` is `CALCULATE(expr, DATESYTD(dates), filter)`: a filter argument on the date
|
||||
// column intersects the window instead of being replaced by it.
|
||||
let window: BTreeSet<ScalarKey> = window.iter().map(|(_, value)| ScalarKey::from(value)).collect();
|
||||
let keys = match filters.filters.get(&(dates.table, dates.column)) {
|
||||
Some(existing) => existing.intersection(&window).cloned().collect(),
|
||||
None => window,
|
||||
};
|
||||
filters.set(dates.table, dates.column, keys);
|
||||
let mut inner = nested_context(filters, ctx);
|
||||
ev.eval(&args[0], &mut inner)
|
||||
}
|
||||
|
||||
/// `OPENINGBALANCE*`/`CLOSINGBALANCE*`: `CALCULATE(<expression>, <boundary date>)`.
|
||||
///
|
||||
/// Excel defines the closing balance on the last date of the period and the opening balance on
|
||||
/// the day before the first date (`PREVIOUSDAY(STARTOF...)`). The expression is evaluated with a
|
||||
/// single-date filter, so a boundary date without data yields BLANK — including on sparse fact
|
||||
/// tables, where a "last date with a value" scan would invent a value Excel does not return.
|
||||
fn balance(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period, opening: bool) -> Result<Scalar, EvalError> {
|
||||
let max = if period == Period::Year { 4 } else { 3 };
|
||||
if args.len() < 2 || args.len() > max {
|
||||
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
|
||||
}
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let dates = date_column(ev, &args[1])?;
|
||||
let visible = visible_dates(ev, dates, &base);
|
||||
let Some(last) = visible.last().copied() else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
|
||||
let (start, end) = period_bounds(period, last, year_end);
|
||||
// Every cell of the boundary day, not one per day: a fact date column can hold several
|
||||
// timestamps that share a day, and all of them belong to the period's boundary.
|
||||
let boundary = if opening {
|
||||
// PREVIOUSDAY(STARTOF...): the stored cells of the day before the period, when they exist.
|
||||
let day = start.floor() - 1.0;
|
||||
dates_between(ev, dates, day, day)
|
||||
} else {
|
||||
// `ENDOF*` is the last day that exists in the column, not the calendar end of the period.
|
||||
let window = dates_between(ev, dates, start, end);
|
||||
let Some(boundary_day) = window.last().map(|(date, _)| *date) else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
window.into_iter().filter(|(date, _)| *date == boundary_day).collect()
|
||||
};
|
||||
if boundary.is_empty() {
|
||||
return Ok(Scalar::Blank);
|
||||
}
|
||||
let boundary_keys: BTreeSet<ScalarKey> = boundary.iter().map(|(_, value)| ScalarKey::from(value)).collect();
|
||||
|
||||
let mut filters = date_table_filters(ev, &base, dates);
|
||||
if let Some(filter) = args.get(2) {
|
||||
apply_filter_arg(ev, filter, &mut filters, ctx)?;
|
||||
}
|
||||
let keys = match filters.filters.get(&(dates.table, dates.column)) {
|
||||
Some(existing) => existing.intersection(&boundary_keys).cloned().collect(),
|
||||
None => boundary_keys,
|
||||
};
|
||||
filters.set(dates.table, dates.column, keys);
|
||||
let mut inner = nested_context(filters, ctx);
|
||||
ev.eval(&args[0], &mut inner)
|
||||
}
|
||||
|
||||
/// `FIRSTNONBLANKVALUE`/`LASTNONBLANKVALUE`: the expression value at the first (last) visible
|
||||
/// value of the column whose expression result is not blank.
|
||||
fn non_blank_value(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<Scalar, EvalError> {
|
||||
if args.len() != 2 {
|
||||
return Err(EvalError::new(format!("{name} expects 2 arguments")));
|
||||
}
|
||||
// CALCULATE sugar, like `TOTAL*`: the row context transitions to filters first, and the
|
||||
// expression runs with no row frames so a measure argument cannot re-transition the candidate
|
||||
// filter away.
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let (table, column) = column_reference(ev, &args[0])?;
|
||||
let source = ev.table(table, &base);
|
||||
let values = source.column(column);
|
||||
let keys: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(ScalarKey::from).collect();
|
||||
let ordered: Vec<ScalarKey> = if first { keys.into_iter().collect() } else { keys.into_iter().rev().collect() };
|
||||
let mut inner = nested_context(base, ctx);
|
||||
for key in ordered {
|
||||
inner.filters.set(table, column, [key]);
|
||||
let value = ev.eval(&args[1], &mut inner)?;
|
||||
if !value.is_blank() {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
Ok(Scalar::Blank)
|
||||
}
|
||||
|
||||
/// Resolves a date-column argument. The week functions in the catalog take a calendar/table
|
||||
/// reference, so a table argument is accepted too and its date column is chosen the same way
|
||||
/// `ranges::date_axis` chooses one: a column whose declared type is a date type first, a column
|
||||
/// named `Date` only as the fallback. An untyped column is never preferred over a typed one.
|
||||
fn date_column(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<DateColumn, EvalError> {
|
||||
if let BoundExpr::Table(table) = expr {
|
||||
let Some(model_table) = ev.model().tables.get(*table) else {
|
||||
return Err(EvalError::new("the date table is out of range"));
|
||||
};
|
||||
let column = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("table `{}` has no date column", model_table.name)))?;
|
||||
return Ok(DateColumn { table: *table, column });
|
||||
}
|
||||
let (table, column) = column_reference(ev, expr)?;
|
||||
let Some(model_table) = ev.model().tables.get(table) else {
|
||||
return Err(EvalError::new("the date table is out of range"));
|
||||
};
|
||||
let Some(model_column) = model_table.columns.get(column) else {
|
||||
return Err(EvalError::new("the date column is out of range"));
|
||||
};
|
||||
if !is_date_column(model_column.data_type.as_deref()) {
|
||||
return Err(EvalError::new(format!("`{}`[{}] is not a date column", model_table.name, model_column.name)));
|
||||
}
|
||||
Ok(DateColumn { table, column })
|
||||
}
|
||||
|
||||
/// Resolves a plain column argument without a type restriction.
|
||||
fn column_reference(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<(usize, usize), EvalError> {
|
||||
match expr {
|
||||
BoundExpr::Column { table, column } => {
|
||||
let Some(model_table) = ev.model().tables.get(*table) else {
|
||||
return Err(EvalError::new("the column's table is out of range"));
|
||||
};
|
||||
if model_table.columns.get(*column).is_none() {
|
||||
return Err(EvalError::new("the column is out of range"));
|
||||
}
|
||||
Ok((*table, *column))
|
||||
}
|
||||
BoundExpr::UnqualifiedColumn { name } => {
|
||||
let tables = ev.model().tables_with_column(name);
|
||||
let [table] = tables.as_slice() else {
|
||||
return Err(EvalError::new(format!("column `[{name}]` is ambiguous or not in the model")));
|
||||
};
|
||||
let column = ev.model().column_index(*table, name).ok_or_else(|| EvalError::new(format!("column `[{name}]` is not in the model")))?;
|
||||
Ok((*table, column))
|
||||
}
|
||||
_ => Err(EvalError::new("this function needs a column reference")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The date values visible in the current filter context. Filters propagate to the date table
|
||||
/// only along bidirectional relationships, which `Evaluator::table` already models; filters on
|
||||
/// the fact table of a single-direction date relationship must not shrink the calendar.
|
||||
fn visible_dates(ev: &Evaluator<'_>, dates: DateColumn, filters: &FilterContext) -> Vec<f64> {
|
||||
let table = ev.table(dates.table, filters);
|
||||
let values: Vec<f64> = table.column(dates.column).iter().filter_map(date_value).collect();
|
||||
normalized(values)
|
||||
}
|
||||
|
||||
/// The dates of the column in `[start, end]`, each with the column's own value so a filter built
|
||||
/// from them matches the stored cells even when the column has no declared date type. Serials are
|
||||
/// rounded down to their day, so a DateTime cell that carries a time of day still matches the
|
||||
/// whole-day bounds; every cell of a day is kept, because the filter keys are the exact cell
|
||||
/// values and a day may hold more than one timestamp.
|
||||
fn dates_between(ev: &Evaluator<'_>, dates: DateColumn, start: f64, end: f64) -> Vec<(f64, Scalar)> {
|
||||
let Some(model_table) = ev.model().tables.get(dates.table) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut values: Vec<(f64, Scalar)> = model_table
|
||||
.rows
|
||||
.iter()
|
||||
.filter_map(|row| row.get(dates.column).map(|value| (value, date_value(value))))
|
||||
.filter_map(|(value, serial)| serial.filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
|
||||
.filter(|(date, _)| *date >= start - 1e-9 && *date <= end + 1e-9)
|
||||
.collect();
|
||||
values.sort_by(|left, right| left.0.total_cmp(&right.0));
|
||||
values
|
||||
}
|
||||
|
||||
/// Sorts ascending and drops duplicate days.
|
||||
fn normalized(mut dates: Vec<f64>) -> Vec<f64> {
|
||||
dates.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
dates.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
dates
|
||||
}
|
||||
|
||||
/// The context a `TOTAL*`/`BALANCE*`/`NONBLANKVALUE` expression runs in: the window's filters with
|
||||
/// no row frames, carrying the caller's variables and grouping scope. A measure evaluated inside a
|
||||
/// `SUMMARIZE`/`SUMMARIZECOLUMNS` group must still see the group's scope (`ISINSCOPE`), so the scope
|
||||
/// is propagated rather than reset.
|
||||
fn nested_context(filters: FilterContext, ctx: &Context) -> Context {
|
||||
Context { filters, rows: Vec::new(), vars: ctx.vars.clone(), grouping_scope: ctx.grouping_scope.clone() }
|
||||
}
|
||||
|
||||
/// Removes the filters the computed window replaces. A date dimension key replaces every filter on
|
||||
/// the whole date table; any other date column (a fact table's own date) replaces only that
|
||||
/// column's filter, so the fact table keeps its other slices.
|
||||
fn date_table_filters(ev: &Evaluator<'_>, filters: &FilterContext, dates: DateColumn) -> FilterContext {
|
||||
let model = ev.model();
|
||||
let is_dimension_key = model.relationships.iter().any(|relationship| {
|
||||
model.table_index(&relationship.to_table) == Some(dates.table)
|
||||
&& model.column_index(dates.table, &relationship.to_column) == Some(dates.column)
|
||||
});
|
||||
let mut filters = filters.clone();
|
||||
if is_dimension_key {
|
||||
filters.filters.retain(|(table, _), _| *table != dates.table);
|
||||
} else {
|
||||
filters.filters.remove(&(dates.table, dates.column));
|
||||
}
|
||||
filters
|
||||
}
|
||||
|
||||
/// The first and last day of the period containing `anchor`.
|
||||
fn period_bounds(period: Period, anchor: f64, year_end: Option<f64>) -> (f64, f64) {
|
||||
let anchor = anchor.floor();
|
||||
let (year, month, _) = date_parts(anchor);
|
||||
match period {
|
||||
Period::Month => (date_serial(year, month, 1, 0, 0, 0), eomonth(anchor, 0)),
|
||||
Period::Quarter => {
|
||||
let first_month = (month - 1) / 3 * 3 + 1;
|
||||
let start = date_serial(year, first_month, 1, 0, 0, 0);
|
||||
(start, eomonth(start, 2))
|
||||
}
|
||||
Period::Week => {
|
||||
// WEEKDAY numbers are Sunday = 1 ... Saturday = 7.
|
||||
let start = anchor - (date_weekday(anchor) - 1) as f64;
|
||||
(start, start + 6.0)
|
||||
}
|
||||
Period::Year => match year_end {
|
||||
Some(year_end) => fiscal_bounds(anchor, year_end),
|
||||
None => (date_serial(year, 1, 1, 0, 0, 0), date_serial(year, 12, 31, 0, 0, 0)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The fiscal year containing `anchor` for a year-end month/day. The year-end date itself
|
||||
/// belongs to the fiscal year that ends on it.
|
||||
fn fiscal_bounds(anchor: f64, year_end: f64) -> (f64, f64) {
|
||||
let (_, end_month, end_day) = date_parts(year_end);
|
||||
let (year, _, _) = date_parts(anchor);
|
||||
let year_end_in = |year: i64| date_serial(year, end_month, end_day.min(days_in_month(year, end_month)), 0, 0, 0);
|
||||
let end_this_year = year_end_in(year);
|
||||
if anchor <= end_this_year + 1e-9 { (year_end_in(year - 1) + 1.0, end_this_year) } else { (end_this_year + 1.0, year_end_in(year + 1)) }
|
||||
}
|
||||
|
||||
/// Evaluates the optional `YearEndDate` argument. Only its month and day matter.
|
||||
fn year_end_serial(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<f64, EvalError> {
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
let serial = parse_year_end(&value).ok_or_else(|| EvalError::new("YearEndDate must be a date"))?;
|
||||
if !serial.is_finite() {
|
||||
return Err(EvalError::new("YearEndDate must be a date"));
|
||||
}
|
||||
Ok(serial.floor())
|
||||
}
|
||||
|
||||
/// Parses a year-end date. Unlike `parse_date_text`, this accepts the `M/D/YYYY` form used in
|
||||
/// Parses a year-end date through the shared parser, then pins it to a leap year: only the month
|
||||
/// and day are used, so `"6/30/2008"` and `"6/30"` name the same fiscal year end.
|
||||
fn parse_year_end(value: &Scalar) -> Option<f64> {
|
||||
let (month, day) = super::year_end_parts(value)?;
|
||||
Some(date_serial(2000, month, day, 0, 0, 0))
|
||||
}
|
||||
|
||||
/// Applies one CALCULATE-style filter argument to `filters`, the way the core CALCULATE does:
|
||||
/// column predicate, `ALL`/`REMOVEFILTERS` (no argument, column or table), or a table expression
|
||||
/// over a model table. Removal runs before the period window is applied, so the window still
|
||||
/// lands even when the modifier cleared the date table's own filters.
|
||||
fn apply_filter_arg(ev: &Evaluator<'_>, expr: &BoundExpr, filters: &mut FilterContext, ctx: &mut Context) -> Result<(), EvalError> {
|
||||
match expr {
|
||||
BoundExpr::Binary { op, left, right }
|
||||
if matches!(op, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge)
|
||||
&& matches!(**left, BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) =>
|
||||
{
|
||||
let (table, column) = column_reference(ev, left)?;
|
||||
let value = ev.eval(right, ctx)?;
|
||||
// `col <op> v` is FILTER(ALL(col), …): the candidates come from the whole column and
|
||||
// compare with DAX semantics (numeric across types, text ignoring case).
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
let keep = |candidate: &Scalar| {
|
||||
let order = candidate.compare(&value);
|
||||
match op {
|
||||
BinaryOp::Eq => order == Some(Equal),
|
||||
BinaryOp::Ne => order != Some(Equal),
|
||||
BinaryOp::Lt => order == Some(Less),
|
||||
BinaryOp::Le => matches!(order, Some(Less | Equal)),
|
||||
BinaryOp::Gt => order == Some(Greater),
|
||||
_ => matches!(order, Some(Greater | Equal)),
|
||||
}
|
||||
};
|
||||
let keys = ev
|
||||
.table(table, &FilterContext::default())
|
||||
.column(column)
|
||||
.into_iter()
|
||||
.filter(|candidate| keep(candidate))
|
||||
.map(|candidate| ScalarKey::from(&candidate));
|
||||
filters.set(table, column, keys);
|
||||
Ok(())
|
||||
}
|
||||
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("ALL") || spec.name.eq_ignore_ascii_case("REMOVEFILTERS") => {
|
||||
match args.first() {
|
||||
// No argument removes every filter: `ALL ()` is `ALL(<every table>)`.
|
||||
None => filters.clear(),
|
||||
// A column argument clears only that column; a table argument clears the table.
|
||||
// Unqualified columns resolve to the single model column with that name.
|
||||
Some(BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) => {
|
||||
for arg in args {
|
||||
let (table, column) = column_reference(ev, arg)?;
|
||||
filters.filters.remove(&(table, column));
|
||||
}
|
||||
}
|
||||
Some(BoundExpr::Table(table)) => filters.remove_table(*table),
|
||||
Some(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("KEEPFILTERS") => {
|
||||
// KEEPFILTERS applies its inner filter and intersects it with what is already there.
|
||||
let inner = args.first().ok_or_else(|| EvalError::new("KEEPFILTERS needs a filter"))?;
|
||||
let mut applied = filters.clone();
|
||||
apply_filter_arg(ev, inner, &mut applied, ctx)?;
|
||||
for (key, values) in applied.filters {
|
||||
let merged = match filters.filters.get(&key) {
|
||||
Some(existing) => existing.intersection(&values).cloned().collect(),
|
||||
None => values,
|
||||
};
|
||||
filters.filters.insert(key, merged);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
let table = ev.eval_table(expr, ctx)?;
|
||||
let Some(index) = table.lineage else {
|
||||
return Err(EvalError::new("a filter table needs a source table"));
|
||||
};
|
||||
for (position, column) in table.columns.iter().enumerate() {
|
||||
let Some(model_column) = ev.model().column_index(index, &column.name) else { continue };
|
||||
let keys: BTreeSet<ScalarKey> = table.rows.iter().filter_map(|row| row.get(position)).map(ScalarKey::from).collect();
|
||||
filters.set(index, model_column, keys);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nested_context_keeps_the_grouping_scope() {
|
||||
// A date total called from inside a `SUMMARIZE` group runs its expression in a nested
|
||||
// context; the group's scope has to survive so `ISINSCOPE` still sees the group.
|
||||
let ctx = Context {
|
||||
filters: FilterContext::default(),
|
||||
rows: Vec::new(),
|
||||
vars: vec![Scalar::Integer(7)],
|
||||
grouping_scope: Some(vec![(0, 1), (0, 2)]),
|
||||
};
|
||||
let inner = nested_context(FilterContext::default(), &ctx);
|
||||
assert_eq!(inner.grouping_scope, Some(vec![(0, 1), (0, 2)]));
|
||||
assert_eq!(inner.vars, vec![Scalar::Integer(7)]);
|
||||
assert!(inner.rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_context_starts_outside_any_group() {
|
||||
// The same call outside a grouping has no scope to carry.
|
||||
let ctx = Context { filters: FilterContext::default(), rows: Vec::new(), vars: Vec::new(), grouping_scope: None };
|
||||
assert_eq!(nested_context(FilterContext::default(), &ctx).grouping_scope, None);
|
||||
}
|
||||
}
|
||||
@@ -242,11 +242,55 @@ fn an_interval_keyword_is_not_shadowed_by_a_variable() {
|
||||
let bound = bind(&model, "VAR YEAR = 1 RETURN DATEDIFF ( Sales[Amount], Sales[Amount], YEAR )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
|
||||
// `DATEADD`'s interval is catalogued as text, but it is the same documented enumeration: a
|
||||
// variable holding another interval must not replace it.
|
||||
let bound = bind(&model, "VAR MONTH = \"DAY\" RETURN DATEADD ( Sales[Amount], 1, MONTH )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"MONTH\")"), "{debug}");
|
||||
// `DATESINPERIOD`'s fourth argument is the same documented enumeration, including `WEEK`,
|
||||
// which `DATEADD` does not accept.
|
||||
for interval in ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"] {
|
||||
let formula = format!("VAR {interval} = \"DAY\" RETURN DATESINPERIOD ( Date[Date], Date[Date], -1, {interval} )");
|
||||
let bound = bind(&model, &formula);
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
|
||||
}
|
||||
// `PARALLELPERIOD`'s third argument is the month-boundary enumeration: a variable holding
|
||||
// `YEAR` must not turn `-1, MONTH` into a year shift.
|
||||
for interval in ["MONTH", "QUARTER", "YEAR"] {
|
||||
let formula = format!("VAR {interval} = \"YEAR\" RETURN PARALLELPERIOD ( Date[Date], -1, {interval} )");
|
||||
let bound = bind(&model, &formula);
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
|
||||
}
|
||||
// A variable still wins where the parameter is documented as text: RANKX's Ties argument.
|
||||
let bound = bind(&model, "VAR DENSE = 1 RETURN RANKX ( Sales, Sales[Amount], 42, DENSE )");
|
||||
assert!(format!("{bound:?}").contains("Variable"), "{bound:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interval_keyword_is_not_shadowed_by_a_model_name() {
|
||||
let mut model = sample_model();
|
||||
model.tables.push(ModelTable {
|
||||
name: "YEAR".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![],
|
||||
});
|
||||
// A model table called `YEAR` is not the interval: `DATEADD` must still bind the keyword.
|
||||
let bound = bind(&model, "DATEADD ( Sales[Amount], 1, YEAR )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
|
||||
// A position that does not take an interval keyword still resolves names: `YEAR` in RANKX's
|
||||
// Order slot is not an order word, so the model table wins and must bind as that table.
|
||||
let year_table = model.tables.len() - 1;
|
||||
match bind(&model, "RANKX ( Sales, Sales[Amount], 42, YEAR )") {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(args.get(3), Some(BoundExpr::Table(table)) if *table == year_table), "{args:?}");
|
||||
}
|
||||
other => panic!("expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_order_keywords_bind_at_their_argument_positions() {
|
||||
let model = sample_model();
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Evaluation tests for the date/time function family.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::value::{Scalar, TableColumn, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The OLE Automation serial of a date, built with `chrono` (a normal dependency of the crate,
|
||||
/// independent of the evaluator under test) from the 1899-12-30 epoch.
|
||||
fn serial(year: i32, month: u32, day: u32) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year, month, day).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn model() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Order Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 15)), Scalar::Decimal(20.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 3, 10)), Scalar::Decimal(30.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
// No rows: CALENDARAUTO must take its bounds from the Sales date column.
|
||||
rows: Vec::new(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A model whose only column is numeric: CALENDARAUTO has nothing to scan.
|
||||
fn model_without_dates() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Numbers".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(1)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Empty".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: Vec::new(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A model whose date column is declared `Date` rather than `DateTime`: DAX has both date types,
|
||||
/// so the fiscal calendar has to be built from either.
|
||||
fn model_with_date_typed_columns() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Order Date".into(), data_type: Some("Date".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::DateTime(serial(2023, 3, 31)), Scalar::Decimal(20.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_in(model: &DataModel, src: &str) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval_table_in(model: &DataModel, src: &str) -> Result<TableValue, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval(src: &str) -> Result<Scalar, String> {
|
||||
eval_in(&model(), src)
|
||||
}
|
||||
|
||||
fn eval_table(src: &str) -> Result<TableValue, String> {
|
||||
eval_table_in(&model(), src)
|
||||
}
|
||||
|
||||
fn value(src: &str) -> Scalar {
|
||||
eval(src).unwrap_or_else(|error| panic!("{src}: {error}"))
|
||||
}
|
||||
|
||||
fn assert_close(actual: Scalar, expected: f64, label: &str) {
|
||||
match actual {
|
||||
Scalar::Decimal(value) if (value - expected).abs() <= 1e-12 => {}
|
||||
other => panic!("{label}: expected {expected}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text conversion
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn datevalue_reads_the_common_text_dates() {
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15\")"), Scalar::DateTime(45_306.0));
|
||||
assert_eq!(value("DATEVALUE(\"2024/1/15\")"), Scalar::DateTime(45_306.0));
|
||||
// The documented en-US form, month first.
|
||||
assert_eq!(value("DATEVALUE(\"1/8/2009\")"), Scalar::DateTime(39_821.0));
|
||||
// A time portion is ignored: DATEVALUE returns the date.
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(45_306.0));
|
||||
// A 12-hour clock suffix is accepted in both date orders.
|
||||
let expected = Scalar::DateTime(serial(2024, 1, 15));
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15 4:48 PM\")"), expected);
|
||||
assert_eq!(value("DATEVALUE(\"1/15/2024 4:48 PM\")"), expected);
|
||||
assert_eq!(value("DATEVALUE(DATE(2024,1,15))"), Scalar::DateTime(45_306.0));
|
||||
assert_eq!(value("DATEVALUE(\"2024-02-29\")"), Scalar::DateTime(45_351.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datevalue_rejects_invalid_text() {
|
||||
assert!(eval("DATEVALUE(\"not a date\")").is_err());
|
||||
// Impossible days and month-first days above 12 are errors, not serial rollover.
|
||||
assert!(eval("DATEVALUE(\"2024-02-30\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"31/12/2024\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"2024-13-01\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"\")").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timevalue_reads_the_common_text_times() {
|
||||
let clock = (16.0 * 3600.0 + 48.0 * 60.0 + 23.0) / 86_400.0;
|
||||
assert_eq!(value("TIMEVALUE(\"16:48:23\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"4:48:23 PM\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"12:00 AM\")"), Scalar::DateTime(0.0));
|
||||
assert_eq!(value("TIMEVALUE(\"12:30 PM\")"), Scalar::DateTime((12.0 * 3600.0 + 30.0 * 60.0) / 86_400.0));
|
||||
assert_eq!(value("TIMEVALUE(\"6:00\")"), Scalar::DateTime(0.25));
|
||||
assert_eq!(value("TIMEVALUE(\"2024-01-15\")"), Scalar::DateTime(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timevalue_rejects_invalid_text() {
|
||||
assert!(eval("TIMEVALUE(\"25:00\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"12:61\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"lunch\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"13:00 PM\")").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Scalar date parts
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn quarter_maps_month_to_calendar_quarter() {
|
||||
assert_eq!(value("QUARTER(DATE(2024,1,15))"), Scalar::Integer(1));
|
||||
assert_eq!(value("QUARTER(DATE(2024,3,31))"), Scalar::Integer(1));
|
||||
assert_eq!(value("QUARTER(DATE(2024,4,1))"), Scalar::Integer(2));
|
||||
assert_eq!(value("QUARTER(DATE(2024,7,1))"), Scalar::Integer(3));
|
||||
assert_eq!(value("QUARTER(DATE(2024,10,5))"), Scalar::Integer(4));
|
||||
assert_eq!(value("QUARTER(DATE(2024,12,31))"), Scalar::Integer(4));
|
||||
assert_eq!(value("QUARTER(\"2024-05-15\")"), Scalar::Integer(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeknum_matches_excel_week_systems() {
|
||||
// System 1: the week containing January 1 is week 1, weeks start on Sunday by default.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,1))"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15))"), Scalar::Integer(3));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), Scalar::Integer(3));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), value("WEEKNUM(DATE(2024,1,15), 11)"));
|
||||
// Monday start: Sunday 2024-01-07 still belongs to week 1.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,7), 2)"), Scalar::Integer(1));
|
||||
// Sunday start: the same Sunday begins week 2.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,7))"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,8), 2)"), Scalar::Integer(2));
|
||||
// A year can end in week 53 when January 1 falls late in the week.
|
||||
assert_eq!(value("WEEKNUM(DATE(2023,12,31))"), Scalar::Integer(53));
|
||||
assert_eq!(value("WEEKNUM(\"2024-01-15\")"), Scalar::Integer(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeknum_iso_weeks_cross_year_boundaries() {
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 21)"), Scalar::Integer(3));
|
||||
// 2021-01-01 (Friday) belongs to ISO week 53 of 2020.
|
||||
assert_eq!(value("WEEKNUM(DATE(2021,1,1), 21)"), Scalar::Integer(53));
|
||||
// 2018-12-31 (Monday) and 2024-12-30 (Monday) are week 1 of the next year.
|
||||
assert_eq!(value("WEEKNUM(DATE(2018,12,31), 21)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,12,30), 21)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,12,29), 21)"), Scalar::Integer(52));
|
||||
assert_eq!(value("WEEKNUM(DATE(2020,12,31), 21)"), Scalar::Integer(53));
|
||||
assert!(eval("WEEKNUM(DATE(2024,1,1), 3)").is_err());
|
||||
assert!(eval("WEEKNUM(DATE(2024,1,1), 10)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// YEARFRAC
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn yearfrac_supports_every_basis() {
|
||||
let start = "DATE(2024,1,1)";
|
||||
let end = "DATE(2024,7,1)";
|
||||
// Leap year 2024: Jan 1 to Jul 1 is 182 actual days.
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end})")), 0.5, "basis 0 default");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 0)")), 180.0 / 360.0, "basis 0");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 1)")), 182.0 / 366.0, "basis 1");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 2)")), 182.0 / 360.0, "basis 2");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 3)")), 182.0 / 365.0, "basis 3");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 4)")), 180.0 / 360.0, "basis 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yearfrac_handles_calendar_boundaries_and_reversed_ranges() {
|
||||
// A whole leap year is 1 for the 30/360 convention and 365/366 for actual/actual.
|
||||
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 0)"), 1.0, "30/360 whole year");
|
||||
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 1)"), 365.0 / 366.0, "actual/actual whole year");
|
||||
// Excel's US 30/360 February rule: the end of February counts as day 30 but March 31 keeps 31.
|
||||
assert_close(value("YEARFRAC(DATE(2019,2,28), DATE(2019,3,31), 0)"), 31.0 / 360.0, "February rule");
|
||||
// Two end-of-February dates collapse to 30/30, which is a full year.
|
||||
assert_close(value("YEARFRAC(DATE(2011,2,28), DATE(2012,2,29), 0)"), 1.0, "February to February");
|
||||
// actual/actual uses 366 when the period contains a February 29.
|
||||
assert_close(value("YEARFRAC(DATE(2011,3,1), DATE(2012,2,29), 1)"), 365.0 / 366.0, "leap day between");
|
||||
// Multi-year actual/actual divides by the average calendar year length.
|
||||
assert_close(value("YEARFRAC(DATE(2000,1,1), DATE(2003,1,1), 1)"), 1096.0 / (1461.0 / 4.0), "average year");
|
||||
// Excel ignores the argument order: the reversed pair returns the positive fraction.
|
||||
assert_close(value("YEARFRAC(DATE(2024,7,1), DATE(2024,1,1), 2)"), 182.0 / 360.0, "reversed");
|
||||
assert_close(value("YEARFRAC(\"2024-01-01\", \"2024-07-01\", 2)"), 182.0 / 360.0, "text dates");
|
||||
// dax.guide's documented example: 2011-01-01 .. 2011-12-15.
|
||||
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 0)"), 344.0 / 360.0, "dax.guide 30/360");
|
||||
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 1)"), 348.0 / 365.0, "dax.guide actual/actual");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yearfrac_rejects_unknown_bases() {
|
||||
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 5)").is_err());
|
||||
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), -1)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// NETWORKDAYS
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn networkdays_counts_working_days_with_weekends_and_holidays() {
|
||||
// January 2024 has 31 days, starting on a Monday, with 8 weekend days.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31))"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1)"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,15) })"), Scalar::Integer(22));
|
||||
// A holiday already on a weekend does not count twice.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,6) })"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,1), DATE(2024,1,15) })"), Scalar::Integer(21));
|
||||
// Weekend code 2 is Sunday/Monday, 11 is Sunday only.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 2)"), Scalar::Integer(22));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 11)"), Scalar::Integer(27));
|
||||
// A reversed range returns the negative count.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,31), DATE(2024,1,1))"), Scalar::Integer(-23));
|
||||
// A single working day and a single weekend day.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,2), DATE(2024,1,2))"), Scalar::Integer(1));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,6), DATE(2024,1,6))"), Scalar::Integer(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn networkdays_rejects_bad_weekend_codes() {
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 0)").is_err());
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 8)").is_err());
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 18)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// CALENDAR / CALENDARAUTO
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn calendar_builds_the_inclusive_date_column() {
|
||||
let table = eval_table("CALENDAR(DATE(2024,2,27), DATE(2024,3,1))").expect("calendar table");
|
||||
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
|
||||
// 2024 is a leap year, so February 29 is included.
|
||||
assert_eq!(
|
||||
table.rows,
|
||||
vec![
|
||||
vec![Scalar::DateTime(serial(2024, 2, 27))],
|
||||
vec![Scalar::DateTime(serial(2024, 2, 28))],
|
||||
vec![Scalar::DateTime(serial(2024, 2, 29))],
|
||||
vec![Scalar::DateTime(serial(2024, 3, 1))],
|
||||
]
|
||||
);
|
||||
assert_eq!(eval_table("CALENDAR(DATE(2024,1,1), DATE(2024,1,31))").expect("january").rows.len(), 31);
|
||||
assert_eq!(value("COUNTROWS(CALENDAR(DATE(2024,1,1), DATE(2024,1,31)))"), Scalar::Integer(31));
|
||||
// Table functions are not scalars.
|
||||
assert!(eval("CALENDAR(DATE(2024,1,1), DATE(2024,1,2))").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_rejects_reversed_bounds() {
|
||||
assert!(eval_table("CALENDAR(DATE(2024,2,1), DATE(2024,1,1))").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_rejects_oversized_spans() {
|
||||
// The whole in-range span is 2,958,466 days, above the 1,000,000-row generation ceiling, so
|
||||
// it must fail instead of allocating the table.
|
||||
let error = eval_table("CALENDAR(DATE(1899,12,30), DATE(9999,12,31))").expect_err("oversized calendar");
|
||||
assert!(error.contains("too large"), "{error}");
|
||||
// 1900-01-01 is serial 2, so exactly 1,000,000 days end on 4637-11-27; the cap is inclusive
|
||||
// there and one day further fails.
|
||||
let largest = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,27))").expect("largest calendar");
|
||||
assert_eq!(largest.rows.len(), 1_000_000);
|
||||
assert_eq!(largest.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(4637, 11, 27))));
|
||||
let error = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,28))").expect_err("one day over the cap");
|
||||
assert!(error.contains("too large"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_covers_whole_fiscal_years() {
|
||||
// Sales spans 2023-06-15 .. 2024-03-10 and Date spans 2023-01-01 .. 2024-12-31.
|
||||
let table = eval_table("CALENDARAUTO()").expect("calendar auto");
|
||||
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
|
||||
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
|
||||
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 12, 31))));
|
||||
assert_eq!(table.rows.len(), 731);
|
||||
assert_eq!(value("COUNTROWS(CALENDARAUTO())"), Scalar::Integer(731));
|
||||
|
||||
// Fiscal years ending in March: 2023-04-01 .. 2024-03-31, including leap day 2024-02-29.
|
||||
let fiscal = eval_table("CALENDARAUTO(3)").expect("fiscal calendar");
|
||||
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 4, 1))));
|
||||
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
|
||||
assert_eq!(fiscal.rows.len(), 366);
|
||||
assert!(fiscal.rows.iter().any(|row| row[0] == Scalar::DateTime(serial(2024, 2, 29))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_reads_date_typed_columns() {
|
||||
// 2023-03-31 .. 2023-06-15, in a column declared `Date`: the whole 2023 calendar year.
|
||||
let table = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO()").expect("calendar auto over Date columns");
|
||||
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
|
||||
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 12, 31))));
|
||||
assert_eq!(table.rows.len(), 365);
|
||||
// A fiscal year ending in March: two fiscal years, since June 2023 falls in FY2024.
|
||||
let fiscal = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO(3)").expect("fiscal calendar over Date columns");
|
||||
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2022, 4, 1))));
|
||||
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_validates_arguments_and_model() {
|
||||
assert!(eval_table("CALENDARAUTO(0)").is_err());
|
||||
assert!(eval_table("CALENDARAUTO(13)").is_err());
|
||||
assert!(eval_table_in(&model_without_dates(), "CALENDARAUTO()").is_err());
|
||||
// Table functions are not scalars.
|
||||
assert!(eval("CALENDARAUTO()").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Clock
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
// The test runs natively and needs an independent clock reference for the date serials.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn clock_functions_track_the_system_clock() {
|
||||
let clock = || {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs_f64() / 86_400.0 + 25_569.0)
|
||||
.expect("system clock")
|
||||
};
|
||||
let serial_of = |src: &str| match value(src) {
|
||||
Scalar::DateTime(serial) => serial,
|
||||
other => panic!("{src} produced {other:?}"),
|
||||
};
|
||||
// Each function is a separate evaluation; retry if a local or UTC day boundary falls inside
|
||||
// the sampling window, so the floor comparisons cannot race midnight.
|
||||
let mut attempts = 0;
|
||||
let (today, now, utc_today, utc_now) = loop {
|
||||
let before = clock();
|
||||
let (today, now) = (serial_of("TODAY()"), serial_of("NOW()"));
|
||||
let (utc_today, utc_now) = (serial_of("UTCTODAY()"), serial_of("UTCNOW()"));
|
||||
let after = clock();
|
||||
if before.floor() == after.floor() && today == now.floor() && utc_today == utc_now.floor() {
|
||||
break (today, now, utc_today, utc_now);
|
||||
}
|
||||
attempts += 1;
|
||||
assert!(attempts < 5, "clock functions disagree: TODAY {today}, NOW {now}, UTCTODAY {utc_today}, UTCNOW {utc_now}");
|
||||
};
|
||||
let expected = clock();
|
||||
assert!((utc_now - expected).abs() < 1.0 / 86_400.0, "UTCNOW follows the system clock");
|
||||
assert!((0.0..1.0).contains(&now.fract()));
|
||||
// The host supplies one wall clock, so the local and UTC variants never differ by a day.
|
||||
assert!((now - utc_now).abs() < 1.0);
|
||||
assert!((today - utc_today).abs() <= 1.0);
|
||||
// Volatile functions take no arguments.
|
||||
assert!(eval("NOW(1)").is_err());
|
||||
assert!(eval("TODAY(1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edate_and_eomonth_survive_extreme_month_offsets() {
|
||||
// `months` is arbitrary input: the month arithmetic must saturate instead of overflowing.
|
||||
let model = model();
|
||||
for (formula, name) in [("EDATE(DATE(2024,1,15), 1E18)", "EDATE"), ("EOMONTH(DATE(2024,1,15), -1E18)", "EOMONTH")] {
|
||||
match eval_in(&model, formula) {
|
||||
// Out-of-range serials are reported, but the month arithmetic itself must not overflow.
|
||||
Ok(value) => assert!(matches!(value, Scalar::DateTime(serial) if serial.is_finite() || serial.is_nan()), "{name}: {value:?}"),
|
||||
Err(error) => assert!(!error.is_empty(), "{name} reported an empty error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Relocated regressions
|
||||
//
|
||||
// These pin documented results that the evaluator used to get wrong; they moved here from
|
||||
// `eval_audit_semantics.rs` and `eval_text.rs` because their functions live in this family.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The single numeric value of an expression; panics when it is not numeric.
|
||||
fn number(src: &str) -> f64 {
|
||||
let evaluated = value(src);
|
||||
evaluated.to_number().unwrap_or_else(|| panic!("{src} is not numeric: {evaluated:?}"))
|
||||
}
|
||||
|
||||
/// The message of the error an expression raises.
|
||||
fn error(src: &str) -> String {
|
||||
match eval(src) {
|
||||
Err(message) => message,
|
||||
Ok(evaluated) => panic!("{src}: expected an error, got {evaluated:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text form of an expression, as produced by `& ""`.
|
||||
fn text(src: &str) -> String {
|
||||
match value(src) {
|
||||
Scalar::String(text) => text,
|
||||
other => panic!("{src} should return text, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mod_follows_the_divisor_sign() {
|
||||
// Microsoft Learn, MOD: "The result has the same sign as the divisor."
|
||||
assert_eq!(value("MOD(7, 3)"), Scalar::Integer(1));
|
||||
assert_eq!(value("MOD(-3, 2)"), Scalar::Integer(1));
|
||||
assert_eq!(value("MOD(3, -2)"), Scalar::Integer(-1));
|
||||
assert_eq!(value("MOD(-3, -2)"), Scalar::Integer(-1));
|
||||
assert_eq!(value("MOD(10, 5)"), Scalar::Integer(0));
|
||||
// A fractional operand keeps the Decimal result.
|
||||
assert_eq!(number("MOD(5.5, 2)"), 1.5);
|
||||
assert_eq!(number("MOD(-5.5, 2)"), 0.5);
|
||||
// A zero divisor is a division-by-zero error, not BLANK.
|
||||
assert!(error("MOD(1, 0)").contains("MOD divisor must not be zero"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundup_and_rounddown_follow_the_sign() {
|
||||
// Microsoft Learn: ROUNDDOWN rounds toward zero, ROUNDUP away from zero.
|
||||
assert_eq!(number("ROUNDDOWN(-2.9, 0)"), -2.0);
|
||||
assert_eq!(number("ROUNDDOWN(2.9, 0)"), 2.0);
|
||||
assert_eq!(number("ROUNDDOWN(-2.345, 2)"), -2.34);
|
||||
assert_eq!(number("ROUNDUP(-2.1, 0)"), -3.0);
|
||||
assert_eq!(number("ROUNDUP(2.1, 0)"), 3.0);
|
||||
assert_eq!(number("ROUNDUP(2.341, 2)"), 2.35);
|
||||
// ROUND still rounds half away from zero.
|
||||
assert_eq!(number("ROUND(2.5, 0)"), 3.0);
|
||||
assert_eq!(number("ROUND(-2.5, 0)"), -3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datediff_counts_interval_boundaries() {
|
||||
// The catalog: DATEDIFF counts the Interval boundaries crossed between two dates.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), DAY)"), Scalar::Integer(60));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), MONTH)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2025, 3, 1), YEAR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 7, 1), QUARTER)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), WEEK)"), Scalar::Integer(8));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), HOUR)"), Scalar::Integer(24));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), MINUTE)"), Scalar::Integer(1_440));
|
||||
// A month boundary is crossed even by a single day.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 31), DATE(2024, 2, 1), MONTH)"), Scalar::Integer(1));
|
||||
// The sign follows Date2 - Date1.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 3, 1), DATE(2024, 1, 1), MONTH)"), Scalar::Integer(-2));
|
||||
// A text argument keeps the time of day, exactly like a DateTime one: the sub-day intervals
|
||||
// must not be read as midnight on both sides.
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", MINUTE)"), Scalar::Integer(120));
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", SECOND)"), Scalar::Integer(7_200));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1) + 10/24, \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
|
||||
assert!(error("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), FORTNIGHT)").contains("DATEDIFF interval"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_wraps_inside_one_day() {
|
||||
// The catalog: "Overflowing arguments wrap inside the same day instead of raising an error
|
||||
// (TIME ( 10, 90, 0 ) is 11:30 and TIME ( 50, 0, 0 ) is 02:00)".
|
||||
assert_eq!(number("TIME(10, 90, 0)"), 11.5 / 24.0);
|
||||
assert_eq!(number("TIME(50, 0, 0)"), 2.0 / 24.0);
|
||||
assert_eq!(number("TIME(25, 0, 0)"), 1.0 / 24.0);
|
||||
assert_eq!(number("TIME(0, 0, 0)"), 0.0);
|
||||
assert_eq!(number("TIME(1, 2, 3)"), (3_723.0) / 86_400.0);
|
||||
assert!(error("TIME(-1, 0, 0)").contains("TIME argument 1"));
|
||||
assert!(error("TIME(32768, 0, 0)").contains("TIME argument 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weekday_honours_the_return_type() {
|
||||
// 2024-01-01 is a Monday. Return type 1 numbers Sunday 1, 2 numbers Monday 1, 3 numbers
|
||||
// Monday 0, and 11-17 start the week on Monday through Sunday.
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1))"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 1)"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 2)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 3)"), Scalar::Integer(0));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 11)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 12)"), Scalar::Integer(7));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 17)"), Scalar::Integer(2));
|
||||
// 2024-01-07 is a Sunday.
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 2)"), Scalar::Integer(7));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 3)"), Scalar::Integer(6));
|
||||
assert!(error("WEEKDAY(DATE(2024, 1, 1), 5)").contains("WEEKDAY return type"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datediff_counts_boundaries_for_sub_day_and_week_intervals() {
|
||||
// 10:59:59 to 11:00:01 crosses the 11:00 hour boundary even though two seconds passed.
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 1), HOUR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 58), TIME(10, 59, 59), SECOND)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 0), MINUTE)"), Scalar::Integer(1));
|
||||
// Exactly one elapsed hour is still one boundary; 59 minutes is none.
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(11, 0, 0), HOUR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(10, 59, 59), HOUR)"), Scalar::Integer(0));
|
||||
// Weeks are Sunday-based: 2024-01-01 is a Monday, so the week boundary is the Sunday before it.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 6), WEEK)"), Scalar::Integer(0));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 7), WEEK)"), Scalar::Integer(1));
|
||||
// The sign follows Date2 - Date1.
|
||||
assert_eq!(value("DATEDIFF(TIME(11, 0, 1), TIME(10, 59, 59), HOUR)"), Scalar::Integer(-1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_and_large_numbers_concatenate_in_dax_form() {
|
||||
assert_eq!(text("CURRENCY(10) & \"\""), "10");
|
||||
assert_eq!(text("CURRENCY(10.5) & \"\""), "10.5");
|
||||
assert_eq!(text("CONVERT(1, CURRENCY) & \"\""), "1");
|
||||
// Very large whole numbers use Excel's exponent text with the explicit sign.
|
||||
assert_eq!(text("1e15 & \"\""), "1E+15");
|
||||
// DAX prints 15 significant digits, so a floating-point residue does not surface.
|
||||
assert_eq!(text("0.1 + 0.2 & \"\""), "0.3");
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Evaluator tests for math and trigonometry functions.
|
||||
|
||||
use gridcraft_dax::model::DataModel;
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
DataModel { tables: vec![], relationships: vec![], measures: vec![] }
|
||||
}
|
||||
|
||||
fn eval_result(source: &str) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval(source: &str) -> Scalar {
|
||||
eval_result(source).expect("expression evaluates")
|
||||
}
|
||||
|
||||
fn assert_close(actual: Scalar, expected: f64) {
|
||||
match actual {
|
||||
Scalar::Decimal(value) => {
|
||||
let tolerance = 1e-9 * expected.abs().max(1.0);
|
||||
assert!((value - expected).abs() <= tolerance, "expected {expected}, got {value}");
|
||||
}
|
||||
other => panic!("expected Decimal({expected}), got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_trigonometry() {
|
||||
assert_close(eval("ACOS(0.5)"), std::f64::consts::FRAC_PI_3);
|
||||
assert_close(eval("ACOS(-1)"), std::f64::consts::PI);
|
||||
assert!(eval_result("ACOS(2)").is_err());
|
||||
assert!(eval_result("ACOS(-1.0001)").is_err());
|
||||
|
||||
assert_close(eval("ASIN(0.5)"), std::f64::consts::FRAC_PI_6);
|
||||
assert_close(eval("ASIN(-1)"), -std::f64::consts::FRAC_PI_2);
|
||||
assert!(eval_result("ASIN(1.5)").is_err());
|
||||
|
||||
assert_close(eval("ATAN(1)"), std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ATAN(0)"), 0.0);
|
||||
|
||||
assert_close(eval("ACOT(1)"), std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ACOT(-1)"), 3.0 * std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ACOT(0)"), std::f64::consts::FRAC_PI_2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperbolic_and_inverse_hyperbolic() {
|
||||
assert_close(eval("ACOSH(2)"), 1.316_957_896_924_816_6);
|
||||
assert!(eval_result("ACOSH(0.5)").is_err());
|
||||
|
||||
assert_close(eval("ASINH(1)"), 0.881_373_587_019_543);
|
||||
assert_close(eval("ATANH(0.5)"), 0.549_306_144_334_054_9);
|
||||
assert!(eval_result("ATANH(1)").is_err());
|
||||
assert!(eval_result("ATANH(-1)").is_err());
|
||||
|
||||
assert_close(eval("ACOTH(2)"), 0.549_306_144_334_054_9);
|
||||
assert_close(eval("ACOTH(-2)"), -0.549_306_144_334_054_9);
|
||||
assert!(eval_result("ACOTH(1)").is_err());
|
||||
assert!(eval_result("ACOTH(-0.5)").is_err());
|
||||
|
||||
assert_close(eval("COSH(1)"), 1.543_080_634_815_243_7);
|
||||
assert_close(eval("SINH(1)"), 1.175_201_193_643_801_4);
|
||||
assert_close(eval("TANH(1)"), 0.761_594_155_955_764_9);
|
||||
assert!(eval_result("SINH(1000)").is_err(), "overflow must be an error, not infinity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cotangent_family() {
|
||||
assert_close(eval("COT(PI() / 4)"), 1.0);
|
||||
assert_close(eval("COTH(1)"), 1.313_035_285_499_331_2);
|
||||
assert!(eval_result("COT(0)").is_err());
|
||||
assert!(eval_result("COTH(0)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_and_odd_round_away_from_zero() {
|
||||
assert_eq!(eval("EVEN(3.2)"), Scalar::Integer(4));
|
||||
assert_eq!(eval("EVEN(-3.2)"), Scalar::Integer(-4));
|
||||
assert_eq!(eval("EVEN(2)"), Scalar::Integer(2));
|
||||
assert_eq!(eval("EVEN(-2)"), Scalar::Integer(-2));
|
||||
assert_eq!(eval("EVEN(0)"), Scalar::Integer(0));
|
||||
|
||||
assert_eq!(eval("ODD(2.1)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("ODD(-2.1)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("ODD(2)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("ODD(0)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("ODD(-2)"), Scalar::Integer(-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mround_sign_and_multiples() {
|
||||
assert_close(eval("MROUND(7.3, 0.5)"), 7.5);
|
||||
assert_close(eval("MROUND(10, 3)"), 9.0);
|
||||
assert_close(eval("MROUND(-7.3, -0.5)"), -7.5);
|
||||
// dax.guide documents the binary floating-point midpoints 6.0 and 7.1.
|
||||
assert_close(eval("MROUND(6.05, 0.1)"), 6.0);
|
||||
assert_close(eval("MROUND(7.05, 0.1)"), 7.1);
|
||||
// A digit count whose scale factor would overflow leaves the value unchanged.
|
||||
assert_close(eval("ROUND(1.5, 400)"), 1.5);
|
||||
assert_close(eval("MROUND(10, 0)"), 0.0);
|
||||
assert!(eval_result("MROUND(7, -2)").is_err());
|
||||
assert!(eval_result("MROUND(-7, 2)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotient_truncates_toward_zero() {
|
||||
assert_eq!(eval("QUOTIENT(7, 2)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("QUOTIENT(-7, 2)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("QUOTIENT(7, -2)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("QUOTIENT(0, 2)"), Scalar::Integer(0));
|
||||
assert!(eval_result("QUOTIENT(7, 0)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqrtpi_domain() {
|
||||
assert_close(eval("SQRTPI(2)"), 2.506_628_274_631_000_2);
|
||||
assert_close(eval("SQRTPI(0)"), 0.0);
|
||||
assert!(eval_result("SQRTPI(-1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_rounds_to_four_decimals() {
|
||||
assert_eq!(eval("CURRENCY(10.5)"), Scalar::Currency(105_000));
|
||||
assert_eq!(eval("CURRENCY(3.66666)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CURRENCY(-3.66666)"), Scalar::Currency(-36_667));
|
||||
assert_eq!(eval("CURRENCY(3.0123456789)"), Scalar::Currency(30_123));
|
||||
assert_eq!(eval("CURRENCY(\"3.66666\")"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CURRENCY(TRUE)"), Scalar::Currency(10_000));
|
||||
assert_eq!(eval("CURRENCY(FALSE)"), Scalar::Currency(0));
|
||||
assert!(eval_result("CURRENCY(\"not a number\")").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_functions_stay_in_range() {
|
||||
for _ in 0..64 {
|
||||
match eval("RAND()") {
|
||||
Scalar::Decimal(value) => assert!((0.0..1.0).contains(&value), "RAND out of range: {value}"),
|
||||
other => panic!("RAND returned {other:?}"),
|
||||
}
|
||||
match eval("RANDBETWEEN(1, 10)") {
|
||||
Scalar::Integer(value) => assert!((1..=10).contains(&value), "RANDBETWEEN out of range: {value}"),
|
||||
other => panic!("RANDBETWEEN returned {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(eval("RANDBETWEEN(5, 5)"), Scalar::Integer(5));
|
||||
assert_eq!(eval("RANDBETWEEN(-3, -3)"), Scalar::Integer(-3));
|
||||
assert!(eval_result("RANDBETWEEN(10, 1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_data_types() {
|
||||
assert_eq!(eval("CONVERT(32.34, INTEGER)"), Scalar::Integer(32));
|
||||
assert_eq!(eval("CONVERT(-32.34, INT64)"), Scalar::Integer(-32));
|
||||
assert_eq!(eval("CONVERT(\"123\", INTEGER)"), Scalar::Integer(123));
|
||||
assert_eq!(eval("CONVERT(1, DOUBLE)"), Scalar::Decimal(1.0));
|
||||
assert_eq!(eval("CONVERT(3.66666, CURRENCY)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CONVERT(3.66666, DECIMAL)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CONVERT(12345, DATETIME)"), Scalar::DateTime(12_345.0));
|
||||
assert_eq!(eval("CONVERT(\"1966-12-25\", DATETIME)"), Scalar::DateTime(24_466.0));
|
||||
assert_eq!(eval("CONVERT(TRUE, STRING)"), Scalar::String("TRUE".into()));
|
||||
assert_eq!(eval("CONVERT(\"TRUE\", BOOLEAN)"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("CONVERT(0, LOGICAL)"), Scalar::Boolean(false));
|
||||
assert!(eval_result("CONVERT(\"abc\", INTEGER)").is_err());
|
||||
assert!(eval_result("CONVERT(1, NONSENSE)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ceiling_floor_and_trunc_use_their_second_argument() {
|
||||
// The catalog's documented semantics: CEILING/FLOOR take a required Significance, TRUNC an
|
||||
// optional NumberOfDigits.
|
||||
assert_close(eval("CEILING(4.42, 0.05)"), 4.45);
|
||||
assert_close(eval("CEILING(10.2, 1)"), 11.0);
|
||||
assert_close(eval("CEILING(10.7, 0.5)"), 11.0);
|
||||
// A negative number with a negative significance rounds away from zero.
|
||||
assert_close(eval("CEILING(-2.5, -2)"), -4.0);
|
||||
// ISO.CEILING takes the significance's magnitude and always rounds up.
|
||||
assert_close(eval("ISO.CEILING(-2.5, 2)"), -2.0);
|
||||
assert!(eval_result("CEILING(2.5, -2)").is_err());
|
||||
|
||||
assert_close(eval("FLOOR(27, 5)"), 25.0);
|
||||
assert_close(eval("FLOOR(2.7, 1)"), 2.0);
|
||||
assert_close(eval("FLOOR(-2.7, -1)"), -2.0);
|
||||
assert!(eval_result("FLOOR(-2.7, 1)").is_err());
|
||||
assert!(eval_result("FLOOR(1, 0)").is_err());
|
||||
|
||||
assert_close(eval("TRUNC(1.239, 2)"), 1.23);
|
||||
assert_close(eval("TRUNC(2.71828)"), 2.0);
|
||||
assert_close(eval("TRUNC(-2.71828, 2)"), -2.71);
|
||||
assert_close(eval("TRUNC(1234.5, -2)"), 1200.0);
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
//! Time-intelligence range functions over an in-memory model.
|
||||
//!
|
||||
//! The fixture date table runs from 2022-01-01 to 2025-12-31 so that previous/next year windows
|
||||
//! always have a full calendar to draw from. `Date` is table 0 and `Sales` is table 1; the
|
||||
//! `Sales[Date]` -> `Date[Date]` relationship is the only cross-filtering path.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, TableValue};
|
||||
use gridcraft_dax::{Binder, BoundExpr, Evaluator, FilterContext, Literal, ScalarKey, parse_expression};
|
||||
|
||||
const DATE_TABLE: usize = 0;
|
||||
const DATE_COLUMN: usize = 0;
|
||||
const YEAR_COLUMN: usize = 1;
|
||||
const SALES_TABLE: usize = 1;
|
||||
const AMOUNT_COLUMN: usize = 1;
|
||||
|
||||
/// Excel/OLE date serial, computed with `chrono` independently of the evaluator.
|
||||
fn serial(year: i64, month: i64, day: i64) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn date_rows() -> Vec<Vec<Scalar>> {
|
||||
use chrono::Datelike;
|
||||
let start = chrono::NaiveDate::from_ymd_opt(2022, 1, 1).expect("the fixture start is a valid date");
|
||||
let end = chrono::NaiveDate::from_ymd_opt(2025, 12, 31).expect("the fixture end is a valid date");
|
||||
start
|
||||
.iter_days()
|
||||
.take_while(|date| *date <= end)
|
||||
.map(|date| {
|
||||
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
|
||||
vec![
|
||||
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
|
||||
Scalar::Integer(year),
|
||||
Scalar::Integer((month - 1) / 3 + 1),
|
||||
Scalar::Integer(month),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// (year, month, day, amount) for every sales row.
|
||||
const SALES: &[(i64, i64, i64, f64)] = &[
|
||||
(2023, 1, 10, 10.0),
|
||||
(2023, 3, 5, 20.0),
|
||||
(2023, 6, 15, 30.0),
|
||||
(2023, 9, 20, 40.0),
|
||||
(2023, 12, 31, 50.0),
|
||||
(2024, 1, 5, 100.0),
|
||||
(2024, 1, 31, 200.0),
|
||||
(2024, 2, 29, 300.0),
|
||||
(2024, 3, 15, 400.0),
|
||||
(2024, 4, 1, 500.0),
|
||||
(2024, 6, 30, 600.0),
|
||||
(2024, 9, 30, 700.0),
|
||||
(2024, 11, 11, 800.0),
|
||||
(2024, 12, 25, 900.0),
|
||||
(2024, 12, 31, 1000.0),
|
||||
];
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: date_rows(),
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: SALES
|
||||
.iter()
|
||||
.map(|(year, month, day, amount)| vec![Scalar::DateTime(serial(*year, *month, *day)), Scalar::Decimal(*amount)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Date".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![Measure {
|
||||
name: "Sales Amount".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
/// A three-day date table whose last row's date cell is BLANK: the axis must drop that row instead
|
||||
/// of reading BLANK as serial 0 (1899-12-30).
|
||||
fn model_with_blank_date() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Day".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 3))],
|
||||
vec![Scalar::Blank],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate(source: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
evaluate_in(&model(), source, filters)
|
||||
}
|
||||
|
||||
fn evaluate_in(model: &DataModel, source: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_with(&bound, filters).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval_with(source: &str, filters: FilterContext) -> Scalar {
|
||||
evaluate(source, filters).expect("expression evaluates")
|
||||
}
|
||||
|
||||
fn eval_error(source: &str, filters: FilterContext) -> String {
|
||||
evaluate(source, filters).expect_err("expression must fail")
|
||||
}
|
||||
|
||||
fn evaluate_table(source: &str) -> Result<TableValue, String> {
|
||||
evaluate_table_in(&model(), source)
|
||||
}
|
||||
|
||||
fn evaluate_table_in(model: &DataModel, source: &str) -> Result<TableValue, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn table(source: &str) -> TableValue {
|
||||
evaluate_table(source).expect("table evaluates")
|
||||
}
|
||||
|
||||
/// Filter context selecting the date column between two inclusive calendar days.
|
||||
fn dates(from: (i64, i64, i64), to: (i64, i64, i64)) -> FilterContext {
|
||||
let mut filters = FilterContext::default();
|
||||
let mut keys = Vec::new();
|
||||
let start = serial(from.0, from.1, from.2) as i64;
|
||||
let end = serial(to.0, to.1, to.2) as i64;
|
||||
for day in start..=end {
|
||||
keys.push(ScalarKey::from(&Scalar::DateTime(day as f64)));
|
||||
}
|
||||
filters.set(DATE_TABLE, DATE_COLUMN, keys);
|
||||
filters
|
||||
}
|
||||
|
||||
fn year(year: i64) -> FilterContext {
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(DATE_TABLE, YEAR_COLUMN, [ScalarKey::from(&Scalar::Integer(year))]);
|
||||
filters
|
||||
}
|
||||
|
||||
/// Number of rows of a table expression evaluated under a filter context.
|
||||
fn row_count(source: &str, filters: FilterContext) -> i64 {
|
||||
let count = eval_with(&format!("COUNTROWS({source})"), filters);
|
||||
match count {
|
||||
Scalar::Blank => 0,
|
||||
other => other.to_number().expect("COUNTROWS is numeric") as i64,
|
||||
}
|
||||
}
|
||||
|
||||
/// (first, last) date of a table expression evaluated under a filter context.
|
||||
fn bounds(source: &str, filters: FilterContext) -> (f64, f64) {
|
||||
let first = eval_with(&format!("MINX({source}, 'Date'[Date])"), filters.clone());
|
||||
let last = eval_with(&format!("MAXX({source}, 'Date'[Date])"), filters);
|
||||
(first.to_number().expect("first date"), last.to_number().expect("last date"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_shifts_the_visible_period() {
|
||||
let march = dates((2024, 3, 1), (2024, 3, 31));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), 29);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
// A partial period keeps its day span.
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 10, \"DAY\")", dates((2024, 3, 25), (2024, 3, 31))), (serial(2024, 4, 4), serial(2024, 4, 10)));
|
||||
// A selection ending on the last day of its period extends to the whole target period.
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"QUARTER\")", dates((2024, 4, 1), (2024, 6, 30))), 91);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", dates((2024, 2, 25), (2024, 2, 29))), (serial(2024, 3, 25), serial(2024, 3, 31)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2024, 3, 1), (2024, 3, 31))), 31);
|
||||
|
||||
let error = eval_error("DATEADD('Date'[Date], 1, \"DECADE\")", FilterContext::default());
|
||||
assert!(error.contains("interval"), "{error}");
|
||||
let error = eval_error("DATEADD(Sales[Amount], 1, \"DAY\")", FilterContext::default());
|
||||
assert!(error.contains("DateTime"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_rejects_a_non_contiguous_selection() {
|
||||
// A complete date column filtered to May 1 and May 3 has a gap at May 2. Shifting the window
|
||||
// would sweep in May 3's source day (and any blocked day inside the range), which Microsoft's
|
||||
// date-column DATEADD contract forbids: the visible dates must be contiguous.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
DATE_TABLE,
|
||||
DATE_COLUMN,
|
||||
[ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 1))), ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 3)))],
|
||||
);
|
||||
let error = eval_error("DATEADD('Date'[Date], 1, \"DAY\")", filters.clone());
|
||||
assert!(error.contains("contiguous"), "{error}");
|
||||
assert!(error.contains("5/1/2024") && error.contains("5/3/2024"), "{error}");
|
||||
// The contract covers every interval, not just days.
|
||||
for interval in ["MONTH", "QUARTER", "YEAR"] {
|
||||
let source = format!("DATEADD('Date'[Date], 1, \"{interval}\")");
|
||||
let error = eval_error(&source, filters.clone());
|
||||
assert!(error.contains("contiguous"), "{error}");
|
||||
}
|
||||
// A contiguous selection still shifts: May 1-2 to May 2-3, and a single day to its neighbour.
|
||||
let contiguous = dates((2024, 5, 1), (2024, 5, 2));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", contiguous.clone()), (serial(2024, 5, 2), serial(2024, 5, 3)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"DAY\")", contiguous), 2);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", dates((2024, 5, 1), (2024, 5, 1))), (serial(2024, 5, 2), serial(2024, 5, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_date_cells_are_not_axis_dates() {
|
||||
let model = model_with_blank_date();
|
||||
// BLANK is not serial 0, so it must not become the first visible date (1899-12-30) or an axis
|
||||
// row that the range functions can select.
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Day'[Date])", FilterContext::default()).expect("first date"), Scalar::DateTime(serial(2024, 1, 1)));
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Day'[Date])", FilterContext::default()).expect("last date"), Scalar::DateTime(serial(2024, 1, 3)));
|
||||
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(1899,12,30), DATE(1899,12,30))").expect("epoch day").rows.len(), 0);
|
||||
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(2024,1,1), DATE(2024,1,3))").expect("window").rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datesbetween_is_inclusive_and_accepts_blanks() {
|
||||
let between = table("DATESBETWEEN('Date'[Date], DATE(2024, 1, 15), DATE(2024, 2, 10))");
|
||||
assert_eq!(between.rows.len(), 27);
|
||||
assert_eq!(between.columns.len(), 1);
|
||||
assert_eq!(between.columns[0].name, "Date");
|
||||
assert_eq!(between.lineage, Some(DATE_TABLE));
|
||||
assert_eq!(between.rows[0][0], Scalar::DateTime(serial(2024, 1, 15)));
|
||||
assert_eq!(between.rows[26][0], Scalar::DateTime(serial(2024, 2, 10)));
|
||||
|
||||
// BLANK boundaries fall back to the visible range.
|
||||
assert_eq!(row_count("DATESBETWEEN('Date'[Date], BLANK(), DATE(2024, 1, 5))", FilterContext::default()), 735);
|
||||
assert_eq!(row_count("DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), BLANK())", FilterContext::default()), 731);
|
||||
|
||||
assert_eq!(table("DATESBETWEEN('Date'[Date], DATE(2024, 2, 1), DATE(2024, 1, 1))").rows.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datesinperiod_moves_backwards_from_the_start_date() {
|
||||
let backwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -1, \"MONTH\")");
|
||||
assert_eq!(backwards.rows.len(), 29);
|
||||
assert_eq!(backwards.rows[0][0], Scalar::DateTime(serial(2024, 2, 16)));
|
||||
assert_eq!(backwards.rows[28][0], Scalar::DateTime(serial(2024, 3, 15)));
|
||||
|
||||
let forwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 3, \"DAY\")");
|
||||
assert_eq!(forwards.rows.len(), 3);
|
||||
assert_eq!(forwards.rows[2][0], Scalar::DateTime(serial(2024, 3, 17)));
|
||||
assert_eq!(table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 0, \"DAY\")").rows.len(), 0);
|
||||
assert_eq!(
|
||||
bounds("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -2, \"WEEK\")", FilterContext::default()),
|
||||
(serial(2024, 3, 2), serial(2024, 3, 15))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_date_windows() {
|
||||
assert_eq!(bounds("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), (serial(2024, 3, 1), serial(2024, 3, 20)));
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), 20);
|
||||
assert_eq!(row_count("DATESQTD('Date'[Date])", dates((2024, 5, 1), (2024, 5, 10))), 40);
|
||||
assert_eq!(row_count("DATESWTD('Date')", dates((2024, 3, 13), (2024, 3, 15))), 6);
|
||||
assert_eq!(row_count("DATESYTD('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), 75);
|
||||
// A fiscal year ending June 30 starts on July 1.
|
||||
assert_eq!(row_count("DATESYTD('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), 46);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_boundaries() {
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 5)));
|
||||
assert_eq!(eval_with("LASTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 20)));
|
||||
let first = table("FIRSTDATE('Date'[Date])");
|
||||
assert_eq!(first.rows.len(), 1);
|
||||
assert_eq!(first.lineage, Some(DATE_TABLE));
|
||||
|
||||
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 1)));
|
||||
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", dates((2024, 2, 1), (2024, 2, 10))), Scalar::DateTime(serial(2024, 2, 29)));
|
||||
assert_eq!(eval_with("STARTOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 4, 1)));
|
||||
assert_eq!(eval_with("ENDOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 6, 30)));
|
||||
assert_eq!(eval_with("STARTOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 10)));
|
||||
assert_eq!(eval_with("ENDOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
assert_eq!(eval_with("STARTOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 1, 1)));
|
||||
assert_eq!(eval_with("ENDOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 12, 31)));
|
||||
assert_eq!(eval_with("STARTOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2023, 7, 1)));
|
||||
assert_eq!(eval_with("ENDOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), Scalar::DateTime(serial(2025, 6, 30)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_periods() {
|
||||
assert_eq!(eval_with("NEXTDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
assert_eq!(eval_with("PREVIOUSDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 14)));
|
||||
|
||||
assert_eq!(bounds("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 4, 1), serial(2024, 4, 30)));
|
||||
assert_eq!(bounds("PREVIOUSMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
assert_eq!(row_count("NEXTQUARTER('Date'[Date])", dates((2024, 2, 1), (2024, 2, 28))), 91);
|
||||
assert_eq!(row_count("PREVIOUSQUARTER('Date'[Date])", dates((2024, 5, 1), (2024, 5, 31))), 91);
|
||||
assert_eq!(bounds("NEXTWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 17), serial(2024, 3, 23)));
|
||||
assert_eq!(bounds("PREVIOUSWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 3), serial(2024, 3, 9)));
|
||||
assert_eq!(bounds("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2025, 1, 1), serial(2025, 12, 31)));
|
||||
assert_eq!(row_count("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 365);
|
||||
assert_eq!(bounds("PREVIOUSYEAR('Date'[Date])", dates((2024, 1, 10), (2024, 1, 20))), (serial(2023, 1, 1), serial(2023, 12, 31)));
|
||||
|
||||
// A partial period is expanded to the full parallel period.
|
||||
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], -1, \"MONTH\")", dates((2024, 3, 15), (2024, 3, 20))), 29);
|
||||
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], 0, \"YEAR\")", dates((2024, 3, 15), (2024, 3, 20))), 366);
|
||||
assert_eq!(row_count("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 31);
|
||||
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2023, 3, 1), serial(2023, 3, 31)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonblank_scan_uses_the_value_expression() {
|
||||
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 1, 10)));
|
||||
assert_eq!(eval_with("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 12, 31)));
|
||||
assert_eq!(row_count("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), 1);
|
||||
// An aggregate expression works too: it is evaluated in the date row's context.
|
||||
assert_eq!(
|
||||
eval_with("LASTNONBLANK('Date'[Date], SUM(Sales[Amount]))", dates((2024, 1, 1), (2024, 6, 30))),
|
||||
Scalar::DateTime(serial(2024, 6, 30))
|
||||
);
|
||||
// No sales at all in 2025: nothing is non-blank.
|
||||
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), Scalar::Blank);
|
||||
assert_eq!(row_count("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_tables_drive_calculate() {
|
||||
let march = dates((2024, 3, 1), (2024, 3, 31));
|
||||
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), DATESMTD('Date'[Date]))", march.clone()), Scalar::Decimal(400.0));
|
||||
assert_eq!(eval_with("CALCULATE([Sales Amount], SAMEPERIODLASTYEAR('Date'[Date]))", march), Scalar::Decimal(20.0));
|
||||
assert_eq!(eval_with("CALCULATE([Sales Amount], PREVIOUSYEAR('Date'[Date]))", dates((2024, 1, 10), (2024, 1, 20))), Scalar::Decimal(150.0));
|
||||
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), ENDOFMONTH('Date'[Date]))", dates((2024, 2, 1), (2024, 2, 10))), Scalar::Decimal(300.0));
|
||||
assert_eq!(eval_with("CALCULATE(COUNTROWS('Date'), FIRSTDATE('Date'[Date]))", dates((2024, 3, 1), (2024, 3, 31))), Scalar::Integer(1));
|
||||
// Rolling twelve months ending December 31, 2024.
|
||||
assert_eq!(
|
||||
eval_with("CALCULATE(SUM(Sales[Amount]), DATESINPERIOD('Date'[Date], DATE(2024, 12, 31), -12, \"MONTH\"))", FilterContext::default()),
|
||||
Scalar::Decimal(5500.0)
|
||||
);
|
||||
assert_eq!(
|
||||
eval_with("CALCULATE(SUM(Sales[Amount]), DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), DATE(2024, 3, 31)))", FilterContext::default()),
|
||||
Scalar::Decimal(1000.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_row_results_are_not_scalars() {
|
||||
let error = eval_error("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
|
||||
assert!(error.contains("rows"), "{error}");
|
||||
let error = eval_error("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
|
||||
assert!(error.contains("rows"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_results_are_scalars() {
|
||||
let filters = dates((2024, 3, 15), (2024, 3, 15));
|
||||
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 1)));
|
||||
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 31)));
|
||||
assert_eq!(eval_with("NEXTDAY('Date'[Date])", filters), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_filter_context_yields_empty_windows() {
|
||||
// An empty date-column filter leaves nothing visible.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(DATE_TABLE, DATE_COLUMN, Vec::<ScalarKey>::new());
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", filters.clone()), 0);
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::Blank);
|
||||
assert_eq!(eval_with("LASTDATE('Date'[Date])", filters), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_filters_do_not_narrow_the_date_axis() {
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(SALES_TABLE, AMOUNT_COLUMN, [ScalarKey::from(&Scalar::Decimal(400.0))]);
|
||||
// Only one sale matches, but the date table itself is unfiltered.
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2022, 1, 1)));
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", filters), 31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interval_keywords_reach_the_evaluator_as_keywords() {
|
||||
// The binder turns a bare interval keyword (DATEADD(..., MONTH)) into `BoundExpr::Keyword`;
|
||||
// build that shape directly so the evaluator path is covered independently of the binder.
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let dateadd = BoundExpr::Call {
|
||||
spec: gridcraft_dax::lookup("DATEADD").expect("DATEADD is catalogued"),
|
||||
args: vec![
|
||||
BoundExpr::Column { table: DATE_TABLE, column: DATE_COLUMN },
|
||||
BoundExpr::Literal(Literal::Integer(-1)),
|
||||
BoundExpr::Keyword("MONTH".into()),
|
||||
],
|
||||
};
|
||||
let countrows = BoundExpr::Call { spec: gridcraft_dax::lookup("COUNTROWS").expect("COUNTROWS is catalogued"), args: vec![dateadd] };
|
||||
let count = evaluator.evaluate_with(&countrows, dates((2024, 3, 1), (2024, 3, 31))).expect("count");
|
||||
assert_eq!(count, Scalar::Integer(29));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn week_functions_accept_a_table_reference() {
|
||||
let filters = dates((2024, 3, 13), (2024, 3, 13));
|
||||
assert_eq!(row_count("DATESWTD('Date')", filters.clone()), 4);
|
||||
assert_eq!(eval_with("STARTOFWEEK('Date')", filters), Scalar::DateTime(serial(2024, 3, 10)));
|
||||
let error = eval_error("DATESWTD('Date'[Date])", FilterContext::default());
|
||||
assert!(error.contains("table"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_and_sameperiodlastyear_keep_the_leap_day_of_a_full_month() {
|
||||
// A full February shifted back a year reaches 29 February 2024, not 28.
|
||||
let february = dates((2025, 2, 1), (2025, 2, 28));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", february.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", february), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
// A selection ending mid-month keeps its day span.
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2025, 2, 1), (2025, 2, 15))), (serial(2024, 2, 1), serial(2024, 2, 15)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_extend_a_selection_ending_on_the_penultimate_day() {
|
||||
// 29 April is its month's penultimate day, but the selection does not contain 30 April, so
|
||||
// the shifted window keeps its day span instead of reaching 31 March.
|
||||
let selection = dates((2024, 4, 1), (2024, 4, 29));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", selection.clone()), (serial(2024, 3, 1), serial(2024, 3, 29)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", selection), 29);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_extend_a_selection_ending_on_day_30_of_a_31_day_month() {
|
||||
// 30 July is one day before its month end, but 31 July is not visible, so the shifted window
|
||||
// stops on 30 August instead of extending to 31 August.
|
||||
let selection = dates((2024, 7, 1), (2024, 7, 30));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 8, 1), serial(2024, 8, 30)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_expand_a_single_month_end_date_to_the_target_period() {
|
||||
// Only 30 April 2024 is visible: the date shifts to 30 May and stays a single date instead of
|
||||
// expanding to the end of May (or the whole target period).
|
||||
let selection = dates((2024, 4, 30), (2024, 4, 30));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 5, 30), serial(2024, 5, 30)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_day_timestamps_stay_in_the_date_axis() {
|
||||
// Two timestamps sharing a day are distinct cells of the column, and the range tables key
|
||||
// their filter on those exact values, so both rows have to survive the axis.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let table = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,2), DATE(2024,1,2))").expect("window");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(table.rows[0][0], Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
|
||||
assert_eq!(table.rows[1][0], Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0));
|
||||
// The other days are untouched by the value-level deduplication.
|
||||
let whole = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,1), DATE(2024,1,2))").expect("whole window");
|
||||
assert_eq!(whole.rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_functions_pick_one_cell_of_a_day() {
|
||||
// A day can hold several timestamps; `FIRSTDATE`/`LASTDATE` are scalar conveniences and must
|
||||
// return one exact cell rather than every cell of the day.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "LASTDATE('Log'[Stamp])", FilterContext::default()).expect("last date"),
|
||||
Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)
|
||||
);
|
||||
|
||||
// Filtered to the first day, which holds two timestamps: `FIRSTDATE` still returns one value.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
0,
|
||||
0,
|
||||
[Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0), Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]
|
||||
.into_iter()
|
||||
.map(|value| ScalarKey::from(&value)),
|
||||
);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters).expect("first date"), Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_functions_stay_inside_the_visible_cells() {
|
||||
// A filter that selects one timestamp of a two-timestamp day: `FIRSTDATE`/`LASTDATE` must pick
|
||||
// from the selected cell, not from the other timestamp the same day holds.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let early = Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0);
|
||||
let late = Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0);
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(0, 0, [ScalarKey::from(&late)]);
|
||||
|
||||
// 14:00 is the only visible cell: the last date is it, even though 09:00 exists in the column.
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", filters.clone()).expect("last date"), late);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters.clone()).expect("first date"), late);
|
||||
|
||||
let mut early_filters = FilterContext::default();
|
||||
early_filters.set(0, 0, [ScalarKey::from(&early)]);
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", early_filters.clone()).expect("last date"), early);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", early_filters).expect("first date"), early);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonblank_candidates_match_mixed_case_text_rows() {
|
||||
// The candidate filter is written through `FilterContext::set`, which folds text the same way
|
||||
// the filter's own comparison does: a candidate `"A"` has to select the `"A"` and `"a"` rows.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "T".into(),
|
||||
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("a".into())], vec![Scalar::String("B".into())]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![gridcraft_dax::model::Measure {
|
||||
name: "Rows".into(),
|
||||
formula: "COUNTROWS('T')".into(),
|
||||
table: Some("T".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
// Only the folded candidate filter leaves rows for the expression; an unfolded key would match
|
||||
// nothing and make every candidate blank.
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "FIRSTNONBLANK('T'[Text], IF([Rows] = 0, BLANK(), 1))", FilterContext::default()).expect("first non blank"),
|
||||
Scalar::String("A".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_ends_pick_the_latest_timestamp_of_a_day() {
|
||||
// A day may hold several timestamps; the axis orders them by their full serial, so `ENDOFMONTH`
|
||||
// returns the latest one even when the model stores it before or after its siblings.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
0,
|
||||
0,
|
||||
[Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0), Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]
|
||||
.into_iter()
|
||||
.map(|value| ScalarKey::from(&value)),
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "ENDOFMONTH('Log'[Stamp])", filters.clone()).expect("end of month"),
|
||||
Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "STARTOFMONTH('Log'[Stamp])", filters).expect("start of month"),
|
||||
Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_impossible_year_end_date_is_rejected_by_the_range_functions() {
|
||||
// The same validation the total functions use: `"2/30"` is not a date, while the documented
|
||||
// `"6/30/2024"` and `"6/30"` forms are.
|
||||
let model = model();
|
||||
let count = |argument: &str| evaluate_in(&model, &format!("COUNTROWS(DATESYTD('Date'[Date], \"{argument}\"))"), FilterContext::default());
|
||||
assert!(count("2/30").is_err());
|
||||
// An empty component is not a date either.
|
||||
assert!(count("6/-30").is_err());
|
||||
assert!(count("6/").is_err());
|
||||
assert!(count("6/30").is_ok());
|
||||
assert!(count("6/30/2024").is_ok());
|
||||
assert!(count("2/29").is_ok());
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
//! Integration tests for the time-intelligence totals and balance evaluator functions.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, ScalarKey};
|
||||
use gridcraft_dax::{BoundExpr, Evaluator, FilterContext, Literal, lookup};
|
||||
|
||||
/// The calendar date of a whole-day Excel/OLE serial, via `chrono`.
|
||||
fn date_of(value: f64) -> chrono::NaiveDate {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
epoch + chrono::Duration::days(value.floor() as i64)
|
||||
}
|
||||
|
||||
/// Excel/OLE date serial for a whole day, computed with `chrono`.
|
||||
fn serial(year: i64, month: i64, day: i64) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn date(year: i64, month: i64, day: i64) -> Scalar {
|
||||
Scalar::DateTime(serial(year, month, day))
|
||||
}
|
||||
|
||||
/// The fixture shared with the worksheet/measure cases: Sales facts for 2023-2024 and a
|
||||
/// contiguous Date table covering both years.
|
||||
fn model() -> DataModel {
|
||||
use chrono::Datelike;
|
||||
let start = date_of(serial(2023, 1, 1));
|
||||
let end = date_of(serial(2024, 12, 31));
|
||||
let date_rows: Vec<Vec<Scalar>> = start
|
||||
.iter_days()
|
||||
.take_while(|date| *date <= end)
|
||||
.map(|date| {
|
||||
// Excel's weekday numbering is 1 = Sunday, matching the evaluator's WEEKDAY default.
|
||||
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
|
||||
vec![
|
||||
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
|
||||
Scalar::Integer(year),
|
||||
Scalar::Integer((month - 1) / 3 + 1),
|
||||
Scalar::Integer(month),
|
||||
Scalar::Integer(i64::from(date.weekday().num_days_from_sunday()) + 1),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(40), date(2024, 1, 3)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(100), date(2024, 1, 5)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(250), date(2024, 1, 12)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(75), date(2024, 2, 3)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(400), date(2024, 2, 20)],
|
||||
vec![Scalar::String("East".into()), Scalar::Blank, date(2024, 3, 15)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(150), date(2024, 4, 1)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(300), date(2024, 6, 18)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(50), date(2024, 7, 7)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(220), date(2024, 9, 9)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(90), date(2024, 11, 11)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(180), date(2024, 12, 1)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(310), date(2024, 12, 25)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(60), date(2023, 3, 10)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(140), date(2023, 6, 15)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(200), date(2023, 9, 20)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(80), date(2023, 12, 5)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Weekday".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: date_rows,
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Date".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
measure("Total Amount", "SUM(Sales[Amount])"),
|
||||
measure("MTD", "TOTALMTD([Total Amount], 'Date'[Date])"),
|
||||
measure("QTD", "TOTALQTD([Total Amount], 'Date'[Date])"),
|
||||
measure("WTD", "TOTALWTD([Total Amount], Date)"),
|
||||
measure("YTD", "TOTALYTD([Total Amount], 'Date'[Date])"),
|
||||
measure("YTD June", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("YTD All", "TOTALYTD([Total Amount], 'Date'[Date], ALL ())"),
|
||||
measure("QTD Remove All", "TOTALQTD([Total Amount], 'Date'[Date], REMOVEFILTERS ())"),
|
||||
measure("YTD Region All", "TOTALYTD([Total Amount], 'Date'[Date], ALL([Region]))"),
|
||||
measure("YTD Over Ten", "TOTALYTD(SUM(Sales[Amount]), 'Date'[Date], Sales[Amount] > 100)"),
|
||||
measure("YTD Unqualified", "TOTALYTD([Total Amount], 'Date'[Date], [Region] = \"East\")"),
|
||||
measure("OB Month", "OPENINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Month", "CLOSINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Quarter", "OPENINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Quarter", "CLOSINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Week", "OPENINGBALANCEWEEK([Total Amount], Date)"),
|
||||
measure("CB Week", "CLOSINGBALANCEWEEK([Total Amount], Date)"),
|
||||
measure("OB Year", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Year", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Year June", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("CB Year June", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("First Non Blank", "FIRSTNONBLANKVALUE('Date'[Date], [Total Amount])"),
|
||||
measure("Last Non Blank", "LASTNONBLANKVALUE('Date'[Date], [Total Amount])"),
|
||||
measure("Bad Date Column", "TOTALMTD([Total Amount], Sales[Amount])"),
|
||||
measure("Bad Filter", "TOTALMTD([Total Amount], 'Date'[Date], 1)"),
|
||||
measure("Bad Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"not a date\")"),
|
||||
measure("Impossible Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"2/30\")"),
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
model
|
||||
}
|
||||
|
||||
fn measure(name: &str, formula: &str) -> Measure {
|
||||
Measure { name: name.into(), formula: formula.into(), table: Some("Sales".into()), format: None, expr: None }
|
||||
}
|
||||
|
||||
fn filters(model: &DataModel, pairs: &[(&str, &str, Scalar)]) -> FilterContext {
|
||||
let mut context = FilterContext::default();
|
||||
for (table, column, value) in pairs {
|
||||
let table_index = model.table_index(table).expect("table exists");
|
||||
let column_index = model.column_index(table_index, column).expect("column exists");
|
||||
context.set(table_index, column_index, [ScalarKey::from(value)]);
|
||||
}
|
||||
context
|
||||
}
|
||||
|
||||
fn date_filter(model: &DataModel, dates: &[Scalar]) -> FilterContext {
|
||||
let table = model.table_index("Date").expect("Date table");
|
||||
let column = model.column_index(table, "Date").expect("Date column");
|
||||
let mut context = FilterContext::default();
|
||||
context.set(table, column, dates.iter().map(ScalarKey::from));
|
||||
context
|
||||
}
|
||||
|
||||
fn eval_measure(model: &DataModel, name: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_measure(name, filters).map_err(|error| format!("{name}: {error}"))
|
||||
}
|
||||
|
||||
fn assert_number(result: Result<Scalar, String>, expected: f64) {
|
||||
match result {
|
||||
Ok(value) => {
|
||||
let actual = value.to_number().expect("numeric result");
|
||||
assert!((actual - expected).abs() < 1e-9, "expected {expected}, got {actual} ({value:?})");
|
||||
}
|
||||
Err(error) => panic!("unexpected error: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn february_filter(model: &DataModel) -> FilterContext {
|
||||
filters(model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_to_date_totals() {
|
||||
let model = model();
|
||||
let february = february_filter(&model);
|
||||
// February 2024: 2024-02-03 (75) + 2024-02-20 (400); January 2024: 40 + 100 + 250.
|
||||
assert_number(eval_measure(&model, "MTD", february.clone()), 475.0);
|
||||
assert_number(eval_measure(&model, "QTD", february.clone()), 865.0);
|
||||
assert_number(eval_measure(&model, "YTD", february.clone()), 865.0);
|
||||
// Fiscal year ending June 30: H2 2023 (200 + 80) plus the 2024 YTD window.
|
||||
assert_number(eval_measure(&model, "YTD June", february), 1145.0);
|
||||
|
||||
let january = date_filter(&model, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&model, "MTD", january.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "QTD", january.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "YTD", january.clone()), 140.0);
|
||||
// 2024-01-05 is a Friday: the DAX week starts on Sunday 2023-12-31.
|
||||
assert_number(eval_measure(&model, "WTD", january), 140.0);
|
||||
|
||||
let second_friday = date_filter(&model, &[date(2024, 1, 12)]);
|
||||
assert_number(eval_measure(&model, "WTD", second_friday), 250.0);
|
||||
|
||||
// The last visible date anchors the window: Feb 28 only, not the whole month.
|
||||
let partial = date_filter(&model, &[date(2024, 1, 5), date(2024, 2, 28)]);
|
||||
assert_number(eval_measure(&model, "MTD", partial.clone()), 475.0);
|
||||
assert_number(eval_measure(&model, "QTD", partial.clone()), 865.0);
|
||||
// No sale in the week of 2024-02-28 (Sunday 25th to Saturday 2nd), so the sum is blank.
|
||||
assert_eq!(eval_measure(&model, "WTD", partial), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_and_closing_balances() {
|
||||
// Boundary dates need facts: add one sale on every date the balance functions select.
|
||||
let mut facts = model();
|
||||
let boundaries = [
|
||||
(2023, 6, 30, 900),
|
||||
(2023, 12, 30, 450),
|
||||
(2023, 12, 31, 500),
|
||||
(2024, 1, 6, 550),
|
||||
(2024, 1, 13, 650),
|
||||
(2024, 1, 31, 600),
|
||||
(2024, 2, 29, 700),
|
||||
(2024, 3, 31, 800),
|
||||
(2024, 6, 30, 950),
|
||||
(2024, 12, 31, 1000),
|
||||
];
|
||||
let sales = &mut facts.tables[0].rows;
|
||||
for (year, month, day, amount) in boundaries {
|
||||
sales.push(vec![Scalar::String("Boundary".into()), Scalar::Integer(amount), date(year, month, day)]);
|
||||
}
|
||||
|
||||
let february = february_filter(&facts);
|
||||
// EXCEL: CLOSINGBALANCEMONTH = CALCULATE(expr, ENDOFMONTH(dates)), OPENING = previous day.
|
||||
assert_number(eval_measure(&facts, "OB Month", february.clone()), 600.0);
|
||||
assert_number(eval_measure(&facts, "CB Month", february.clone()), 700.0);
|
||||
assert_number(eval_measure(&facts, "OB Quarter", february.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Quarter", february.clone()), 800.0);
|
||||
assert_number(eval_measure(&facts, "OB Year", february.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Year", february.clone()), 1000.0);
|
||||
// Fiscal year July 2023 - June 2024: opening is 2023-06-30, closing is 2024-06-30.
|
||||
assert_number(eval_measure(&facts, "OB Year June", february.clone()), 900.0);
|
||||
assert_number(eval_measure(&facts, "CB Year June", february), 950.0);
|
||||
|
||||
let january = date_filter(&facts, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&facts, "OB Month", january.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Month", january.clone()), 600.0);
|
||||
// The DAX week starts on Sunday 2023-12-31, so the opening date is 2023-12-30.
|
||||
assert_number(eval_measure(&facts, "OB Week", january.clone()), 450.0);
|
||||
assert_number(eval_measure(&facts, "CB Week", january), 550.0);
|
||||
|
||||
let second_week = date_filter(&facts, &[date(2024, 1, 12)]);
|
||||
assert_number(eval_measure(&facts, "OB Week", second_week.clone()), 550.0);
|
||||
assert_number(eval_measure(&facts, "CB Week", second_week), 650.0);
|
||||
|
||||
// March 31 carries a boundary fact, so the closing balance is that day's value.
|
||||
let march = filters(&facts, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
|
||||
assert_eq!(eval_measure(&facts, "CB Month", march), Ok(Scalar::Decimal(800.0)));
|
||||
|
||||
// Without a fact on the boundary date Excel returns BLANK, not a scan backwards.
|
||||
let sparse = model();
|
||||
let february = february_filter(&sparse);
|
||||
assert_eq!(eval_measure(&sparse, "OB Month", february.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&sparse, "CB Month", february), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_and_last_non_blank_values() {
|
||||
let model = model();
|
||||
let february = february_filter(&model);
|
||||
assert_number(eval_measure(&model, "First Non Blank", february.clone()), 75.0);
|
||||
assert_number(eval_measure(&model, "Last Non Blank", february.clone()), 400.0);
|
||||
|
||||
let january = date_filter(&model, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&model, "First Non Blank", january.clone()), 100.0);
|
||||
assert_number(eval_measure(&model, "Last Non Blank", january), 100.0);
|
||||
|
||||
let march = filters(&model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
|
||||
assert_eq!(eval_measure(&model, "First Non Blank", march.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "Last Non Blank", march), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_clears_the_outer_filter_context() {
|
||||
let model = model();
|
||||
// February 2024 restricted to the East region: the outer filter sits on the fact table, the
|
||||
// date filters only anchor the window.
|
||||
let east_february = filters(
|
||||
&model,
|
||||
&[("Sales", "Region", Scalar::String("East".into())), ("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))],
|
||||
);
|
||||
// Without a filter argument the region filter still applies: East only, January + February.
|
||||
assert_number(eval_measure(&model, "YTD", east_february.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "QTD", east_february.clone()), 140.0);
|
||||
|
||||
// `ALL ()` clears the whole filter context, so every region is visible again over the same
|
||||
// year-to-date window (40 + 100 + 250 + 75 + 400 = 865).
|
||||
assert_number(eval_measure(&model, "YTD All", east_february.clone()), 865.0);
|
||||
// `REMOVEFILTERS ()` is the same modifier.
|
||||
assert_number(eval_measure(&model, "QTD Remove All", east_february.clone()), 865.0);
|
||||
// An unqualified column argument clears just that column: `[Region]` resolves to Sales[Region].
|
||||
assert_number(eval_measure(&model, "YTD Region All", east_february), 865.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_window_and_invalid_arguments() {
|
||||
let model = model();
|
||||
|
||||
// A date filter outside the model's date range leaves nothing visible.
|
||||
let outside = date_filter(&model, &[date(2030, 1, 1)]);
|
||||
assert_eq!(eval_measure(&model, "MTD", outside.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "CB Month", outside.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "First Non Blank", outside), Ok(Scalar::Blank));
|
||||
|
||||
let error = eval_measure(&model, "Bad Date Column", FilterContext::default()).expect_err("amount is not a date");
|
||||
assert!(error.contains("not a date column"), "{error}");
|
||||
|
||||
let error = eval_measure(&model, "Bad Filter", FilterContext::default()).expect_err("invalid filter");
|
||||
assert!(error.contains("table expression"), "{error}");
|
||||
|
||||
let error = eval_measure(&model, "Bad Year End", FilterContext::default()).expect_err("invalid year end");
|
||||
assert!(error.contains("YearEndDate"), "{error}");
|
||||
// The range functions share the parser, so an impossible day is rejected here too.
|
||||
let error = eval_measure(&model, "Impossible Year End", FilterContext::default()).expect_err("2/30 is not a date");
|
||||
assert!(error.contains("YearEndDate"), "{error}");
|
||||
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let spec = lookup("TOTALMTD").expect("catalog entry");
|
||||
let error = evaluator.evaluate(&BoundExpr::Call { spec, args: Vec::new() }).expect_err("arity");
|
||||
assert!(error.message.contains("between 2 and 3"), "{}", error.message);
|
||||
|
||||
let spec = lookup("FIRSTNONBLANKVALUE").expect("catalog entry");
|
||||
let measure_index = model.measure_index("Total Amount").expect("measure");
|
||||
let expr = BoundExpr::Call { spec, args: vec![BoundExpr::Literal(Literal::Integer(1)), BoundExpr::Measure(measure_index)] };
|
||||
let error = evaluator.evaluate(&expr).expect_err("non-column argument");
|
||||
assert!(error.message.contains("column reference"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_and_unqualified_column_filters_are_applied() {
|
||||
// `TOTALYTD(expr, dates, filter)` is CALCULATE sugar: a comparison and an unqualified column
|
||||
// are filter arguments too, not table expressions.
|
||||
let model = model();
|
||||
let february = date_filter(&model, &[Scalar::DateTime(serial(2024, 2, 1)), Scalar::DateTime(serial(2024, 2, 29))]);
|
||||
let plain = eval_measure(&model, "YTD", february.clone()).expect("YTD");
|
||||
let filtered = eval_measure(&model, "YTD Over Ten", february).expect("YTD Over Ten");
|
||||
// Exact totals, so a filter argument the evaluator ignored could not pass: every 2024
|
||||
// January-February amount is above 10 but only two are above 100.
|
||||
assert_eq!(plain.to_number(), Some(865.0));
|
||||
assert_eq!(filtered.to_number(), Some(650.0));
|
||||
let east = eval_measure(&model, "YTD Unqualified", FilterContext::default()).expect("YTD Unqualified");
|
||||
assert_eq!(east.to_number(), Some(360.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_dimension_filters_reach_the_visible_date_range() {
|
||||
// Snowflaked calendar: `Date` is many-to-one against a `Year` dimension on its one side.
|
||||
// Filtering `Year` propagates to `Date`, so the dates visible to the range functions narrow
|
||||
// to the filtered year instead of spanning the whole model calendar.
|
||||
let mut model = model();
|
||||
model.tables.push(ModelTable {
|
||||
name: "Year".into(),
|
||||
columns: vec![ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(2023)], vec![Scalar::Integer(2024)]],
|
||||
});
|
||||
model.relationships.push(Relationship {
|
||||
from_table: "Date".into(),
|
||||
from_column: "Year".into(),
|
||||
to_table: "Year".into(),
|
||||
to_column: "Year".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
});
|
||||
model.measures.push(measure("Last Date", "LASTDATE('Date'[Date])"));
|
||||
model.measures.push(measure("First Date", "FIRSTDATE('Date'[Date])"));
|
||||
model.measures.push(measure("Dates YTD Rows", "COUNTROWS(DATESYTD('Date'[Date]))"));
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
let y2023 = filters(&model, &[("Year", "Year", Scalar::Integer(2023))]);
|
||||
// The axis ends on the last date of the year the relationship selects, not on the model's
|
||||
// overall last date (2024-12-31).
|
||||
assert_eq!(eval_measure(&model, "Last Date", y2023.clone()), Ok(date(2023, 12, 31)));
|
||||
assert_eq!(eval_measure(&model, "First Date", y2023.clone()), Ok(date(2023, 1, 1)));
|
||||
// 2023 is not a leap year: 365 days in the year-to-date window, not the 366 of 2024.
|
||||
assert_number(eval_measure(&model, "Dates YTD Rows", y2023.clone()), 365.0);
|
||||
// The year-to-date total is 2023's own facts: 60 + 140 + 200 + 80.
|
||||
assert_number(eval_measure(&model, "YTD", y2023.clone()), 480.0);
|
||||
|
||||
let y2024 = filters(&model, &[("Year", "Year", Scalar::Integer(2024))]);
|
||||
assert_eq!(eval_measure(&model, "Last Date", y2024.clone()), Ok(date(2024, 12, 31)));
|
||||
assert_number(eval_measure(&model, "Dates YTD Rows", y2024.clone()), 366.0);
|
||||
// 2024's facts: 40 + 100 + 250 + 75 + 400 + 150 + 300 + 50 + 220 + 90 + 180 + 310.
|
||||
assert_number(eval_measure(&model, "YTD", y2024), 2165.0);
|
||||
}
|
||||
|
||||
/// Fixtures for the two fact-table cases: a model whose date column is a fact column, so there is
|
||||
/// no date dimension whose filters the window may replace.
|
||||
fn fact_date_model(mut measures: Vec<Measure>, rows: Vec<Vec<Scalar>>, amount_type: &str) -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some(amount_type.into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows,
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: std::mem::take(&mut measures),
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
model
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_date_totals_keep_the_other_fact_filters() {
|
||||
// The date column is a fact column, so the window replaces only that column's filter: the
|
||||
// Region slice has to keep applying, as it would to `CALCULATE ( SUM (…), DATESYTD (…) )`.
|
||||
let model = fact_date_model(
|
||||
vec![measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"), measure("MTD Fact", "TOTALMTD(SUM(Sales[Amount]), Sales[Date])")],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), date(2024, 1, 10)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(20), date(2024, 3, 10)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(100), date(2024, 1, 20)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
let east = filters(&model, &[("Sales", "Region", Scalar::String("East".into()))]);
|
||||
// East's own year-to-date facts: 10 + 20. Dropping the Region filter would return 130.
|
||||
assert_number(eval_measure(&model, "YTD Fact", east.clone()), 30.0);
|
||||
assert_number(eval_measure(&model, "MTD Fact", east.clone()), 20.0);
|
||||
|
||||
// A filter on the fact date column itself is replaced by the window, not intersected with it:
|
||||
// anchoring on 2024-03-10 makes the year-to-date window run from 2024-01-01, so both East rows
|
||||
// count (30). Keeping and intersecting the filter would return only 2024-03-10's 20.
|
||||
let east_march = filters(&model, &[("Sales", "Region", Scalar::String("East".into())), ("Sales", "Date", date(2024, 3, 10))]);
|
||||
assert_number(eval_measure(&model, "YTD Fact", east_march), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_date_totals_match_cells_that_carry_a_time_of_day() {
|
||||
// DateTime cells may store a time of day, and a day may hold more than one timestamp; every
|
||||
// cell of the period still has to count, not just the first one found for its day.
|
||||
let model = fact_date_model(
|
||||
vec![
|
||||
measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
|
||||
measure("OB Month", "OPENINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
|
||||
measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"),
|
||||
],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(5), Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(7), Scalar::DateTime(serial(2024, 2, 29) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
// March's closing balance covers both 2024-03-31 timestamps, not the earlier February date.
|
||||
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
|
||||
// March's opening balance is the day before its start: 2024-02-29 09:30.
|
||||
assert_number(eval_measure(&model, "OB Month", FilterContext::default()), 7.0);
|
||||
// The year-to-date window keeps every cell: 5 + 7 + 3 + 10, including both March 31 rows.
|
||||
assert_number(eval_measure(&model, "YTD Fact", FilterContext::default()), 25.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_filters_intersect_the_boundary_day() {
|
||||
// The boundary day holds two timestamps; a filter argument that keeps only one of them has to
|
||||
// intersect with the boundary keys, exactly like `TOTAL*`, instead of being dropped.
|
||||
let mut model = fact_date_model(
|
||||
vec![measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])")],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
model.measures.push(measure("CB Month Filtered", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date], Sales[Date] > DATE(2024,3,31) + 10/24)"));
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
// Without a filter both same-day cells are the boundary.
|
||||
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
|
||||
// With a filter that keeps only the 14:00 cell the boundary is one cell: 10, not 13.
|
||||
assert_number(eval_measure(&model, "CB Month Filtered", FilterContext::default()), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_table_argument_uses_its_typed_date_column() {
|
||||
// `TOTALWTD(…, Calendar)` must resolve the calendar's date column exactly like `DATESWTD`:
|
||||
// the declared date type wins over an earlier untyped column.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Label".into(), data_type: None },
|
||||
ModelColumn { name: "Day".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::String("first".into()), date(2024, 1, 1)], vec![Scalar::String("second".into()), date(2024, 1, 2)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
|
||||
.into_iter()
|
||||
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
// 2024-01-02 is a Tuesday, so the week starts on Sunday 2023-12-31: both calendar days are in
|
||||
// the window and the sum is 30. Binding the untyped `Label` column would return BLANK.
|
||||
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_with_one_untyped_column_is_still_a_calendar() {
|
||||
// A calendar whose only date column is untyped keeps working: the unambiguous untyped column
|
||||
// is the fallback once no typed date column and no `Date` column exist.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![ModelColumn { name: "Day".into(), data_type: None }],
|
||||
rows: vec![vec![date(2024, 1, 1)], vec![date(2024, 1, 2)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
|
||||
.into_iter()
|
||||
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_date_column_declared_as_a_non_date_type_is_rejected() {
|
||||
// An integer `Date` column (YYYYMMDD keys) is not a date axis: report the model, do not read
|
||||
// its numbers as OLE serials.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(20_240_101)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }],
|
||||
rows: vec![vec![Scalar::Decimal(10.0)]],
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
let error = eval_measure(&model, "Week To Date", FilterContext::default()).expect_err("an Int64 Date column is not a date axis");
|
||||
assert!(error.contains("has no date column"), "{error}");
|
||||
}
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Chart",
|
||||
["Insert", "Charts"],
|
||||
None,
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|pareto|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
|
||||
has_doc,
|
||||
insert_chart
|
||||
),
|
||||
|
||||
@@ -59,6 +59,7 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
|
||||
("bubble", _) => ChartKind::Bubble,
|
||||
("radar", _) => ChartKind::Radar,
|
||||
("histogram", _) => ChartKind::Histogram,
|
||||
("pareto", _) => ChartKind::Pareto,
|
||||
("waterfall", _) => ChartKind::Waterfall,
|
||||
("funnel", _) => ChartKind::Funnel,
|
||||
("treemap", _) => ChartKind::Treemap,
|
||||
@@ -285,7 +286,11 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
|
||||
},
|
||||
title,
|
||||
series,
|
||||
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
|
||||
legend: match kind {
|
||||
ChartKind::Pie | ChartKind::Doughnut => LegendPos::Right,
|
||||
ChartKind::Pareto => LegendPos::None,
|
||||
_ => LegendPos::Bottom,
|
||||
},
|
||||
data_labels: false,
|
||||
data_table: None,
|
||||
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
|
||||
|
||||
@@ -4042,6 +4042,7 @@ fn every_chart_kind_survives_xlsx() {
|
||||
("combo", ChartKind::Combo),
|
||||
("stock", ChartKind::Stock),
|
||||
("histogram", ChartKind::Histogram),
|
||||
("pareto", ChartKind::Pareto),
|
||||
("boxWhisker", ChartKind::BoxWhisker),
|
||||
("waterfall", ChartKind::Waterfall),
|
||||
("funnel", ChartKind::Funnel),
|
||||
@@ -4073,6 +4074,16 @@ fn every_chart_kind_survives_xlsx() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_chart_has_no_legend() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Item", "Count"], ["A", 3], ["B", 2], ["C", 1]]})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "pareto", "range": "A1:B4"})).unwrap();
|
||||
let c = &s.doc().unwrap().wb.active().unwrap().charts[0];
|
||||
assert_eq!(c.kind, gridcraft_model::ChartKind::Pareto);
|
||||
assert_eq!(c.legend, gridcraft_model::LegendPos::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_set_doughnut_hole_and_angle() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -317,6 +317,327 @@ fn a_python_cell_without_its_code_keeps_its_whole_cached_result_as_values() {
|
||||
}
|
||||
}
|
||||
|
||||
fn long_warning(n: u64) -> String {
|
||||
format!("sheet \"Sheet1\": {n} cell text(s) longer than Excel's limit of 32767 UTF-16 units were read; they were not cut to that length")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_in_a_python_spill_is_kept_and_warned_about() {
|
||||
// A Python cell's spilled values are its result, kept and saved, so text in them longer than
|
||||
// Excel allows in a cell is kept whole with the warning a plain cell's gets; at the limit, no warning.
|
||||
let most = gridcraft_core::MAX_CELL_CHARS as usize;
|
||||
let book = |n: usize| {
|
||||
let data = format!(
|
||||
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A2\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c></row></sheetData>",
|
||||
"a".repeat(n)
|
||||
);
|
||||
crate::io::open_bytes("long.xlsx", &excel_shaped(&data, Some(&["[1, 'text']"]))).unwrap()
|
||||
};
|
||||
let long = |warnings: &[String]| warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>();
|
||||
let (wb, warnings) = book(most);
|
||||
assert!(long(&warnings).is_empty(), "{warnings:?}");
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most).into())));
|
||||
let (wb, warnings) = book(most + 1);
|
||||
assert_eq!(long(&warnings), [long_warning(1)], "{warnings:?}");
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most + 1).into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_address_in_a_python_spill_keeps_the_last_value_with_a_warning() {
|
||||
// A2 lies in A1's spill and has the default style, so its value is kept only as part of the
|
||||
// result, in the spill and not in a cell; a second A2, after B2, replaces it there, as on any
|
||||
// cell, and is counted as a repeat, found by the column bitmap of row 2's element (the next
|
||||
// test puts the second A2 in a later element, after another row's, where the spill finds it).
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c><c r=\"A2\"><v>9</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
|
||||
assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(5.0));
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w
|
||||
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(!warnings.iter().any(|w| w.contains("out of column order")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_address_in_a_python_spill_in_a_later_row_element_is_found_in_the_spill() {
|
||||
// As above, but the second A2 sits in a second row element for row 2, after row 3's: the
|
||||
// column bitmap has been cleared and A2 is not the furthest cell, so only the spill finds the
|
||||
// repeat.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c></row><row r=\"3\"><c r=\"C3\"><v>7</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>9</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w
|
||||
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
|
||||
"{warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_spilled_text_is_counted_when_read_even_where_a_repeat_replaces_it() {
|
||||
// A long A2 in A1's spill, then a second A2: the long text is counted as it is read, so a
|
||||
// plain value replacing it leaves the count at one, and a second long one makes it two.
|
||||
let long = format!("<c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c>", "a".repeat(gridcraft_core::MAX_CELL_CHARS as usize + 1));
|
||||
let count = |second: &str| {
|
||||
let data = format!(
|
||||
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\">{long}{second}</row></sheetData>"
|
||||
);
|
||||
let (_, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(&data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("already read")), "{warnings:?}");
|
||||
warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(count("<c r=\"A2\"><v>9</v></c>"), [long_warning(1)]);
|
||||
assert_eq!(count(&long), [long_warning(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_code_dropped_at_the_element_cap_leaves_its_cells_with_their_values() {
|
||||
// The first script's code holds a million elements. With the `environmentDefinition` before
|
||||
// the scripts in the tree, the last of them crosses the reader's element cap for a part, and
|
||||
// the code element is dropped with the 999,999 it held: 1,000,001 elements. A script whose
|
||||
// code was dropped is treated as missing, so A1, naming it, keeps its cached value and no
|
||||
// Python code, through a save too. The second script is read whole, and the third, an empty
|
||||
// `code` in the file, is empty code, as before.
|
||||
let crowded = format!("x = 1{}", "<pad/>".repeat(1_000_000));
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c>\
|
||||
<c r=\"C1\"><f>_xlfn._xlws.PY(2,0)</f><v>3</v></c></row></sheetData>";
|
||||
let bytes = excel_shaped(data, Some(&[&crowded, "y = 2", ""]));
|
||||
let (_, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.starts_with("the Python part: dropped 1000001 element(s)")
|
||||
&& w.ends_with("a script that lost its code and kept no code after it counts as missing")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(warnings.iter().any(|w| w.starts_with("1 Python cell(s) name code the file's Python part doesn't hold")), "{warnings:?}");
|
||||
let mut s = s();
|
||||
open(&mut s, "crowded.xlsx", &bytes);
|
||||
let check = |s: &Session, when: &str| {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
let a1 = sh.cell(CellRef::parse("A1").unwrap()).unwrap_or_else(|| panic!("{when}: A1 is stored"));
|
||||
assert_eq!(a1.value, Value::Number(1.0), "{when}");
|
||||
assert!(a1.py.is_none() && a1.formula.is_none(), "{when}: A1 is a plain value");
|
||||
assert_eq!(code(s, "B1").map(|p| p.code), Some("y = 2".to_string()), "{when}");
|
||||
assert_eq!(code(s, "C1").map(|p| p.code), Some(String::new()), "{when}");
|
||||
};
|
||||
check(&s, "after open");
|
||||
let saved = save(&mut s, "xlsx");
|
||||
open(&mut s, "saved.xlsx", &saved);
|
||||
check(&s, "after a save");
|
||||
}
|
||||
|
||||
/// A1 naming the one script, `script` (a whole `pythonScript` element), read: A1's Python code, if
|
||||
/// any, and the warnings.
|
||||
fn a1_code_with_script(script: &str) -> (Option<String>, Vec<String>) {
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["MARKER"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| {
|
||||
if name == "xl/python/python1.xml" { text.replace("<pythonScript><code>MARKER</code></pythonScript>", script) } else { text.to_string() }
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("script.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).cloned();
|
||||
(a1.and_then(|c| c.py.map(|p| p.code.clone())), warnings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_without_code_reads_as_empty_code_also_when_an_unknown_element_crosses_the_cap() {
|
||||
// A script with no code reads as empty code. An unknown element in it that crosses the
|
||||
// element cap is dropped and counted, but holds nothing the reader reads: the script still
|
||||
// reads as empty code, not as missing.
|
||||
for (script, dropped) in [
|
||||
("<pythonScript><other/></pythonScript>".to_string(), false),
|
||||
(format!("<pythonScript><other>{}</other></pythonScript>", "<pad/>".repeat(1_000_001)), true),
|
||||
] {
|
||||
let (code, warnings) = a1_code_with_script(&script);
|
||||
assert_eq!(code.as_deref(), Some(""), "{warnings:?}");
|
||||
assert_eq!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), dropped, "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_whose_first_code_is_dropped_at_the_element_cap_takes_its_second_code() {
|
||||
// The first code crosses the element cap and is dropped whole: it took no place in the
|
||||
// script's allowance of one code, so the second code is read, and A1 takes it.
|
||||
let (code, warnings) =
|
||||
a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code>y = 2</code></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_whose_code_is_dropped_at_the_element_cap_before_an_empty_code_counts_as_missing() {
|
||||
// The first code crosses the element cap and is dropped whole, and the code after it is empty:
|
||||
// the script lost its code and kept none, so A1 keeps only its value, as when no code follows.
|
||||
let (code, warnings) = a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code/></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code, None, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_that_keeps_its_code_and_loses_a_second_one_past_the_element_cap_keeps_its_code() {
|
||||
// The second code crosses the element cap; it is one more than a script holds, so it is
|
||||
// dropped for that, and the script, which lost no code it reads, keeps its first code, empty
|
||||
// or not.
|
||||
for kept in ["y = 2", ""] {
|
||||
let (code, warnings) =
|
||||
a1_code_with_script(&format!("<pythonScript><code>{kept}</code><code>x = 1{}</code></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code.as_deref(), Some(kept), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_that_loses_an_unknown_element_at_the_element_cap_keeps_its_code() {
|
||||
// The script's code comes first; an unknown element after it crosses the element cap and is
|
||||
// dropped whole. The code was kept, so A1 keeps it.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let crowded = format!("</code><extra>{}</extra></pythonScript>", "<pad/>".repeat(1_000_001));
|
||||
let good = excel_shaped(data, Some(&["y = 2"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</code></pythonScript>", &crowded) } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("y = 2"), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_script_with_the_element_cap_full_is_read_and_the_part_fails_when_its_scripts_close() {
|
||||
// The `environmentDefinition` and the filler before `pythonScripts` fill the part's element
|
||||
// cap of a million. An empty script holds no element, so it is handed out as on main and
|
||||
// reads as empty code; `pythonScripts` itself is then one element past the cap, so the part
|
||||
// fails as it closes, and the warning counts the empty script among those kept. A1, naming
|
||||
// it, keeps the empty code. With one element less of filler the part is whole.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["MARKER"]));
|
||||
for (filler, script, damaged) in
|
||||
[(999_999, "<pythonScript/>", true), (999_999, "<pythonScript></pythonScript>", true), (999_998, "<pythonScript/>", false)]
|
||||
{
|
||||
let scripts = format!("{}<pythonScripts>{script}</pythonScripts>", "<pad/>".repeat(filler));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| {
|
||||
if name == "xl/python/python1.xml" {
|
||||
text.replace("<pythonScripts><pythonScript><code>MARKER</code></pythonScript></pythonScripts>", &scripts)
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("full.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some(""), "{script} after {filler}: {warnings:?}");
|
||||
let failed: Vec<&String> = warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).collect();
|
||||
let expected = "the Python part is damaged (the file contains invalid XML: the part holds more than 1000000 elements); kept 1 scripts";
|
||||
assert_eq!(failed, if damaged { vec![expected] } else { vec![] }, "{script} after {filler}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold") || w.starts_with("the Python part: dropped")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_python_part_still_reports_what_it_dropped_before_the_damage() {
|
||||
// The script's second code is dropped, then the part ends in an unclosed comment: both the
|
||||
// damage and the dropped element are warned about.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["x = 1</code><code>y = 2"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (_, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
|
||||
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_code_in_a_python_script_is_dropped_with_a_warning() {
|
||||
// A script holds one code: the first is read, the second dropped and counted.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("twice.xlsx", &excel_shaped(data, Some(&["x = 1</code><code>y = 2"]))).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"));
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
|
||||
}
|
||||
|
||||
fn unknown_warning(n: u64) -> String {
|
||||
format!("the Python part: {n} element(s) GridCraft does not read (unknown elements) were left out and will not be saved")
|
||||
}
|
||||
|
||||
fn unknown_warnings(warnings: &[String]) -> Vec<String> {
|
||||
warnings.iter().filter(|w| w.contains("does not read")).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_with_an_unknown_child_keeps_its_code_and_warns_that_it_will_not_be_saved() {
|
||||
// The unknown child is small, so nothing reaches an allowance or the element cap and nothing
|
||||
// is dropped: the code is read, and the child, which a save does not write, is warned about.
|
||||
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code><extra>note</extra></pythonScript>");
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_children_across_two_scripts_are_counted_in_one_warning() {
|
||||
// Two unknown children in the first script and one in the second: one warning, counting three.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c></row></sheetData>";
|
||||
let scripts = ["x = 1</code><extra/><other>text</other><code>unread", "y = 2</code><extra/><code>unread"];
|
||||
let (wb, warnings) = crate::io::open_bytes("unknown.xlsx", &excel_shaped(data, Some(&scripts))).unwrap();
|
||||
let sheet = wb.sheet(0).unwrap();
|
||||
let code = |cell: &str| sheet.cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_ref().map(|p| p.code.clone()));
|
||||
assert_eq!(code("A1").as_deref(), Some("x = 1"), "{warnings:?}");
|
||||
assert_eq!(code("B1").as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(3)], "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_without_unknown_children_gives_no_unknown_element_warning() {
|
||||
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code></pythonScript>");
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert!(unknown_warnings(&warnings).is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_python_part_still_reports_unknown_children_read_before_the_damage() {
|
||||
// The script, with one unknown child, closes before the part ends in an unclosed comment: both
|
||||
// the damage and the unknown child are warned about, and the script's code is kept.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["x = 1</code><extra/><code>unread"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
|
||||
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_python_spill_whose_blank_cells_have_no_records_is_still_a_spill() {
|
||||
// A1's result spills over A1:A3, and the file holds no records for the blank A2 and A3.
|
||||
|
||||
@@ -23,6 +23,19 @@ fn needle(args: &[Arg], i: usize) -> R<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup value of XLOOKUP and XMATCH. Unlike the older lookups, a reference to a blank cell is
|
||||
/// blank rather than numeric zero: it matches a blank entry and nothing else (#4044). A written
|
||||
/// blank argument (`XMATCH(, array)`) still becomes zero, as MATCH does.
|
||||
fn xneedle(args: &[Arg], i: usize) -> R<Value> {
|
||||
let a = arg(args, i)?;
|
||||
match a.value.scalar() {
|
||||
Value::Error(e) => Err(e),
|
||||
Value::Empty if a.from_ref || a.blank_value => Ok(Value::Empty),
|
||||
Value::Empty => Ok(Value::Number(0.0)),
|
||||
v => Ok(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// Order of two values for the approximate and binary searches: [`compare`], except that numbers
|
||||
/// compare exactly. Excel's `=` treats numbers equal to 15 significant digits as equal, but its
|
||||
/// lookups don't. Observed in Excel 365 with A1 holding
|
||||
@@ -233,6 +246,12 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
if search_mode.abs() == 2 {
|
||||
let desc = search_mode == -2;
|
||||
// A blank needle only matches a blank entry. The coercing comparison would read it as
|
||||
// numeric zero, so the exact result stands even when it finds nothing: the approximate
|
||||
// probes must not fall through to a zero (#4044).
|
||||
if matches!(x, Value::Empty) {
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
}
|
||||
if match_mode == 2 {
|
||||
// Wildcards are not supported with binary search: Excel falls back to exact.
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
@@ -292,13 +311,20 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
|
||||
fn bsearch_exact(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
|
||||
if matches!(x, Value::Empty) {
|
||||
// A blank needle only matches a blank entry. The coercing comparison below would read it
|
||||
// as numeric zero, so handle it here: blanks sort last in both directions, so the first
|
||||
// blank entry is the only possible exact match.
|
||||
let p = hay.partition_point(|v| !matches!(v, Value::Empty));
|
||||
return matches!(hay.get(p)?, Value::Empty).then_some(p);
|
||||
}
|
||||
let p = bsearch_first(x, hay, desc)?;
|
||||
let v = hay.get(p)?;
|
||||
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
|
||||
}
|
||||
|
||||
fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -344,7 +370,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
}
|
||||
|
||||
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -567,6 +593,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
mod tests {
|
||||
use gridcraft_core::{CellError, Value};
|
||||
|
||||
use crate::Arg;
|
||||
use crate::util::testutil::*;
|
||||
|
||||
fn table() -> Value {
|
||||
@@ -759,6 +786,49 @@ mod tests {
|
||||
assert_eq!(rows_of(&r), vec![vec![nv(3.0), nv(1.0)]]);
|
||||
}
|
||||
|
||||
/// A reference to a blank cell is a blank lookup value, not numeric zero, for XMATCH and
|
||||
/// XLOOKUP: it finds a blank entry and misses numbers. MATCH keeps Excel's zero coercion (#4044).
|
||||
#[test]
|
||||
fn xmatch_and_xlookup_treat_a_blank_reference_as_blank() {
|
||||
let numbers = || av(row(&[0.0, 1.0, 3.0]));
|
||||
let blank = || Arg::reference(Value::Empty);
|
||||
is_err(ev("XMATCH", vec![blank(), numbers()]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), rf(arr(vec![vec![Value::Empty], vec![nv(2.0)]]))]), 1.0);
|
||||
let keys = || rf(col(&[0.0, 1.0, 3.0]));
|
||||
let values = || av(col(&[10.0, 20.0, 30.0]));
|
||||
close(ev("XLOOKUP", vec![blank(), keys(), values(), n(999.0), n(0.0)]), 999.0);
|
||||
// Binary exact search (search mode 2 ascending, -2 descending) does not coerce the blank
|
||||
// needle to zero either: {0} has no blank entry, {0;blank} has one last.
|
||||
let zero = || rf(col(&[0.0]));
|
||||
let zero_then_blank = || rf(arr(vec![vec![nv(0.0)], vec![Value::Empty]]));
|
||||
let just_blank = || rf(arr(vec![vec![Value::Empty]]));
|
||||
for mode in [2.0, -2.0] {
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(0.0), n(mode)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(0.0), n(mode)]), 2.0);
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(0.0), n(mode)]), 1.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 999.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 10.0);
|
||||
// The approximate binary modes (-1 next smaller, 1 next larger) still take a present
|
||||
// exact blank before their fallback, in both search directions.
|
||||
for mm in [-1.0, 1.0] {
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(mm), n(mode)]), 1.0);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(mm), n(mode)]), 2.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 10.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero_then_blank(), av(col(&[10.0, 20.0])), n(999.0), n(mm), n(mode)]), 20.0);
|
||||
// Without a blank entry the approximate probes must not read the blank as zero.
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(mm), n(mode)]), CellError::NA);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 999.0);
|
||||
}
|
||||
}
|
||||
// Controls: numeric zero is still a key, and a written blank stays zero.
|
||||
close(ev("XMATCH", vec![n(0.0), numbers()]), 1.0);
|
||||
close(ev("XLOOKUP", vec![n(0.0), keys(), values(), n(999.0), n(0.0)]), 10.0);
|
||||
is_err(ev("XMATCH", vec![n(0.0), just_blank(), n(0.0), n(2.0)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![empty(), zero(), n(0.0), n(2.0)]), 1.0);
|
||||
close(ev("MATCH", vec![blank(), numbers(), n(0.0)]), 1.0);
|
||||
close(ev("XMATCH", vec![empty(), numbers()]), 1.0);
|
||||
}
|
||||
|
||||
/// Lookups compare numbers exactly, unlike `=` (15 significant digits). Observed in Excel 365.
|
||||
#[test]
|
||||
fn lookups_compare_numbers_exactly() {
|
||||
|
||||
@@ -23,8 +23,8 @@ use descriptive::{
|
||||
use distributions::{
|
||||
beta_dist, beta_inv, betadist_legacy, binom_dist, binom_dist_range, binom_inv, chisq_dist, chisq_dist_rt, chisq_inv, chisq_inv_rt, chisq_test,
|
||||
confidence_norm, confidence_t, expon_dist, f_dist, f_dist_rt, f_inv, f_inv_rt, f_test, fisher, gamma_dist, gamma_fn, gamma_inv, gammaln, gauss,
|
||||
hypgeom_dist, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist, t_dist, t_dist_2t,
|
||||
t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
|
||||
hypgeom_dist, hypgeomdist_legacy, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist,
|
||||
t_dist, t_dist_2t, t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use regression::{MAX_REGRESSORS, check_regression_size};
|
||||
@@ -649,7 +649,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
S,
|
||||
"HYPGEOMDIST(sample_s, number_sample, population_s, number_pop)",
|
||||
"Hypergeometric probability of an exact count.",
|
||||
hypgeom_dist
|
||||
hypgeomdist_legacy
|
||||
),
|
||||
f!(
|
||||
"NEGBINOM.DIST",
|
||||
|
||||
@@ -804,15 +804,27 @@ pub(super) fn weibull_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
num_val(if cum { -(-t).exp_m1() } else { al / be.powf(al) * x.powf(al - 1.0) * (-t).exp() })
|
||||
}
|
||||
|
||||
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
fn hypgeom_common(a: &[Arg], strict: bool) -> R<Value> {
|
||||
let k = num(a, 0)?.trunc();
|
||||
let n = num(a, 1)?.trunc();
|
||||
let kk = num(a, 2)?.trunc();
|
||||
let nn = num(a, 3)?.trunc();
|
||||
let cum = if a.len() > 4 { boolean(a, 4)? } else { false };
|
||||
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn || k > n.min(kk) || k < (n - nn + kk).max(0.0) {
|
||||
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let lo = (n - nn + kk).max(0.0);
|
||||
let hi = n.min(kk);
|
||||
if k < lo || k > hi {
|
||||
// Above the support the mass is zero and the cumulative form is 1, as
|
||||
// Excel returns (#4032). Below the support Excel returns #NUM!, so both
|
||||
// forms stay strict there. The legacy compatibility form is strict on
|
||||
// both sides.
|
||||
if strict || k < lo {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
return num_val(if cum { 1.0 } else { 0.0 });
|
||||
}
|
||||
let pmf = |i: f64| (ln_comb(kk, i) + ln_comb(nn - kk, n - i) - ln_comb(nn, n)).exp();
|
||||
if !cum {
|
||||
return num_val(pmf(k));
|
||||
@@ -829,6 +841,14 @@ pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
num_val(s.min(1.0))
|
||||
}
|
||||
|
||||
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
hypgeom_common(a, false)
|
||||
}
|
||||
|
||||
pub(super) fn hypgeomdist_legacy(a: &[Arg], _: C) -> R<Value> {
|
||||
hypgeom_common(a, true)
|
||||
}
|
||||
|
||||
pub(super) fn negbinom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
let f = num(a, 0)?.trunc();
|
||||
let s = num(a, 1)?.trunc();
|
||||
|
||||
@@ -821,6 +821,25 @@ fn discrete() {
|
||||
close_tol(ev("NEGBINOMDIST", vec![n(10.0), n(5.0), n(0.25)]), 0.0550487, D7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hypgeom_dist_out_of_support_clamps() {
|
||||
// Support is [max(0, n - nn + kk), min(n, kk)].
|
||||
// Above support: k=2, n=1, kk=1, nn=3 -> high = min(1, 1) = 1, so 2 is above.
|
||||
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(false)]), Value::Number(0.0));
|
||||
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(true)]), Value::Number(1.0));
|
||||
// Controls inside the support (low = max(0, 1 - 3 + 1) = 0, high = 1).
|
||||
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(false)]), 1.0 / 3.0);
|
||||
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(true)]), 1.0);
|
||||
// Below support stays #NUM!, as Excel documents: k=0, n=4, kk=8, nn=10
|
||||
// -> low = max(0, 4 - 10 + 8) = 2, so 0 is below.
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(false)]), CellError::Num);
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(true)]), CellError::Num);
|
||||
// Legacy compatibility form stays strict outside the support.
|
||||
is_err(ev("HYPGEOMDIST", vec![n(5.0), n(4.0), n(8.0), n(20.0)]), CellError::Num);
|
||||
// Invalid population arguments stay #NUM! (number_sample > number_pop here).
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(1.0), n(5.0), n(2.0), n(3.0), b(false)]), CellError::Num);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous() {
|
||||
close_tol(ev("EXPON.DIST", vec![n(0.2), n(10.0), b(true)]), 0.86466472, D7);
|
||||
|
||||
@@ -513,6 +513,7 @@ pub enum ChartKind {
|
||||
Bubble,
|
||||
Radar,
|
||||
Histogram,
|
||||
Pareto,
|
||||
Waterfall,
|
||||
Funnel,
|
||||
Treemap,
|
||||
|
||||
@@ -298,6 +298,8 @@ impl SheetApp {
|
||||
match i18n::Language::parse(code) {
|
||||
Some(l) => {
|
||||
self.ui.language = l;
|
||||
// Chart text is translated: cached primitives hold the old language.
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": l}))
|
||||
}
|
||||
None => Err(format!("unknown language {code:?} (use one of {})", i18n::Language::code_list(", "))),
|
||||
@@ -305,10 +307,12 @@ impl SheetApp {
|
||||
}
|
||||
"app.language.english" => {
|
||||
self.ui.language = i18n::Language::En;
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": i18n::Language::En}))
|
||||
}
|
||||
"app.language.japanese" => {
|
||||
self.ui.language = i18n::Language::Ja;
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": i18n::Language::Ja}))
|
||||
}
|
||||
"ui.quickAnalysis" => crate::quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)),
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
|
||||
use egui::epaint::{PathShape, PathStroke};
|
||||
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
|
||||
use gridcraft_chart::{HAlign, Prim, VAlign};
|
||||
use gridcraft_chart::{ChartLabels, HAlign, Prim, VAlign};
|
||||
use gridcraft_engine::model::{Anchor, ObjKind, ObjRef, ShapeKind, Sheet, Workbook};
|
||||
|
||||
use crate::SheetApp;
|
||||
@@ -39,7 +39,8 @@ pub fn paint_chart(p: &Painter, rect: Rect, wb: &Workbook, sheet: usize, chart:
|
||||
let origin = rect.center() - vec2(w * z, h * z) / 2.0;
|
||||
let data = gridcraft_chart::resolve(wb, sheet, chart);
|
||||
let m = EguiMeasure { painter: p, z };
|
||||
let prims = gridcraft_chart::render(chart, &data, w, h, &m);
|
||||
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
|
||||
let prims = gridcraft_chart::render_with_labels(chart, &data, w, h, &m, &labels);
|
||||
paint_prims(&p.with_clip_rect(rect.intersect(p.clip_rect())), origin, &prims, z);
|
||||
}
|
||||
|
||||
@@ -254,7 +255,8 @@ fn render_chart(p: &Painter, z: f32, wb: &Workbook, si: usize, ch: &gridcraft_en
|
||||
tests::RENDERS.with(|c| c.set(c.get() + 1));
|
||||
let data = gridcraft_chart::resolve(wb, si, ch);
|
||||
let m = EguiMeasure { painter: p, z };
|
||||
gridcraft_chart::render(ch, &data, ch.anchor.width, ch.anchor.height, &m)
|
||||
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
|
||||
gridcraft_chart::render_with_labels(ch, &data, ch.anchor.width, ch.anchor.height, &m, &labels)
|
||||
}
|
||||
|
||||
/// The primitives of chart `ci` of sheet `si`: from the frame cache when the workbook, zoom and
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::show::ok_cancel;
|
||||
use super::{Color32, Dialog, Icon, Json, Sense, SheetApp, Stroke, StrokeKind, icons, json, vec2};
|
||||
|
||||
/// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`.
|
||||
const ALL_CHARTS: [(&str, &str, &str); 23] = [
|
||||
const ALL_CHARTS: [(&str, &str, &str); 24] = [
|
||||
("column", "", "Clustered Column"),
|
||||
("column", "stacked", "Stacked Column"),
|
||||
("column", "stacked100", "100% Stacked Column"),
|
||||
@@ -23,6 +23,7 @@ const ALL_CHARTS: [(&str, &str, &str); 23] = [
|
||||
("scatter", "lines", "Scatter with Lines"),
|
||||
("radar", "", "Radar"),
|
||||
("histogram", "", "Histogram"),
|
||||
("pareto", "", "Pareto"),
|
||||
("waterfall", "", "Waterfall"),
|
||||
("funnel", "", "Funnel"),
|
||||
("combo", "", "Combo"),
|
||||
@@ -51,7 +52,7 @@ pub(super) fn select_chart(d: &mut Dialog, i: usize) {
|
||||
|
||||
fn chart_icon(t: &str) -> Icon {
|
||||
match t {
|
||||
"column" | "bar" | "histogram" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
|
||||
"column" | "bar" | "histogram" | "pareto" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
|
||||
"line" | "area" | "radar" => Icon::ChartLine,
|
||||
"pie" | "doughnut" => Icon::ChartPie,
|
||||
"scatter" | "bubble" => Icon::ChartScatter,
|
||||
|
||||
@@ -430,6 +430,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatizace",
|
||||
"Table Design" => "Návrh tabulky",
|
||||
"Chart Design" => "Návrh grafu",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Kumulativní %",
|
||||
"Ready" => "Připraveno",
|
||||
"Enter" => "Zadat",
|
||||
"Edit" => "Úpravy",
|
||||
|
||||
@@ -447,6 +447,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatisieren",
|
||||
"Table Design" => "Tabellenentwurf",
|
||||
"Chart Design" => "Diagrammentwurf",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Kumuliert %",
|
||||
"Ready" => "Bereit",
|
||||
"Enter" => "Eingeben",
|
||||
"Edit" => "Bearbeiten",
|
||||
|
||||
@@ -393,6 +393,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Αυτοματισμός",
|
||||
"Table Design" => "Σχεδίαση πίνακα",
|
||||
"Chart Design" => "Σχεδίαση γραφήματος",
|
||||
"Pareto" => "Παρέτο",
|
||||
"Cumulative %" => "Αθροιστικό %",
|
||||
"Ready" => "Έτοιμο",
|
||||
"Enter" => "Εισαγωγή",
|
||||
"Edit" => "Επεξεργασία",
|
||||
|
||||
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatizar",
|
||||
"Table Design" => "Diseño de tabla",
|
||||
"Chart Design" => "Diseño de gráfico",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% acumulado",
|
||||
"Ready" => "Listo",
|
||||
"Enter" => "Introducir",
|
||||
"Edit" => "Modificar",
|
||||
|
||||
@@ -308,6 +308,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatiser",
|
||||
"Table Design" => "Création de tableau",
|
||||
"Chart Design" => "Création de graphique",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% cumulé",
|
||||
"Ready" => "Prêt",
|
||||
"Enter" => "Entrée",
|
||||
"Edit" => "Modifier",
|
||||
|
||||
@@ -292,6 +292,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatizza",
|
||||
"Table Design" => "Progettazione tabella",
|
||||
"Chart Design" => "Progettazione grafico",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% cumulativo",
|
||||
"Ready" => "Pronto",
|
||||
"Enter" => "Immetti",
|
||||
"Edit" => "Modifica",
|
||||
|
||||
@@ -299,6 +299,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
("Automate", "自動化"),
|
||||
("Table Design", "テーブル デザイン"),
|
||||
("Chart Design", "グラフ デザイン"),
|
||||
("Pareto", "パレート図"),
|
||||
("Cumulative %", "累積 %"),
|
||||
("Ready", "準備完了"),
|
||||
("Enter", "入力"),
|
||||
("Edit", "編集"),
|
||||
|
||||
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "자동화",
|
||||
"Table Design" => "표 디자인",
|
||||
"Chart Design" => "차트 디자인",
|
||||
"Pareto" => "파레토",
|
||||
"Cumulative %" => "누적 %",
|
||||
"Ready" => "준비",
|
||||
"Enter" => "입력",
|
||||
"Edit" => "편집",
|
||||
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatiseren",
|
||||
"Table Design" => "Tabelontwerp",
|
||||
"Chart Design" => "Grafiekontwerp",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Cumulatief %",
|
||||
"Ready" => "Gereed",
|
||||
"Enter" => "Invoeren",
|
||||
"Edit" => "Bewerken",
|
||||
|
||||
@@ -286,6 +286,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatyzacja",
|
||||
"Table Design" => "Projekt tabeli",
|
||||
"Chart Design" => "Projekt wykresu",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Skumulowany %",
|
||||
"Ready" => "Gotowy",
|
||||
"Enter" => "Wprowadź",
|
||||
"Edit" => "Edytuj",
|
||||
|
||||
@@ -851,6 +851,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Scatter with Lines" => "Dispersão com Linhas",
|
||||
"Radar" => "Radar",
|
||||
"Histogram" => "Histograma",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% Acumulado",
|
||||
"Waterfall" => "Cascata",
|
||||
"Funnel" => "Funil",
|
||||
"Combo" => "Combinação",
|
||||
|
||||
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatizare",
|
||||
"Table Design" => "Design tabel",
|
||||
"Chart Design" => "Proiectare diagramă",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% cumulat",
|
||||
"Ready" => "Gata",
|
||||
"Enter" => "Enter",
|
||||
"Edit" => "Editare",
|
||||
|
||||
@@ -295,6 +295,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Автоматизация",
|
||||
"Table Design" => "Конструктор таблиц",
|
||||
"Chart Design" => "Конструктор диаграмм",
|
||||
"Pareto" => "Парето",
|
||||
"Cumulative %" => "Накопленный %",
|
||||
"Ready" => "Готово",
|
||||
"Enter" => "Ввод",
|
||||
"Edit" => "Изменение",
|
||||
|
||||
@@ -298,6 +298,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Automatizacija",
|
||||
"Table Design" => "Dizajn tabele",
|
||||
"Chart Design" => "Dizajn grafikona",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Kumulativno %",
|
||||
"Ready" => "Spremno",
|
||||
"Enter" => "Unos",
|
||||
"Edit" => "Uređivanje",
|
||||
|
||||
@@ -407,6 +407,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Otomatikleştir",
|
||||
"Table Design" => "Tablo Tasarımı",
|
||||
"Chart Design" => "Grafik Tasarımı",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "Kümülatif %",
|
||||
"Ready" => "Hazır",
|
||||
"Enter" => "Giriş",
|
||||
"Edit" => "Düzenle",
|
||||
|
||||
@@ -288,6 +288,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Автоматизація",
|
||||
"Table Design" => "Конструктор таблиць",
|
||||
"Chart Design" => "Конструктор діаграм",
|
||||
"Pareto" => "Парето",
|
||||
"Cumulative %" => "Накопичений %",
|
||||
"Ready" => "Готово",
|
||||
"Enter" => "Ввід",
|
||||
"Edit" => "Редагування",
|
||||
|
||||
@@ -301,6 +301,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "Tự động hóa",
|
||||
"Table Design" => "Thiết kế bảng",
|
||||
"Chart Design" => "Thiết kế biểu đồ",
|
||||
"Pareto" => "Pareto",
|
||||
"Cumulative %" => "% tích lũy",
|
||||
"Ready" => "Sẵn sàng",
|
||||
"Enter" => "Nhập",
|
||||
"Edit" => "Sửa",
|
||||
|
||||
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Automate" => "自动化",
|
||||
"Table Design" => "表格设计",
|
||||
"Chart Design" => "图表设计",
|
||||
"Pareto" => "排列图",
|
||||
"Cumulative %" => "累积百分比",
|
||||
"Ready" => "就绪",
|
||||
"Enter" => "输入",
|
||||
"Edit" => "编辑",
|
||||
|
||||
@@ -205,6 +205,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
|
||||
("Doughnut", "doughnut", ""),
|
||||
("Scatter", "scatter", ""),
|
||||
("Radar", "radar", ""),
|
||||
("Pareto", "pareto", ""),
|
||||
] {
|
||||
let cur = chart.kind == gridcraft_engine::cmd::insert::chart_kind(k, s);
|
||||
if ui.selectable_label(cur, l).clicked() {
|
||||
|
||||
@@ -160,6 +160,7 @@ pub(super) fn chart_design(app: &mut SheetApp, ui: &mut Ui) {
|
||||
("Doughnut", "doughnut", ""),
|
||||
("Scatter", "scatter", ""),
|
||||
("Radar", "radar", ""),
|
||||
("Pareto", "pareto", ""),
|
||||
("Waterfall", "waterfall", ""),
|
||||
("Funnel", "funnel", ""),
|
||||
("Treemap", "treemap", ""),
|
||||
|
||||
@@ -118,11 +118,15 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
("Number Format", &["Comma", "Comma [0]", "Currency", "Currency [0]", "Percent"]),
|
||||
];
|
||||
for (g, names) in groups {
|
||||
ui.label(egui::RichText::new(*g).strong());
|
||||
ui.label(egui::RichText::new(app.ui.language.tr(g)).strong());
|
||||
egui::Grid::new(("csg", *g)).spacing(vec2(4.0, 4.0)).show(ui, |ui| {
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
// The built-in style keeps its English name: it is stored in the workbook and sent
|
||||
// by `home.cellStyle`, so only the painted label is translated.
|
||||
let label = app.ui.language.tr(n);
|
||||
let st = gridcraft_engine::cmd::format::builtin_cell_style(n, &wb.theme).unwrap_or_default();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(82.0, 24.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
|
||||
let fill = st
|
||||
.fill
|
||||
.fg
|
||||
@@ -144,7 +148,7 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(4.0, 0.0),
|
||||
Align2::LEFT_CENTER,
|
||||
*n,
|
||||
label,
|
||||
egui::FontId::new((st.font.size).clamp(10.0, 15.0), fam),
|
||||
col,
|
||||
);
|
||||
@@ -162,3 +166,71 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::cell_style_gallery;
|
||||
use crate::SheetApp;
|
||||
use crate::i18n::Language;
|
||||
use egui_kittest::kittest::{NodeT as _, Queryable};
|
||||
use serde_json::json;
|
||||
|
||||
/// Every text a frame painted, at any depth.
|
||||
fn painted_text(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_owned()),
|
||||
egui::Shape::Vec(shapes) => {
|
||||
for s in shapes {
|
||||
painted_text(s, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The gallery paints its group headings and style names through the interface language, while
|
||||
/// the English built-in names stay what `home.cellStyle` receives.
|
||||
#[test]
|
||||
fn gallery_labels_are_translated() {
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
app.run("app.language.set", serde_json::json!({"language": "ja"})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| cell_style_gallery(&mut app, ui));
|
||||
output.textures_delta.clear();
|
||||
let mut texts = Vec::new();
|
||||
for clipped in &output.shapes {
|
||||
painted_text(&clipped.shape, &mut texts);
|
||||
}
|
||||
for english in ["Good, Bad and Neutral", "Heading 1"] {
|
||||
let translated = Language::Ja.tr(english);
|
||||
assert_ne!(translated, english, "the Japanese catalog translates {english:?}");
|
||||
assert!(texts.iter().any(|t| t == translated), "the gallery paints {translated:?}; painted: {texts:?}");
|
||||
assert!(!texts.iter().any(|t| t == english), "the gallery no longer paints {english:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each swatch is a button named with its translated label, and activating it applies the
|
||||
/// English built-in style (`home.cellStyle`'s key), not the painted translation (#4249).
|
||||
#[test]
|
||||
fn gallery_swatches_are_named_buttons_and_activate_their_builtin_style() {
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
app.run("app.language.set", json!({"language": "ja"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(600.0, 800.0))
|
||||
.allow_missing_glyphs()
|
||||
.build_ui_state(|ui, app: &mut SheetApp| cell_style_gallery(app, ui), app);
|
||||
h.run_steps(2);
|
||||
let label = Language::Ja.tr("Heading 1");
|
||||
let swatch = h.get_by_label(label);
|
||||
assert_eq!(swatch.accesskit_node().role(), egui::accesskit::Role::Button, "the swatch is a button");
|
||||
swatch.click();
|
||||
h.run_steps(2);
|
||||
let cell = h.state_mut().session.execute("cell.get", json!({"cell": "A1"})).unwrap();
|
||||
assert_eq!(cell["style"]["font"]["size"], json!(15.0), "Heading 1's size");
|
||||
assert_eq!(cell["style"]["font"]["bold"], json!(true), "Heading 1's weight");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +125,12 @@ pub(super) fn insert(app: &mut SheetApp, ui: &mut Ui) {
|
||||
"insert.chart.scatter",
|
||||
vec![("Scatter", "scatter", ""), ("Scatter with Lines", "scatter", "lines"), ("Bubble", "bubble", "")],
|
||||
),
|
||||
(Icon::Chart, "Statistic", "insert.chart.statistic", vec![("Histogram", "histogram", ""), ("Box & Whisker", "boxWhisker", "")]),
|
||||
(
|
||||
Icon::Chart,
|
||||
"Statistic",
|
||||
"insert.chart.statistic",
|
||||
vec![("Histogram", "histogram", ""), ("Pareto", "pareto", ""), ("Box & Whisker", "boxWhisker", "")],
|
||||
),
|
||||
(
|
||||
Icon::Theme,
|
||||
"Hierarchy & more",
|
||||
|
||||
+79
-25
@@ -2,7 +2,7 @@
|
||||
//! which files keep as `cx:chartSpace` "chartex" parts (`xl/charts/chartExN.xml`) rather than
|
||||
//! DrawingML chart parts.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::{collections::HashMap, fmt::Write as _};
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_formula::{Expr, SheetSel};
|
||||
@@ -23,6 +23,7 @@ pub fn is_chartex(k: ChartKind) -> bool {
|
||||
use craft_drawingml::chart::ChartType;
|
||||
match k {
|
||||
ChartKind::Histogram => ChartType::Histogram.is_chartex(),
|
||||
ChartKind::Pareto => ChartType::Pareto.is_chartex(),
|
||||
ChartKind::BoxWhisker => ChartType::BoxWhisker.is_chartex(),
|
||||
ChartKind::Waterfall => ChartType::Waterfall.is_chartex(),
|
||||
ChartKind::Funnel => ChartType::Funnel.is_chartex(),
|
||||
@@ -64,7 +65,8 @@ fn chartex_text(tx: &El) -> Option<String> {
|
||||
pub(crate) fn from_dml_chartex(dc: craft_drawingml::chart::Chart, root: Option<&El>) -> Option<Chart> {
|
||||
use craft_drawingml::chart::ChartType;
|
||||
let kind = match dc.kind {
|
||||
ChartType::Histogram | ChartType::Pareto => ChartKind::Histogram,
|
||||
ChartType::Histogram => ChartKind::Histogram,
|
||||
ChartType::Pareto => ChartKind::Pareto,
|
||||
ChartType::BoxWhisker => ChartKind::BoxWhisker,
|
||||
ChartType::Waterfall => ChartKind::Waterfall,
|
||||
ChartType::Funnel => ChartKind::Funnel,
|
||||
@@ -73,35 +75,31 @@ pub(crate) fn from_dml_chartex(dc: craft_drawingml::chart::Chart, root: Option<&
|
||||
_ => return None,
|
||||
};
|
||||
let default_quartiles = if dc.inclusive_quartiles { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive };
|
||||
let data: Vec<(String, Option<String>, Option<String>)> = root
|
||||
.and_then(|r| r.child("chartData"))
|
||||
.map(|cd| {
|
||||
cd.kids("data")
|
||||
.map(|d| {
|
||||
let id = d.attr("id").unwrap_or("").to_string();
|
||||
let cat =
|
||||
d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(chartex_formula);
|
||||
let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(chartex_formula);
|
||||
(id, cat, val)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut data = HashMap::new();
|
||||
if let Some(chart_data) = root.and_then(|r| r.child("chartData")) {
|
||||
for d in chart_data.kids("data") {
|
||||
// Match the previous first-definition lookup even if an input repeats an ID.
|
||||
data.entry(d.attr("id").unwrap_or("")).or_insert_with(|| {
|
||||
let cat = d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(chartex_formula);
|
||||
let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(chartex_formula);
|
||||
(cat, val)
|
||||
});
|
||||
}
|
||||
}
|
||||
// Match craft-drawingml's boolean rule: only true literals hide a series. An explicit
|
||||
// hidden="0" is visible and must stay paired with its parsed series by index.
|
||||
let hidden_true = |e: &El| matches!(e.attr("hidden").map(str::trim), Some("1" | "true" | "on" | "t"));
|
||||
let series_els: Vec<&El> = root
|
||||
.and_then(|r| r.path(&["chart", "plotArea", "plotAreaRegion"]))
|
||||
.map(|region| region.kids("series").filter(|s| s.attr("layoutId") != Some("paretoLine")).collect())
|
||||
.map(|region| region.kids("series").filter(|s| s.attr("layoutId") != Some("paretoLine") && !hidden_true(s)).collect())
|
||||
.unwrap_or_default();
|
||||
let series = dc
|
||||
let mut series: Vec<Series> = dc
|
||||
.series
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, s)| {
|
||||
let sel = series_els.get(idx).copied();
|
||||
let (cat, val) = sel
|
||||
.and_then(|el| el.child_val("dataId"))
|
||||
.and_then(|id| data.iter().find(|(i, _, _)| i == id))
|
||||
.map(|(_, c, v)| (c.clone(), v.clone()))
|
||||
.unwrap_or_default();
|
||||
let (cat, val) = sel.and_then(|el| el.child_val("dataId")).and_then(|id| data.get(id)).cloned().unwrap_or_default();
|
||||
let color = s
|
||||
.fill
|
||||
.as_ref()
|
||||
@@ -127,6 +125,33 @@ pub(crate) fn from_dml_chartex(dc: craft_drawingml::chart::Chart, root: Option<&
|
||||
Series { quartiles, name, categories, values, color, ..Default::default() }
|
||||
})
|
||||
.collect();
|
||||
// Excel hides every Pareto column after the first, and craft's chartex parser drops
|
||||
// hidden series. Keep them so the extra value columns survive an xlsx round trip.
|
||||
if kind == ChartKind::Pareto
|
||||
&& let Some(region) = root.and_then(|r| r.path(&["chart", "plotArea", "plotAreaRegion"]))
|
||||
{
|
||||
for sel in region.kids("series").filter(|s| hidden_true(s) && s.attr("layoutId") != Some("paretoLine")) {
|
||||
let (cat, val) = sel.child_val("dataId").and_then(|id| data.get(id)).cloned().unwrap_or_default();
|
||||
let idx = series.len();
|
||||
let quartiles = sel
|
||||
.path(&["layoutPr", "statistics"])
|
||||
.and_then(|st| st.attr("quartileMethod"))
|
||||
.map(|m| if m == "inclusive" { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive })
|
||||
.unwrap_or(default_quartiles);
|
||||
let color = sel
|
||||
.path(&["spPr", "solidFill"])
|
||||
.and_then(crate::drawing::dml_color)
|
||||
.filter(|c| *c != gridcraft_model::Color::Theme(4 + (idx % 6) as u8, 0));
|
||||
series.push(Series {
|
||||
quartiles,
|
||||
name: sel.child("tx").and_then(chartex_text),
|
||||
categories: cat,
|
||||
values: val.unwrap_or_default(),
|
||||
color,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
let legend = match dc.legend.as_deref() {
|
||||
None => LegendPos::None,
|
||||
Some("b") => LegendPos::Bottom,
|
||||
@@ -318,8 +343,15 @@ pub fn write_chartex(wb: &Workbook, si: usize, ch: &Chart, names: &mut Vec<Strin
|
||||
ChartKind::Sunburst => "sunburst",
|
||||
_ => "clusteredColumn",
|
||||
};
|
||||
let pareto = ch.kind == ChartKind::Pareto;
|
||||
// Excel stores one clusteredColumn series per value column and a paretoLine for each,
|
||||
// hiding every column after the first. Opening a Pareto made from two value columns in
|
||||
// Excel 365 and saving it keeps that shape (observed 2026-10-18); the hidden series are
|
||||
// part of Excel's own file, so they stay here too.
|
||||
for (i, ser) in ch.series.iter().enumerate() {
|
||||
let _ = write!(s, "<cx:series layoutId=\"{layout}\" uniqueId=\"{{00000000-0000-0000-0000-{:08X}{i:04X}}}\">", ch.id);
|
||||
// Excel shows the first Pareto series and hides the rest.
|
||||
let hidden = if pareto && i > 0 { " hidden=\"1\"" } else { "" };
|
||||
let _ = write!(s, "<cx:series layoutId=\"{layout}\" uniqueId=\"{{00000000-0000-0000-0000-{:08X}{i:04X}}}\"{hidden}>", ch.id);
|
||||
if let Some(n) = &ser.name {
|
||||
s.push_str(&tx_xml(n, wb, si, names));
|
||||
}
|
||||
@@ -360,13 +392,32 @@ pub fn write_chartex(wb: &Workbook, si: usize, ch: &Chart, names: &mut Vec<Strin
|
||||
);
|
||||
}
|
||||
ChartKind::Treemap => s.push_str("<cx:layoutPr><cx:parentLabelLayout val=\"overlapping\"/></cx:layoutPr>"),
|
||||
ChartKind::Pareto => {
|
||||
if ser.categories.is_some() {
|
||||
s.push_str("<cx:layoutPr><cx:aggregation/></cx:layoutPr>");
|
||||
} else {
|
||||
s.push_str("<cx:layoutPr><cx:binning intervalClosed=\"r\"/></cx:layoutPr>");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if pareto {
|
||||
s.push_str("<cx:axisId val=\"1\"/>");
|
||||
}
|
||||
s.push_str("</cx:series>");
|
||||
if pareto {
|
||||
let _ = write!(
|
||||
s,
|
||||
"<cx:series layoutId=\"paretoLine\" ownerIdx=\"{}\" uniqueId=\"{{00000000-0000-0000-0000-{:08X}{:04X}}}\"><cx:axisId val=\"2\"/></cx:series>",
|
||||
i * 2,
|
||||
ch.id,
|
||||
0x8000 + i
|
||||
);
|
||||
}
|
||||
}
|
||||
s.push_str("</cx:plotAreaRegion>");
|
||||
let gap = match ch.kind {
|
||||
ChartKind::Histogram => Some("0"),
|
||||
ChartKind::Histogram | ChartKind::Pareto => Some("0"),
|
||||
ChartKind::BoxWhisker => Some("1"),
|
||||
ChartKind::Waterfall => Some("0.5"),
|
||||
ChartKind::Funnel => Some("0.06"),
|
||||
@@ -393,6 +444,9 @@ pub fn write_chartex(wb: &Workbook, si: usize, ch: &Chart, names: &mut Vec<Strin
|
||||
);
|
||||
}
|
||||
}
|
||||
if pareto {
|
||||
s.push_str("<cx:axis id=\"2\"><cx:valScaling max=\"1\" min=\"0\"/><cx:units unit=\"percentage\"/><cx:tickLabels/></cx:axis>");
|
||||
}
|
||||
s.push_str("</cx:plotArea>");
|
||||
let pos = match ch.legend {
|
||||
LegendPos::None => None,
|
||||
|
||||
@@ -91,7 +91,7 @@ fn from_craft_el(e: &craft_xml::El) -> El {
|
||||
craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {}
|
||||
}
|
||||
}
|
||||
El { name, attrs, children, text }
|
||||
El { name, attrs, children, text, ..El::default() }
|
||||
}
|
||||
|
||||
/// Colour of a DrawingML colour choice inside `e` (e.g. a `solidFill`).
|
||||
|
||||
@@ -47,10 +47,12 @@ pub const MAX_CODE_BYTES: usize = 64 * 1024 * 1024;
|
||||
/// The scripts read from a workbook's Python part, and what the cells took from them.
|
||||
#[derive(Default)]
|
||||
pub struct ScriptsIn {
|
||||
scripts: Vec<String>,
|
||||
/// Each script's code, `None` for a script whose code the parser dropped at the element cap:
|
||||
/// a cell naming it keeps only its value, as for a script the part doesn't hold.
|
||||
scripts: Vec<Option<String>>,
|
||||
/// Bytes of code the cells may still take ([`MAX_CODE_BYTES`] in all).
|
||||
budget: usize,
|
||||
/// Python cells that kept only their value: no such script, or over the budget.
|
||||
/// Python cells that kept only their value: no such script or code, or over the budget.
|
||||
missing: usize,
|
||||
}
|
||||
|
||||
@@ -89,21 +91,38 @@ pub fn read(cx: &mut Ctx<'_>, rels: &[crate::package::Rel]) -> Result<ScriptsIn,
|
||||
}
|
||||
};
|
||||
let mut over = 0usize;
|
||||
let parsed = xml::parse_streaming(&bytes, &["pythonScript"], &mut |el: El| {
|
||||
let parsed = xml::parse_streaming(&bytes, SCRIPTS, &mut |el: El| {
|
||||
if out.scripts.len() < MAX_SCRIPTS {
|
||||
out.scripts.push(script_code(&el));
|
||||
// A script that lost a `code` at the element cap and kept no code after it (none, or an
|
||||
// empty one) counts as missing code. One that lost no code and has none, or an empty
|
||||
// one, reads as empty code, as before.
|
||||
let code = script_code(&el);
|
||||
out.scripts.push((!el.lost(SCRIPTS.children, "code") || !code.is_empty()).then_some(code));
|
||||
} else {
|
||||
over += 1;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
match parsed {
|
||||
Ok(root) if root.name != "python" => {
|
||||
let (dropped, unlisted) = match parsed {
|
||||
Ok(xml::Streamed { root, .. }) if root.name != "python" => {
|
||||
cx.warn(format!("the Python part has the root <{}>; Python cells kept only their values", root.name));
|
||||
out.scripts.clear();
|
||||
(0, 0)
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => cx.warn(format!("the Python part is damaged ({e}); kept {} scripts", out.scripts.len())),
|
||||
Ok(s) => (s.dropped, s.unlisted),
|
||||
Err(f) => {
|
||||
cx.warn(format!("the Python part is damaged ({}); kept {} scripts", f.error, out.scripts.len()));
|
||||
(f.dropped, f.unlisted)
|
||||
}
|
||||
};
|
||||
if dropped > 0 {
|
||||
cx.warn(format!(
|
||||
"the Python part: dropped {dropped} element(s), counting what they held, that a script may not hold (a second code, unknown elements, or more elements than a part may hold); a script that lost its code and kept no code after it counts as missing"
|
||||
));
|
||||
}
|
||||
// Unknown children that fit are read with their script but not kept: a save writes only the code.
|
||||
if unlisted > 0 {
|
||||
cx.warn(format!("the Python part: {unlisted} element(s) GridCraft does not read (unknown elements) were left out and will not be saved"));
|
||||
}
|
||||
if over > 0 {
|
||||
cx.warn(format!("the Python part holds more than {MAX_SCRIPTS} scripts; {over} were not read"));
|
||||
@@ -118,6 +137,10 @@ pub fn read(cx: &mut Ctx<'_>, rels: &[crate::package::Rel]) -> Result<ScriptsIn,
|
||||
/// worth keep the last of them, and the line break after it, from being cut.
|
||||
const MAX_ENCODED_CHARS: usize = 14 * (2 * (MAX_SCRIPT_CHARS + 1) + 2);
|
||||
|
||||
/// The part is streamed one `pythonScript` at a time; a script's code is its first `code` child,
|
||||
/// the only one read, so one is all a script element keeps.
|
||||
const SCRIPTS: xml::Streaming<'static> = xml::Streaming { split: &["pythonScript"], children: &[("code", 1)] };
|
||||
|
||||
/// A `pythonScript` element's code (ST_Xstring), with `\n` line breaks, cut after
|
||||
/// [`MAX_SCRIPT_CHARS`] characters. The limit is measured on the decoded code, so escapes in the
|
||||
/// file (`_x000D_`, `_x0009_`) don't cut a script that fits; decoding is linear and reads at most
|
||||
@@ -163,8 +186,9 @@ pub enum PyFormula {
|
||||
Not,
|
||||
/// A Python cell with this code.
|
||||
Code(PyCode),
|
||||
/// A `PY(index, …)` call naming a script the part doesn't hold (or over the budget): the
|
||||
/// cell keeps only its cached value, since no calculation can evaluate the formula.
|
||||
/// A `PY(index, …)` call naming a script the part doesn't hold (or whose code was dropped, or
|
||||
/// over the budget): the cell keeps only its cached value, since no calculation can evaluate
|
||||
/// the formula.
|
||||
Missing,
|
||||
}
|
||||
|
||||
@@ -180,7 +204,7 @@ pub fn cell_code(scripts: &mut ScriptsIn, formula: &gridcraft_model::Formula, ra
|
||||
let Some((index, object, params)) = expr.as_deref().and_then(py_call) else {
|
||||
return PyCode::from_formula(raw).map_or(PyFormula::Not, PyFormula::Code);
|
||||
};
|
||||
let code = scripts.scripts.get(index).map(|code| with_params(code, params));
|
||||
let code = scripts.scripts.get(index).and_then(Option::as_deref).map(|code| with_params(code, params));
|
||||
match code.filter(|c| c.len() <= scripts.budget) {
|
||||
Some(code) => {
|
||||
scripts.budget -= code.len();
|
||||
@@ -267,7 +291,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn scripts(list: &[&str]) -> ScriptsIn {
|
||||
ScriptsIn { scripts: list.iter().map(|s| s.to_string()).collect(), budget: MAX_CODE_BYTES, missing: 0 }
|
||||
ScriptsIn { scripts: list.iter().map(|s| Some(s.to_string())).collect(), budget: MAX_CODE_BYTES, missing: 0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -297,7 +321,7 @@ mod tests {
|
||||
fn hostile_scripts_are_bounded() {
|
||||
// Many formulas naming one script take from one budget.
|
||||
let code = "x".repeat(1_000);
|
||||
let mut s = ScriptsIn { scripts: vec![code], budget: 2_500, missing: 0 };
|
||||
let mut s = ScriptsIn { scripts: vec![Some(code)], budget: 2_500, missing: 0 };
|
||||
let f = formula("_xlfn._xlws.PY(0,0)");
|
||||
let taken = (0..5).filter(|_| matches!(cell_code(&mut s, &f, ""), PyFormula::Code(_))).count();
|
||||
assert_eq!(taken, 2);
|
||||
@@ -324,10 +348,11 @@ mod tests {
|
||||
let xml = write(&codes);
|
||||
assert!(xml.contains(NS) && xml.contains("<pythonScripts><pythonScript><code>a = 1\nb = \"two\" & 'three' <tag></code>"), "{xml}");
|
||||
let mut read = Vec::new();
|
||||
let root = xml::parse_streaming(xml.as_bytes(), &["pythonScript"], &mut |el| {
|
||||
let root = xml::parse_streaming(xml.as_bytes(), SCRIPTS, &mut |el| {
|
||||
read.push(script_code(&el));
|
||||
Ok(())
|
||||
})
|
||||
.map(|s| s.root)
|
||||
.unwrap_or_default();
|
||||
assert_eq!(root.name, "python");
|
||||
assert_eq!(read, codes);
|
||||
|
||||
+96
-11
@@ -17,7 +17,12 @@ use crate::{IoError, ReadReport};
|
||||
pub struct Ctx<'a> {
|
||||
pub pkg: Package<'a>,
|
||||
pub report: ReadReport,
|
||||
pub sst: Vec<Arc<str>>,
|
||||
/// The shared strings by index, `None` for a string that lost all its text at the element cap:
|
||||
/// a cell using it reads as one naming a string the table doesn't hold.
|
||||
pub sst: Vec<Option<Arc<str>>>,
|
||||
/// The shared strings longer than Excel allows in a cell, by index: a sheet counts each cell
|
||||
/// it reads that uses one, without scanning the text again.
|
||||
pub long_strings: std::collections::HashSet<usize>,
|
||||
/// Phonetic (furigana) data of the shared strings, one entry per base text.
|
||||
pub phonetics: Vec<PhoneticString>,
|
||||
/// Cell format index → model style.
|
||||
@@ -173,6 +178,16 @@ pub fn find_rel<'r>(rels: &'r [Rel], kind: &str) -> Option<&'r Rel> {
|
||||
rels.iter().find(|r| r.kind == kind)
|
||||
}
|
||||
|
||||
/// What one shared string (`si`) may hold: one `phoneticPr`, and its text without a count, as plain
|
||||
/// text `t`, rich-text runs `r` and phonetic runs `rPh`. The schema allows one `t`, but a second one
|
||||
/// is text the reader has always kept (joined to the first, as in an inline string), and dropping
|
||||
/// text would lose the user's data at the next save, so a string past Excel's length is kept whole
|
||||
/// and warned about instead (its size stays bounded by the part's size limit,
|
||||
/// [`MAX_PART`](crate::package::MAX_PART) bytes). Of other names, the parser hands over up to
|
||||
/// [`MAX_UNLISTED_CHILD_NAMES`](xml::MAX_UNLISTED_CHILD_NAMES) once each, which the reader leaves
|
||||
/// out and counts in a warning, and drops the rest.
|
||||
const STRING_CHILDREN: &[(&str, usize)] = &[("t", usize::MAX), ("phoneticPr", 1), ("r", usize::MAX), ("rPh", usize::MAX)];
|
||||
|
||||
fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError> {
|
||||
// Shared strings, streamed item by item. Phonetic (furigana) runs are kept next to the text
|
||||
// they annotate, so an open + save does not delete them.
|
||||
@@ -182,29 +197,98 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError>
|
||||
let mut sst = Vec::new();
|
||||
let mut phonetics = Vec::new();
|
||||
let mut dropped = 0usize;
|
||||
let res = xml::parse_streaming(&b, &["si"], &mut |si| {
|
||||
let mut long_strings = std::collections::HashSet::new();
|
||||
let mut cut = 0usize;
|
||||
let mut lost = 0usize;
|
||||
let mut unplaced = 0usize;
|
||||
let mut props_lost = 0usize;
|
||||
let res = xml::parse_streaming(&b, xml::Streaming { split: &["si"], children: STRING_CHILDREN }, &mut |si| {
|
||||
if sst.len() >= MAX_STRINGS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_STRINGS} shared strings")));
|
||||
}
|
||||
let text = xml::rich_text(&si);
|
||||
// A string that lost a `t` or a run at the element cap lost text.
|
||||
let text_lost = si.cut != 0 && (si.lost(STRING_CHILDREN, "t") || si.lost(STRING_CHILDREN, "r"));
|
||||
let raw = si.kids("rPh").count();
|
||||
let (runs, props) = xml::phonetic_data(&si, &text);
|
||||
dropped += raw.saturating_sub(runs.len());
|
||||
if !runs.is_empty() || props.is_some() {
|
||||
phonetics.push(PhoneticString { text: text.clone(), runs, props });
|
||||
if text_lost {
|
||||
// Phonetic runs point into the text as the file held it; a part lost at the
|
||||
// cap moves what came after it, so a run could land on other characters.
|
||||
// All of them, damaged or not, are dropped and counted with the cut, and the
|
||||
// string's phonetic properties go with them, so nothing is filed under the
|
||||
// shortened text, where it would stand in for an intact string's reading.
|
||||
unplaced += raw;
|
||||
props_lost += usize::from(si.child("phoneticPr").is_some());
|
||||
}
|
||||
sst.push(Arc::from(text));
|
||||
if si.cut != 0 {
|
||||
cut += 1;
|
||||
// One that lost text and kept none (an empty run kept before it holds
|
||||
// none) counts as missing, as in a table cut short before it, and keeps
|
||||
// its place so the strings after it keep their indexes. One that lost
|
||||
// only phonetic parts keeps its text, empty or not.
|
||||
if text_lost && text.is_empty() {
|
||||
lost += 1;
|
||||
sst.push(None);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Cut or not, text longer than Excel allows is counted by each sheet for the
|
||||
// cells that use it.
|
||||
if xml::exceeds_cell_text(&text) {
|
||||
long_strings.insert(sst.len());
|
||||
}
|
||||
if !text_lost {
|
||||
let (runs, props) = xml::phonetic_data(&si, &text);
|
||||
dropped += raw.saturating_sub(runs.len());
|
||||
if !runs.is_empty() || props.is_some() {
|
||||
phonetics.push(PhoneticString { text: text.clone(), runs, props });
|
||||
}
|
||||
}
|
||||
sst.push(Some(Arc::from(text)));
|
||||
Ok(())
|
||||
});
|
||||
match res {
|
||||
Ok(_) => {}
|
||||
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
|
||||
Err(e) => cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len())),
|
||||
let (dropped_elements, ignored) = match res {
|
||||
Ok(s) => (s.dropped, s.unlisted),
|
||||
Err(xml::StreamFailure { error: IoError::TooLarge(m), .. }) => return Err(IoError::TooLarge(m)),
|
||||
Err(f) => {
|
||||
cx.warn(format!("shared strings are damaged ({}); kept {} strings", f.error, sst.len()));
|
||||
(f.dropped, f.unlisted)
|
||||
}
|
||||
};
|
||||
if dropped_elements > 0 {
|
||||
cx.warn(format!(
|
||||
"shared strings: dropped {dropped_elements} element(s), counting what they held, that a string may not hold (a second phoneticPr, unknown elements, or more elements than a part may hold)"
|
||||
));
|
||||
}
|
||||
if dropped > 0 {
|
||||
cx.warn(format!("shared strings: {dropped} phonetic runs were dropped (bad sb/eb or no reading)"));
|
||||
}
|
||||
if ignored > 0 {
|
||||
cx.warn(format!(
|
||||
"shared strings: {ignored} element(s) GridCraft does not read (unknown elements) were left out and will not be saved"
|
||||
));
|
||||
}
|
||||
if cut > 0 {
|
||||
// A string that kept nothing of its text is said to be missing, so its cells are
|
||||
// not taken for cells that kept part of a string.
|
||||
let missing = if lost > 0 { format!("; {lost} of them kept no text and count as missing strings") } else { String::new() };
|
||||
let phonetic = if unplaced > 0 {
|
||||
format!(
|
||||
"; {unplaced} phonetic run(s) in strings that lost text were dropped, since their offsets point into the text as it was"
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let props = if props_lost > 0 {
|
||||
format!("; {props_lost} of them dropped their phonetic properties with the text they lost")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
cx.warn(format!(
|
||||
"shared strings: {cut} string(s) were being read when the part reached its element limit; each lost, whole, the parts that did not fit within that limit{missing}{phonetic}{props}"
|
||||
));
|
||||
}
|
||||
cx.sst = sst;
|
||||
cx.long_strings = long_strings;
|
||||
cx.keep_phonetics(phonetics);
|
||||
}
|
||||
None => cx.warn(format!("missing part {}", r.target)),
|
||||
@@ -328,6 +412,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
pkg,
|
||||
report: ReadReport::default(),
|
||||
sst: vec![],
|
||||
long_strings: Default::default(),
|
||||
phonetics: vec![],
|
||||
xf_map: vec![],
|
||||
dxfs: vec![],
|
||||
|
||||
@@ -61,6 +61,21 @@ struct RowState {
|
||||
/// The cell being read lost its shared formula to a copy limit: its cached value is kept, even
|
||||
/// inside an array range (where a formula's cached values otherwise give way to the spill).
|
||||
shared_copy_refused: bool,
|
||||
/// Cells and row properties read again where one was already read (see `read_craft_row`).
|
||||
repeated: u64,
|
||||
/// Cells placed out of column order or in another row's element.
|
||||
elsewhere: u64,
|
||||
/// The furthest cell read so far, in row-major order.
|
||||
furthest: Option<CellRef>,
|
||||
/// One bit per column: the columns of its own row the row elements read since the row number
|
||||
/// last changed have held.
|
||||
seen: Vec<u64>,
|
||||
/// The row number of the row elements whose cells `seen` holds.
|
||||
seen_row: Option<u32>,
|
||||
/// How many of `seen`'s words, from the first, may hold a bit.
|
||||
seen_words: usize,
|
||||
/// Cell texts longer than Excel allows, counted as they are read (see `read_craft_cell`).
|
||||
long: u64,
|
||||
}
|
||||
|
||||
/// The known dynamic range `pos` lies in, when it isn't the range's anchor: the cell's cached
|
||||
@@ -182,7 +197,7 @@ fn from_craft_el(e: &craft_xml::El) -> El {
|
||||
craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {}
|
||||
}
|
||||
}
|
||||
El { name, attrs, children, text }
|
||||
El { name, attrs, children, text, ..El::default() }
|
||||
}
|
||||
|
||||
fn to_range_ref(r: craft_xlsx::Range) -> RangeRef {
|
||||
@@ -261,6 +276,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
cx.warn(w);
|
||||
}
|
||||
settle_python_spills_past_budget(&st, &mut sheet);
|
||||
warn_row_state(cx, name, &st);
|
||||
|
||||
apply_craft_sheet_part(cx, &sheet_part, &rels, name, too_many_merges, &mut sheet)?;
|
||||
let root = from_craft_el(&sheet_part.root);
|
||||
@@ -721,6 +737,33 @@ fn read_protected_ranges(e: &El, sheet: &mut Sheet) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Says what the rows of sheet `name` read twice, placed elsewhere or read past Excel's length.
|
||||
fn warn_row_state(cx: &mut Ctx<'_>, name: &str, st: &RowState) {
|
||||
if st.repeated > 0 {
|
||||
// A later cell or row is read again where the earlier one was, as on main, which mostly
|
||||
// leaves the last one read; not always: a cell repeating a picture cell's address replaces
|
||||
// the cell's value, but the picture stays and is what is saved, and an empty cell repeating
|
||||
// a value in a Python cell's spill leaves that value.
|
||||
cx.warn(format!(
|
||||
"sheet \"{name}\": {} cell(s), or a row's properties, repeated an address or row already read; the later ones were read again",
|
||||
st.repeated
|
||||
));
|
||||
}
|
||||
if st.elsewhere > 0 {
|
||||
cx.warn(format!(
|
||||
"sheet \"{name}\": {} cell(s) sat out of column order, or in another row's element, and were placed where their addresses say",
|
||||
st.elsewhere
|
||||
));
|
||||
}
|
||||
if st.long > 0 {
|
||||
cx.warn(format!(
|
||||
"sheet \"{name}\": {} cell text(s) longer than Excel's limit of {} UTF-16 units were read; they were not cut to that length",
|
||||
st.long,
|
||||
gridcraft_core::MAX_CELL_CHARS
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charges `n` cell elements against the workbook's [`MAX_CELLS`].
|
||||
fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> {
|
||||
cx.cells = cx.cells.saturating_add(n);
|
||||
@@ -745,30 +788,100 @@ fn read_craft_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &
|
||||
if let Some(s) = row.style {
|
||||
info.style = Some(cx.style(Some(s)));
|
||||
}
|
||||
if info != LineInfo::default() {
|
||||
sheet.rows.insert(r, info);
|
||||
// A row whose properties are read again over ones already read is counted, the later ones
|
||||
// kept. A repeated row without properties leaves the earlier ones, as on main, and isn't
|
||||
// counted.
|
||||
if info != LineInfo::default() && sheet.rows.insert(r, info).is_some() {
|
||||
st.repeated = st.repeated.saturating_add(1);
|
||||
}
|
||||
// The rightmost column of the cells this row element has held so far: a cell not to its right
|
||||
// is out of column order.
|
||||
let mut rightmost: Option<u32> = None;
|
||||
st.seen.resize(MAX_COLS.div_ceil(64) as usize, 0);
|
||||
// A row element with another row number than the one before starts with no column held: the
|
||||
// words the earlier ones may have set are cleared. Row elements of the same number in a row
|
||||
// share the bits, so a cell repeating one of an earlier element for its row is seen.
|
||||
if st.seen_row != Some(r) {
|
||||
st.seen.iter_mut().take(st.seen_words).for_each(|w| *w = 0);
|
||||
st.seen_row = Some(r);
|
||||
st.seen_words = 0;
|
||||
}
|
||||
for c in &row.cells {
|
||||
charge_cells(cx, 1).map_err(|e| craft_xlsx::Error::TooLarge(e.to_string()))?;
|
||||
let pos = CellRef::new(c.at.row, c.at.col);
|
||||
// Every cell is placed where its address says. A cell of this row element's own row at a
|
||||
// column held already, by this element or by an element for the same row right before it,
|
||||
// repeats it, whatever the reader stored for it. Past that, a cell at the furthest position
|
||||
// read so far, in row-major order, repeats it; one before it repeats an address when a
|
||||
// cell, a cell picture or a Python spill value is stored there. So a cell the reader stores
|
||||
// nothing for (such as a blank cell without a style or a value inside another formula's array) is
|
||||
// seen repeated by a cell of its own row in a later row element only when no element for
|
||||
// another row came between them, or at the furthest position read so far; elsewhere it is
|
||||
// counted as out of order when it is, or not at all. A cell of the element's own row takes
|
||||
// one bit test; only a cell that isn't past the furthest one (never, in a file Excel
|
||||
// wrote) is looked up, in up to three maps.
|
||||
let past = st.furthest.is_none_or(|f| pos > f);
|
||||
let (word, bit) = ((pos.col / 64) as usize, 1u64 << (pos.col % 64));
|
||||
let mut held = false;
|
||||
if pos.row == r
|
||||
&& let Some(w) = st.seen.get_mut(word)
|
||||
{
|
||||
held = *w & bit != 0;
|
||||
*w |= bit;
|
||||
}
|
||||
let repeat = held
|
||||
|| !past
|
||||
&& (st.furthest == Some(pos)
|
||||
|| sheet.cells.get(pos).is_some()
|
||||
|| sheet.cell_pictures.contains_key(&pos)
|
||||
|| sheet.spill.contains_key(&pos));
|
||||
if repeat {
|
||||
st.repeated = st.repeated.saturating_add(1);
|
||||
} else if pos.row != r || rightmost.is_some_and(|m| pos.col <= m) {
|
||||
// Out of column order, or naming another row than the one it sits in: placed where
|
||||
// its address says, as it always has been, and said.
|
||||
st.elsewhere = st.elsewhere.saturating_add(1);
|
||||
}
|
||||
if past {
|
||||
st.furthest = Some(pos);
|
||||
}
|
||||
rightmost = rightmost.max(Some(pos.col));
|
||||
read_craft_cell(cx, sheet, st, c, pos);
|
||||
}
|
||||
// The words up to the rightmost cell's hold every bit this element's cells set.
|
||||
if let Some(m) = rightmost {
|
||||
st.seen_words = st.seen_words.max(((m / 64) as usize).saturating_add(1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_craft_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &craft_xlsx::Cell, pos: CellRef) {
|
||||
let style = cx.style((c.style != 0).then_some(c.style));
|
||||
// Text longer than Excel allows is kept whole, since cutting it would lose the user's data at
|
||||
// the next save; it is counted for the warning as the cell is read (see below).
|
||||
let mut long = false;
|
||||
let value = match &c.value {
|
||||
CraftValue::Empty => Value::Empty,
|
||||
CraftValue::Shared(i) => match cx.sst.get(*i as usize) {
|
||||
Some(s) => Value::Text(s.clone()),
|
||||
CraftValue::Shared(i) => match cx.sst.get(*i as usize).and_then(Option::as_ref) {
|
||||
Some(s) => {
|
||||
// A text within the limit in bytes is within it in units; only longer ones are looked up.
|
||||
long = s.len() > gridcraft_core::MAX_CELL_CHARS as usize && cx.long_strings.contains(&(*i as usize));
|
||||
Value::Text(s.clone())
|
||||
}
|
||||
// Past the table, or a string that lost text at the element cap and kept none.
|
||||
None => {
|
||||
cx.warn("some cells refer to missing shared strings");
|
||||
Value::Empty
|
||||
}
|
||||
},
|
||||
CraftValue::Text(t) => Value::Text(t.as_ref().into()),
|
||||
CraftValue::Inline(s) => Value::Text(s.text.as_ref().into()),
|
||||
CraftValue::Text(t) => {
|
||||
long = xml::exceeds_cell_text(t);
|
||||
Value::Text(t.as_ref().into())
|
||||
}
|
||||
CraftValue::Inline(s) => {
|
||||
long = xml::exceeds_cell_text(&s.text);
|
||||
Value::Text(s.text.as_ref().into())
|
||||
}
|
||||
CraftValue::Bool(b) => Value::Bool(*b),
|
||||
CraftValue::Error(e) => Value::Error(map_craft_error(*e)),
|
||||
CraftValue::Date(d) => match parse_iso_datetime(d, cx.date_system) {
|
||||
@@ -827,6 +940,10 @@ fn read_craft_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &c
|
||||
let python_anchor = spilled_from.is_some_and(|r| sheet.cells.get(r.start).is_some_and(|a| a.py.is_some()));
|
||||
let value = match spilled_from {
|
||||
Some(r) if python_anchor && r.count() <= gridcraft_model::python::MAX_RESULT_CELLS as u64 => {
|
||||
// A Python cell's spilled text is kept and saved, so a long one counts.
|
||||
if long && matches!(value, Value::Text(_)) {
|
||||
st.long = st.long.saturating_add(1);
|
||||
}
|
||||
if !value.is_empty() {
|
||||
sheet.spill.insert(pos, value);
|
||||
}
|
||||
@@ -843,6 +960,14 @@ fn read_craft_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &c
|
||||
{
|
||||
sheet.spill_ranges.insert(pos, *r);
|
||||
}
|
||||
// A long text is counted as the cell is read, so one that a later cell at the same address
|
||||
// replaces is still counted. Not counted, since the cell doesn't keep them: a picture's
|
||||
// fallback (returned above), a value inside another formula's array, and the cached result of
|
||||
// a formula that parses, which opening the workbook calculates again (one that doesn't parse
|
||||
// keeps its cached text, and is counted).
|
||||
if long && formula.as_ref().is_none_or(|f| f.expr.is_none()) && matches!(value, Value::Text(_)) {
|
||||
st.long = st.long.saturating_add(1);
|
||||
}
|
||||
sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style, py });
|
||||
}
|
||||
|
||||
@@ -1105,6 +1230,7 @@ mod tests {
|
||||
pkg,
|
||||
report: Default::default(),
|
||||
sst: vec![],
|
||||
long_strings: Default::default(),
|
||||
phonetics: vec![],
|
||||
xf_map: vec![],
|
||||
dxfs: vec![],
|
||||
|
||||
@@ -18,6 +18,7 @@ mod extlist;
|
||||
mod fixtures;
|
||||
mod google_sheets_dummy;
|
||||
mod ink_roundtrip;
|
||||
mod limits;
|
||||
mod literal_category_roundtrip;
|
||||
mod locale_numfmt;
|
||||
mod malformed;
|
||||
|
||||
+102
-283
@@ -687,294 +687,113 @@ fn doughnut_writes_every_series_as_a_ring_with_hole_and_angle() {
|
||||
assert_eq!((ch.kind, ch.series.len(), ch.hole_size, ch.first_slice_angle), (ChartKind::Doughnut, 2, 25, 180));
|
||||
}
|
||||
|
||||
/// #377: a WordArt-style text box keeps its run size, bold, typeface, text fill and outline, its
|
||||
/// centring (horizontal and vertical) and its "no outline" shape line, through a round trip.
|
||||
#[test]
|
||||
fn text_box_formatting_is_read_and_written() {
|
||||
let drawing = r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><xdr:twoCellAnchor>
|
||||
<xdr:from><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>2</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>7</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>8</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>
|
||||
<xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="2" name="TextBox 1"/><xdr:cNvSpPr txBox="1"/></xdr:nvSpPr>
|
||||
<xdr:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:ln w="9525" cmpd="sng"><a:noFill/></a:ln></xdr:spPr>
|
||||
<xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip" wrap="square" rtlCol="0" anchor="ctr"/><a:lstStyle/>
|
||||
<a:p><a:pPr algn="ctr"/><a:r><a:rPr lang="en-US" sz="5400" b="1"><a:ln w="19050"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill></a:ln><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:latin typeface="Arial Black"/></a:rPr><a:t>DRAFT</a:t></a:r></a:p></xdr:txBody></xdr:sp><xdr:clientData/></xdr:twoCellAnchor></xdr:wsDr>"#;
|
||||
let srels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/></Relationships>"#;
|
||||
let bytes = minimal(
|
||||
r#"<sheetData/><drawing r:id="rId1"/>"#,
|
||||
&[("xl/worksheets/_rels/sheet1.xml.rels", srels), ("xl/drawings/drawing1.xml", drawing)],
|
||||
"",
|
||||
"",
|
||||
);
|
||||
let (wb, _) = read_xlsx(&bytes).unwrap();
|
||||
let sp = &wb.sheet(0).unwrap().shapes[0];
|
||||
assert_eq!(sp.kind, gridcraft_model::ShapeKind::TextBox);
|
||||
assert_eq!(sp.text, "DRAFT");
|
||||
let f = &sp.format;
|
||||
assert!(f.no_line, "a:ln/a:noFill: no border");
|
||||
assert_eq!(f.font_size, Some(54.0));
|
||||
assert!(f.bold && !f.italic);
|
||||
assert_eq!(f.font.as_deref(), Some("Arial Black"));
|
||||
assert_eq!(f.text_color, Some(Color::Theme(0, 0)));
|
||||
assert_eq!(f.text_outline, Some((Color::Theme(1, 0), 1.5)));
|
||||
assert_eq!(f.align, Some(gridcraft_model::ShapeTextAlign::Center));
|
||||
assert_eq!(f.anchor, Some(gridcraft_model::ShapeTextAnchor::Middle));
|
||||
|
||||
let (back, _) = read_xlsx(&crate::write_xlsx(&wb).unwrap()).unwrap();
|
||||
let g = &back.sheet(0).unwrap().shapes[0].format;
|
||||
let rgb = |c: Option<Color>| c.and_then(|c| c.resolve(&wb.theme));
|
||||
assert_eq!((g.no_line, g.font_size, g.bold, g.font.as_deref()), (true, Some(54.0), true, Some("Arial Black")));
|
||||
assert_eq!((g.align, g.anchor), (f.align, f.anchor));
|
||||
assert_eq!(rgb(g.text_color), rgb(f.text_color));
|
||||
assert_eq!(rgb(g.text_outline.map(|o| o.0)), rgb(f.text_outline.map(|o| o.0)));
|
||||
assert_eq!(g.text_outline.map(|o| o.1), Some(1.5));
|
||||
}
|
||||
|
||||
/// #1013: cell format 0 is the workbook's Normal cell format. A file that gives it a number
|
||||
/// format, fill, alignment or protection must keep all of it for cells that omit their style (or
|
||||
/// say s="0"), not only the font.
|
||||
#[test]
|
||||
fn the_default_cell_format_keeps_every_property_of_xf_zero() {
|
||||
let styles = r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>
|
||||
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FF00B050"/><bgColor indexed="64"/></patternFill></fill></fills>
|
||||
<borders count="1"><border/></borders>
|
||||
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
|
||||
<cellXfs count="2"><xf numFmtId="2" fontId="0" fillId="1" borderId="0" applyNumberFormat="1" applyFill="1" applyAlignment="1" applyProtection="1"><alignment horizontal="center"/><protection locked="0"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellXfs>
|
||||
</styleSheet>"#;
|
||||
let rels = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#;
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><v>5</v></c><c r="B1" s="0"><v>5</v></c></row></sheetData>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[("xl/styles.xml", styles)], rels, "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
let check = |st: &gridcraft_model::Style, when: &str| {
|
||||
assert_eq!(st.num_fmt.as_str(), "0.00", "number format {when}");
|
||||
assert_eq!(st.fill.pattern, PatternType::Solid, "fill {when}");
|
||||
assert_eq!(st.fill.fg, Color::Rgb(0x00B050), "fill colour {when}");
|
||||
assert_eq!(st.align.h, HAlign::Center, "alignment {when}");
|
||||
assert!(!st.protection.locked, "protection {when}");
|
||||
};
|
||||
check(wb.styles.get(StyleId::DEFAULT), "after reading");
|
||||
assert_eq!(s.cell(at("A1")).unwrap().style, StyleId::DEFAULT);
|
||||
assert_eq!(s.cell(at("B1")).unwrap().style, StyleId::DEFAULT);
|
||||
let (back, _) = read_xlsx(&crate::write_xlsx(&wb).unwrap()).unwrap();
|
||||
check(back.styles.get(StyleId::DEFAULT), "after saving");
|
||||
}
|
||||
|
||||
/// `_xludf.` marks a user-defined call even when a built-in has the same name; dropping it turns
|
||||
/// the call into the built-in, and `_xludf.EOMONTH()` into a call Excel repairs away (#726).
|
||||
#[test]
|
||||
fn user_defined_function_prefix_round_trips() {
|
||||
let cases =
|
||||
[("A1", "_xludf.EOMONTH()"), ("A2", "_xludf.CONCAT(\"a\",\"b\")"), ("A3", "_xludf.SUM(1,2)"), ("A4", "MYUDF(1)"), ("A5", "_xludf.MYUDF(1)")];
|
||||
let rows: String = cases
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (a, f))| format!(r#"<row r="{}"><c r="{a}"><f>{}</f></c></row>"#, i + 1, f.replace('"', """)))
|
||||
.collect();
|
||||
let (wb, _) = read_xlsx(&minimal(&format!("<sheetData>{rows}</sheetData>"), &[], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
for (a, f) in cases {
|
||||
assert_eq!(s.cell(at(a)).unwrap().formula.as_ref().unwrap().text, f, "read {a}");
|
||||
}
|
||||
fn pareto_chartex_parts() {
|
||||
use gridcraft_model::{Chart, ChartKind, LegendPos, Series};
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
let mut sheet = gridcraft_model::Sheet::new("Data");
|
||||
sheet.charts.push(Chart {
|
||||
id: 1,
|
||||
kind: ChartKind::Pareto,
|
||||
anchor: Default::default(),
|
||||
title: None,
|
||||
series: vec![Series {
|
||||
name: Some("Data!$B$1".into()),
|
||||
categories: Some("Data!$A$2:$A$5".into()),
|
||||
values: "Data!$B$2:$B$5".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
legend: LegendPos::None,
|
||||
data_labels: false,
|
||||
data_table: None,
|
||||
gridlines: true,
|
||||
style: 2,
|
||||
hole_size: 75,
|
||||
first_slice_angle: 0,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: None,
|
||||
});
|
||||
wb.sheets = vec![std::sync::Arc::new(sheet)];
|
||||
let bytes = crate::write_xlsx(&wb).unwrap();
|
||||
let mut pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
for (a, f) in cases {
|
||||
let cell = sheet.child("sheetData").unwrap().kids("row").flat_map(|r| r.kids("c")).find(|c| c.attr("r") == Some(a)).unwrap();
|
||||
assert_eq!(cell.child("f").unwrap().text, f, "written {a}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A formula saved without dynamic-array metadata is a legacy formula: Excel intersects a range
|
||||
/// given where one value is expected with the formula's row or column, and shows the formula with
|
||||
/// `@` there. Dynamic-array formulas (`cm`) and Ctrl+Shift+Enter arrays are read as written.
|
||||
#[test]
|
||||
fn legacy_formulas_read_with_implicit_intersection() {
|
||||
let body = r#"<sheetData>
|
||||
<row r="1"><c r="A1"><v>1</v></c></row>
|
||||
<row r="2"><c r="A2"><v>2</v></c><c r="B2"><f>TANH(A1:A3)</f><v>0.96</v></c><c r="C2" cm="1"><f t="array" ref="C2:C4">TANH(A1:A3)</f><v>0.76</v></c><c r="D2"><f t="array" ref="D2:D4">TANH(A1:A3)</f><v>0.76</v></c></row>
|
||||
<row r="3"><c r="A3"><v>3</v></c><c r="B3"><f>SUM(A1:A3)</f><v>6</v></c><c r="E3"><f>SUMPRODUCT(A1:A3*A1:A3)</f><v>14</v></c></row>
|
||||
<row r="4"><c r="B4"><f>A1:A3+Vals*2</f></c><c r="E4"><f>INDEX(A1:C3,0,1)</f></c><c r="F4"><f>IF(A1>0,A1:A3,0)</f></c><c r="G4"><f>SUM(IF(A1:A3>1,A1:A3))</f></c></row>
|
||||
<row r="5"><c r="A5"><v>4</v></c><c r="B5"><v>5</v></c><c r="C5"><v>6</v></c></row>
|
||||
<row r="7"><c r="B7"><f>TANH(A5:C5)</f></c><c r="C7"><f>COUNTIF(A1:A3,">1")+ROWS(A1:A3)</f></c><c r="D7"><f>ROW(A1:A3)</f></c><c r="E7"><f>T(A5:C5)</f></c></row>
|
||||
</sheetData>"#;
|
||||
let names = r#"<definedNames><definedName name="Vals">Data!$A$1:$A$3</definedName></definedNames>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", names)).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
let f = |a: &str| s.cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| (f.text.clone(), f.array)).unwrap();
|
||||
let cases = [
|
||||
("B2", "TANH(@A1:A3)"),
|
||||
("C2", "TANH(A1:A3)"),
|
||||
("B3", "SUM(A1:A3)"),
|
||||
("E3", "SUMPRODUCT(A1:A3*A1:A3)"),
|
||||
("B4", "@A1:A3+@Vals*2"),
|
||||
("E4", "@INDEX(A1:C3,0,1)"),
|
||||
("F4", "IF(A1>0,@A1:A3,0)"),
|
||||
("G4", "SUM(IF(@A1:A3>1,A1:A3))"),
|
||||
("B7", "TANH(@A5:C5)"),
|
||||
("C7", "COUNTIF(A1:A3,\">1\")+ROWS(A1:A3)"),
|
||||
("D7", "@ROW(A1:A3)"),
|
||||
// T reads a reference's top-left cell rather than intersecting it.
|
||||
("E7", "@T(A5:C5)"),
|
||||
];
|
||||
for (a, text) in cases {
|
||||
assert_eq!(f(a), (text.to_string(), None), "{a}");
|
||||
}
|
||||
assert_eq!(f("D2"), ("TANH(A1:A3)".to_string(), RangeRef::parse("D2:D4")));
|
||||
}
|
||||
|
||||
/// The caller's function facts decide what a legacy formula means: an add-in function takes the
|
||||
/// range whole and its result is intersected; a parameter the library says takes an array is not
|
||||
/// intersected. Saving the intersected add-in call writes it back as the legacy formula it was.
|
||||
#[test]
|
||||
fn legacy_formulas_use_the_callers_function_facts() {
|
||||
let body = r#"<sheetData>
|
||||
<row r="1"><c r="A1"><v>1</v></c></row>
|
||||
<row r="2"><c r="A2"><v>2</v></c><c r="B2"><f>MYUDF(A1:A3)</f></c><c r="C2"><f>TANH(A1:A3)</f></c></row>
|
||||
<row r="3"><c r="A3"><v>3</v></c></row>
|
||||
</sheetData>"#;
|
||||
let bytes = minimal(body, &[], "", "");
|
||||
let library = crate::FunctionInfo { is_builtin: |n| n != "MYUDF", is_scalar_arg: |n, _| n != "TANH" };
|
||||
let text =
|
||||
|wb: &gridcraft_model::Workbook, a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap();
|
||||
let (plain, _) = read_xlsx(&bytes).unwrap();
|
||||
assert_eq!(text(&plain, "B2"), "MYUDF(@A1:A3)", "without facts every function is built in");
|
||||
assert_eq!(text(&plain, "C2"), "TANH(@A1:A3)");
|
||||
let (wb, _) = crate::read_xlsx_with(&bytes, library).unwrap();
|
||||
assert_eq!(text(&wb, "B2"), "@MYUDF(A1:A3)");
|
||||
assert_eq!(text(&wb, "C2"), "TANH(A1:A3)");
|
||||
let out = crate::write_xlsx_with(&wb, crate::XlsxKind::Workbook, library).unwrap();
|
||||
let mut pkg = crate::package::Package::open(&out).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
let b2 = sheet.child("sheetData").unwrap().kids("row").flat_map(|r| r.kids("c")).find(|c| c.attr("r") == Some("B2")).unwrap();
|
||||
assert_eq!(b2.attr("cm"), None);
|
||||
assert_eq!(b2.child("f").map(|f| f.text.as_str()), Some("MYUDF(A1:A3)"));
|
||||
let (back, _) = crate::read_xlsx_with(&out, library).unwrap();
|
||||
assert_eq!(text(&back, "B2"), "@MYUDF(A1:A3)");
|
||||
}
|
||||
|
||||
/// Legacy IF does not evaluate its condition as an array inside SUMPRODUCT, nor IFERROR and IFNA
|
||||
/// their arguments (that needs Ctrl+Shift+Enter): they are intersected there, while IF's results
|
||||
/// stay arrays.
|
||||
#[test]
|
||||
fn legacy_if_and_iferror_arguments_are_intersected_inside_array_functions() {
|
||||
let body = r#"<sheetData>
|
||||
<row r="1"><c r="A1"><v>1</v></c></row>
|
||||
<row r="2"><c r="A2"><v>2</v></c><c r="D2"><f>SUMPRODUCT(IFERROR(A1:A3/A1:A3,0))</f></c><c r="E2"><f>SUMPRODUCT(IFNA(A1:A3,0),A1:A3)</f></c></row>
|
||||
<row r="3"><c r="A3"><v>3</v></c></row>
|
||||
<row r="4"><c r="D4"><f>SUMPRODUCT(IF(A1:A3>1,1,0))</f></c><c r="E4"><f>SUMPRODUCT(IF(A1>1,A1:A3,0))</f></c></row>
|
||||
</sheetData>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
let text = |a: &str| wb.sheet(0).unwrap().cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap();
|
||||
assert_eq!(text("D2"), "SUMPRODUCT(IFERROR(@A1:A3/@A1:A3,0))");
|
||||
assert_eq!(text("E2"), "SUMPRODUCT(IFNA(@A1:A3,0),A1:A3)");
|
||||
assert_eq!(text("D4"), "SUMPRODUCT(IF(@A1:A3>1,1,0))");
|
||||
assert_eq!(text("E4"), "SUMPRODUCT(IF(A1>1,A1:A3,0))");
|
||||
}
|
||||
/// `customWidth="1"` pins a column even when its width rounds to the default: Standard Width does not
|
||||
/// move it, and a save must keep its `<col>` (openpyxl writes 9.08 for Excel's 8.43, #1607).
|
||||
#[test]
|
||||
fn custom_widths_equal_to_the_default_round_trip() {
|
||||
let body = r#"<sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
|
||||
<cols><col min="4" max="5" width="9.08" customWidth="1"/><col min="6" max="6" width="9.140625" customWidth="1"/><col min="7" max="7" width="9.2" customWidth="1"/><col min="8" max="8" width="9.140625"/></cols>
|
||||
<sheetData/>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
assert_eq!(s.default_col_width, 64.0);
|
||||
for c in 3..=6 {
|
||||
assert_eq!(s.cols.get(&c).and_then(|i| i.size), Some(64.0), "read col {c}");
|
||||
}
|
||||
assert_eq!(s.cols.get(&7), None, "a width without customWidth equal to the default stays the default");
|
||||
let bytes = crate::write_xlsx(&wb).unwrap();
|
||||
let mut pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
let cols: Vec<_> =
|
||||
sheet.child("cols").unwrap().kids("col").map(|c| (c.attr_u32("min"), c.attr_u32("max"), c.flag("customWidth", false))).collect();
|
||||
assert_eq!(cols, [(Some(4), Some(7), true)]);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut cx = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("xl/charts/chartEx1.xml").unwrap(), &mut cx).unwrap();
|
||||
assert!(cx.contains("layoutId=\"clusteredColumn\""), "{cx}");
|
||||
assert!(cx.contains("<cx:aggregation />") || cx.contains("<cx:aggregation/>"), "{cx}");
|
||||
assert!(cx.contains("layoutId=\"paretoLine\" ownerIdx=\"0\""), "{cx}");
|
||||
assert!(cx.contains("<cx:axisId val=\"1\"/>") && cx.contains("<cx:axisId val=\"2\"/>"), "{cx}");
|
||||
assert!(cx.contains("<cx:units unit=\"percentage\"/>"), "{cx}");
|
||||
assert!(cx.contains("<cx:valScaling max=\"1\" min=\"0\"/>"), "{cx}");
|
||||
let (back, _) = crate::read_xlsx(&bytes).unwrap();
|
||||
assert_eq!(back.sheet(0).unwrap().charts[0].kind, ChartKind::Pareto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_skipped_drawing_object_is_reported() {
|
||||
let frame = |row: u32, rid: &str| {
|
||||
format!(
|
||||
r#"<xdr:twoCellAnchor><xdr:from><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>{row}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>3</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>{}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to><xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="2" name="C"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/drawing/2014/chartex">{rid}</a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor>"#,
|
||||
row + 5
|
||||
)
|
||||
};
|
||||
let missing = r#"<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId9"/>"#;
|
||||
let gone = r#"<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId1"/>"#;
|
||||
let drawing = format!(
|
||||
r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">{}{}{}{}{}</xdr:wsDr>"#,
|
||||
frame(0, ""),
|
||||
frame(10, ""),
|
||||
frame(20, ""),
|
||||
frame(30, missing),
|
||||
frame(40, gone)
|
||||
);
|
||||
let drels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../charts/chart9.xml"/></Relationships>"#;
|
||||
let srels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/></Relationships>"#;
|
||||
let bytes = super::minimal(
|
||||
r#"<sheetData/><drawing r:id="rId1"/>"#,
|
||||
&[("xl/worksheets/_rels/sheet1.xml.rels", srels), ("xl/drawings/drawing1.xml", &drawing), ("xl/drawings/_rels/drawing1.xml.rels", drels)],
|
||||
"",
|
||||
"",
|
||||
);
|
||||
let (_, rep) = read_xlsx(&bytes).unwrap();
|
||||
for n in 1..=5 {
|
||||
let tag = format!("object {n})");
|
||||
let hits = rep.warnings.iter().filter(|w| w.contains("skipped") && w.contains("drawing1.xml") && w.contains(&tag)).count();
|
||||
assert_eq!(hits, 1, "object {n}: {:?}", rep.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// A number format code repeated by many differential formats is read into one allocation.
|
||||
#[test]
|
||||
fn inline_dxf_number_formats_are_shared() {
|
||||
let code = format!("0.00{}", " \"x\"".repeat(50));
|
||||
let dxfs: String = (0..3).map(|_| format!(r#"<dxf><numFmt numFmtId="170" formatCode="{}"/></dxf>"#, code.replace('"', """))).collect();
|
||||
let styles =
|
||||
format!(r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dxfs count="3">{dxfs}</dxfs></styleSheet>"#);
|
||||
let root = crate::xml::parse(styles.as_bytes()).unwrap();
|
||||
let read = crate::styles::read_styles(&root, &[], "Calibri");
|
||||
assert_eq!(read.dxfs.len(), 3);
|
||||
assert_eq!(read.dxfs[0].num_fmt.as_str(), code);
|
||||
assert!(read.dxfs.iter().all(|d| std::sync::Arc::ptr_eq(&d.num_fmt.0, &read.dxfs[0].num_fmt.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_column_groups_on_different_axes_preserve_secondary_and_kind() {
|
||||
let drawing = r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<xdr:twoCellAnchor><xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>6</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>15</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to><xdr:graphicFrame><xdr:nvGraphicFramePr><xdr:cNvPr id="2" name="Chart 1"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId1"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor>
|
||||
</xdr:wsDr>"#;
|
||||
let chart = r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart><c:plotArea>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:tx><c:v>Primary</c:v></c:tx><c:val><c:numRef><c:f>Data!$B$2:$B$5</c:f></c:numRef></c:val></c:ser><c:axId val="1"/><c:axId val="2"/></c:barChart>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="1"/><c:tx><c:v>Secondary</c:v></c:tx><c:val><c:numRef><c:f>Data!$C$2:$C$5</c:f></c:numRef></c:val></c:ser><c:axId val="3"/><c:axId val="4"/></c:barChart>
|
||||
<c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx><c:catAx><c:axId val="3"/></c:catAx><c:valAx><c:axId val="4"/></c:valAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>"#;
|
||||
let drels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../charts/chart1.xml"/></Relationships>"#;
|
||||
let srels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/></Relationships>"#;
|
||||
let bytes = minimal(
|
||||
r#"<sheetData/><drawing r:id="rId1"/>"#,
|
||||
&[
|
||||
("xl/worksheets/_rels/sheet1.xml.rels", srels),
|
||||
("xl/drawings/drawing1.xml", drawing),
|
||||
("xl/drawings/_rels/drawing1.xml.rels", drels),
|
||||
("xl/charts/chart1.xml", chart),
|
||||
fn pareto_multi_series_keeps_one_hidden_column_per_extra_series() {
|
||||
use gridcraft_model::{Chart, ChartKind, LegendPos, Series};
|
||||
// Excel 365 keeps the second value column as a hidden clusteredColumn plus its own
|
||||
// paretoLine (observed by opening and re-saving such a chart). The writer must match.
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
let mut sheet = gridcraft_model::Sheet::new("Data");
|
||||
sheet.charts.push(Chart {
|
||||
id: 1,
|
||||
kind: ChartKind::Pareto,
|
||||
anchor: Default::default(),
|
||||
title: None,
|
||||
series: vec![
|
||||
Series {
|
||||
name: Some("Data!$B$1".into()),
|
||||
categories: Some("Data!$A$2:$A$5".into()),
|
||||
values: "Data!$B$2:$B$5".into(),
|
||||
..Default::default()
|
||||
},
|
||||
Series {
|
||||
name: Some("Data!$C$1".into()),
|
||||
categories: Some("Data!$A$2:$A$5".into()),
|
||||
values: "Data!$C$2:$C$5".into(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
"",
|
||||
"",
|
||||
legend: LegendPos::None,
|
||||
data_labels: false,
|
||||
data_table: None,
|
||||
gridlines: true,
|
||||
style: 2,
|
||||
hole_size: 75,
|
||||
first_slice_angle: 0,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: None,
|
||||
});
|
||||
wb.sheets = vec![std::sync::Arc::new(sheet)];
|
||||
let bytes = crate::write_xlsx(&wb).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut cx = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("xl/charts/chartEx1.xml").unwrap(), &mut cx).unwrap();
|
||||
assert_eq!(cx.matches("layoutId=\"clusteredColumn\"").count(), 2, "{cx}");
|
||||
assert_eq!(cx.matches("hidden=\"1\"").count(), 1, "one column hidden, as Excel writes it: {cx}");
|
||||
assert_eq!(cx.matches("layoutId=\"paretoLine\"").count(), 2, "a cumulative line per column, as Excel writes it: {cx}");
|
||||
assert!(cx.contains("ownerIdx=\"0\"") && cx.contains("ownerIdx=\"2\""), "{cx}");
|
||||
assert!(cx.contains("<cx:data id=\"1\">"), "the hidden column keeps its data: {cx}");
|
||||
let (back, _) = crate::read_xlsx(&bytes).unwrap();
|
||||
let after = &back.sheet(0).unwrap().charts[0];
|
||||
assert_eq!(after.series.len(), 2, "the hidden column still carries its value series");
|
||||
assert_eq!(
|
||||
(after.series[1].name.as_deref(), after.series[1].categories.as_deref(), after.series[1].values.as_str()),
|
||||
(Some("Data!$C$1"), Some("Data!$A$2:$A$5"), "Data!$C$2:$C$5")
|
||||
);
|
||||
let (wb, _) = read_xlsx(&bytes).unwrap();
|
||||
let ch = &wb.sheet(0).unwrap().charts[0];
|
||||
// Series of one kind are one chart, a column chart with a secondary-axis series.
|
||||
assert_eq!(ch.kind, gridcraft_model::ChartKind::ColumnClustered);
|
||||
assert!(!ch.series[0].secondary);
|
||||
assert!(ch.series[1].secondary);
|
||||
assert_eq!(ch.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]);
|
||||
|
||||
let out = crate::write_xlsx(&wb).unwrap();
|
||||
let (wb2, _) = read_xlsx(&out).unwrap();
|
||||
let ch2 = &wb2.sheet(0).unwrap().charts[0];
|
||||
assert_eq!(ch2.kind, gridcraft_model::ChartKind::ColumnClustered);
|
||||
assert!(!ch2.series[0].secondary);
|
||||
assert!(ch2.series[1].secondary);
|
||||
assert_eq!(ch2.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]);
|
||||
// An explicit false hidden value means visible: the chartEx reader must keep its XML
|
||||
// entry index-aligned with the parsed series, so each series keeps its own name and data.
|
||||
let cleared = cx.replace("hidden=\"1\"", "hidden=\"0\"");
|
||||
let chart = crate::chartex::read_chartex(&crate::xml::parse(cleared.as_bytes()).unwrap()).unwrap();
|
||||
assert_eq!(chart.series.len(), 2, "hidden=\"0\" stays visible, not a second hidden column");
|
||||
// names surface as the cached `<cx:v>` text through the pinned parser; the formulas stay in tx
|
||||
assert_eq!(chart.series[0].name.as_deref(), Some("_xlchart.v1.4"));
|
||||
assert_eq!(chart.series[1].name.as_deref(), Some("_xlchart.v1.5"));
|
||||
assert_eq!(chart.series[1].values, "_xlchart.v1.3");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,939 @@
|
||||
//! Excel's limits as the bound of legitimate input, and the schema as the list of what a shared
|
||||
//! string may hold. A worksheet cell that repeats an address already read is read again, as
|
||||
//! before, and a warning counts the repeats the reader sees (see `read_craft_row`); cells out of
|
||||
//! column order or in another row's element are placed where their addresses say, and counted.
|
||||
//! Cell text and shared-string runs past Excel's length are kept whole, since cutting them would
|
||||
//! lose the user's data at the next save, and warned about. Elements the schema does not know in a
|
||||
//! shared string are tolerated a few times and then dropped, never crowd out an element the schema
|
||||
//! allows, and are named in a warning, since nothing reads them.
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_CELL_CHARS, MAX_COLS, Value, col_to_letters};
|
||||
|
||||
use super::minimal;
|
||||
use crate::read_xlsx;
|
||||
use crate::xml::{MAX_UNLISTED_CHILD_NAMES, MAX_XML_NODES};
|
||||
|
||||
const SST_RELS: &str = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>"#;
|
||||
const A1_IS_SHARED_STRING_0: &str = r#"<sheetData><row r="1"><c r="A1" t="s"><v>0</v></c></row></sheetData>"#;
|
||||
|
||||
fn string_warning(n: u64) -> String {
|
||||
format!(
|
||||
"shared strings: dropped {n} element(s), counting what they held, that a string may not hold (a second phoneticPr, unknown elements, or more elements than a part may hold)"
|
||||
)
|
||||
}
|
||||
fn repeat_warning(n: u64) -> String {
|
||||
format!("sheet \"Data\": {n} cell(s), or a row's properties, repeated an address or row already read; the later ones were read again")
|
||||
}
|
||||
fn elsewhere_warning(n: u64) -> String {
|
||||
format!("sheet \"Data\": {n} cell(s) sat out of column order, or in another row's element, and were placed where their addresses say")
|
||||
}
|
||||
const CUT: &str = "shared strings: 1 string(s) were being read when the part reached its element limit; each lost, whole, the parts that did not fit within that limit";
|
||||
const LONG_TEXT: &str = "sheet \"Data\": 1 cell text(s) longer than Excel's limit of 32767 UTF-16 units were read; they were not cut to that length";
|
||||
fn long_warning(n: u64) -> String {
|
||||
format!("sheet \"Data\": {n} cell text(s) longer than Excel's limit of 32767 UTF-16 units were read; they were not cut to that length")
|
||||
}
|
||||
|
||||
/// One row: `cells` cells from A1 on, then `extra` cells addressed A2, valued 1000, 1001 and on.
|
||||
fn row_of(cells: u32, extra: usize) -> String {
|
||||
let mut body = String::from("<sheetData><row r=\"1\">");
|
||||
for col in 0..cells {
|
||||
body.push_str(&format!("<c r=\"{}1\"><v>{}</v></c>", col_to_letters(col), col + 1));
|
||||
}
|
||||
for n in 0..extra {
|
||||
body.push_str(&format!("<c r=\"A2\"><v>{}</v></c>", 1000 + n));
|
||||
}
|
||||
body.push_str("</row></sheetData>");
|
||||
body
|
||||
}
|
||||
|
||||
fn a1(wb: &gridcraft_model::Workbook) -> Value {
|
||||
wb.sheet(0).unwrap().value(CellRef::parse("A1").unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_element_with_more_cells_than_the_grid_is_wide_is_placed_as_before() {
|
||||
// The full width, read whole with nothing said.
|
||||
let (wb, rep) = read_xlsx(&minimal(&row_of(MAX_COLS, 0), &[], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Number(1.0));
|
||||
assert_eq!(s.value(CellRef::parse("XFD1").unwrap()), Value::Number(MAX_COLS as f64));
|
||||
assert_eq!(s.cells.len(), MAX_COLS as usize);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("dropped") || w.contains("already read") || w.contains("column order")), "{:?}", rep.warnings);
|
||||
// Two cells more, both addressed A2, in row 1's element: each address is inside the grid, so
|
||||
// both are placed, the last one read kept at A2. The first is named for sitting in another
|
||||
// row's element, the second for repeating it.
|
||||
let (wb, rep) = read_xlsx(&minimal(&row_of(MAX_COLS, 2), &[], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
assert_eq!(value(&wb, "A2"), Value::Number(1001.0));
|
||||
assert_eq!(s.value(CellRef::parse("XFD1").unwrap()), Value::Number(MAX_COLS as f64));
|
||||
assert_eq!(s.cells.len(), MAX_COLS as usize + 1);
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(1)), "{:?}", rep.warnings);
|
||||
// Without addresses, cells take the next column: those past column XFD are outside the grid
|
||||
// and dropped by the row reader, with its own warning.
|
||||
let body = format!("<sheetData><row r=\"1\">{}</row></sheetData>", "<c><v>1</v></c>".repeat(MAX_COLS as usize + 2));
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().cells.len(), MAX_COLS as usize);
|
||||
assert!(
|
||||
rep.warnings.iter().any(|w| w == "sheet \"Data\": 2 cells or rows outside the 1,048,576 × 16,384 grid were dropped"),
|
||||
"{:?}",
|
||||
rep.warnings
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared-string table with one string: `unknown` invented elements, then the plain text if
|
||||
/// asked, `runs` one-character rich-text runs, `phonetic` one-character phonetic runs, and `props`
|
||||
/// phonetic properties elements.
|
||||
fn sst_with(unknown: usize, plain: Option<&str>, runs: usize, phonetic: usize, props: usize) -> String {
|
||||
let mut si = String::from("<si>");
|
||||
for i in 0..unknown {
|
||||
si.push_str(&format!("<unknown{i}/>"));
|
||||
}
|
||||
if let Some(t) = plain {
|
||||
si.push_str(&format!("<t>{t}</t>"));
|
||||
}
|
||||
si.push_str(&"<r><t>a</t></r>".repeat(runs));
|
||||
si.push_str(&"<rPh sb=\"0\" eb=\"1\"><t>b</t></rPh>".repeat(phonetic));
|
||||
si.push_str(&"<phoneticPr fontId=\"0\"/>".repeat(props));
|
||||
si.push_str("</si>");
|
||||
format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="1" uniqueCount="1">{si}</sst>"#)
|
||||
}
|
||||
|
||||
fn read_sst(sst: String) -> (gridcraft_model::Workbook, crate::ReadReport) {
|
||||
read_xlsx(&minimal(A1_IS_SHARED_STRING_0, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_keeps_its_runs_whole_past_excels_length_and_drops_only_what_the_schema_forbids() {
|
||||
let most = MAX_CELL_CHARS as usize;
|
||||
// Everything the schema allows, with as many runs as a cell has characters: read whole, no
|
||||
// warning.
|
||||
let (wb, rep) = read_sst(sst_with(0, Some(""), most, most, 1));
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most).into()));
|
||||
assert!(
|
||||
!rep.warnings.iter().any(|w| w.starts_with("shared strings") || w.contains("dropped") || w.contains("longer than Excel's")),
|
||||
"{:?}",
|
||||
rep.warnings
|
||||
);
|
||||
// One run more than Excel's length: kept whole (32,768 characters), with the long-text warning
|
||||
// and no drop.
|
||||
let (wb, rep) = read_sst(sst_with(0, None, most + 1, 0, 0));
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most + 1).into()));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings);
|
||||
// A second phonetic properties element is one more than the schema allows: dropped with the
|
||||
// warning. A second text is text, kept and joined to the first as in an inline string.
|
||||
let two_of_each = r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>first</t><t>second</t><phoneticPr fontId="0"/><phoneticPr fontId="1"/></si></sst>"#;
|
||||
let (wb, rep) = read_sst(two_of_each.to_string());
|
||||
assert_eq!(a1(&wb), Value::Text("firstsecond".into()));
|
||||
assert!(rep.warnings.contains(&string_warning(1)), "{:?}", rep.warnings);
|
||||
// Unknown elements before the text are tolerated a few times and never crowd the text out.
|
||||
let (wb, rep) = read_sst(sst_with(MAX_UNLISTED_CHILD_NAMES, Some("hello"), 0, 0, 1));
|
||||
assert_eq!(a1(&wb), Value::Text("hello".into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings);
|
||||
let (wb, rep) = read_sst(sst_with(1000, Some("hello"), 2, 1, 1));
|
||||
assert_eq!(a1(&wb), Value::Text("helloaa".into()));
|
||||
assert!(rep.warnings.contains(&string_warning(1000 - MAX_UNLISTED_CHILD_NAMES as u64)), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_text_longer_than_excel_allows_is_kept_whole_with_a_warning() {
|
||||
let most = MAX_CELL_CHARS as usize;
|
||||
let plain =
|
||||
|n: usize| format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>{}</t></si></sst>"#, "a".repeat(n));
|
||||
// A shared string of exactly the limit: no warning. One character more: kept whole, warned.
|
||||
let (wb, rep) = read_sst(plain(most));
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most).into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
let (wb, rep) = read_sst(plain(most + 1));
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most + 1).into()));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
// A long shared string in a cell inside another formula's array isn't kept there (the array
|
||||
// fills it), so it isn't counted.
|
||||
let in_array = r#"<sheetData><row r="1"><c r="A1"><f t="array" ref="A1:A2">1</f><v>1</v></c></row><row r="2"><c r="A2" t="s"><v>0</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(in_array, &[("xl/sharedStrings.xml", &plain(most + 1))], SST_RELS, "")).unwrap();
|
||||
assert_eq!(value(&wb, "A2"), Value::Empty);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
// A long shared string no cell uses is not warned about; the cells using
|
||||
// one are counted, each.
|
||||
let two = |cells: &str| {
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>short</t></si><si><t>{}</t></si></sst>"#,
|
||||
"a".repeat(most + 1)
|
||||
);
|
||||
read_xlsx(&minimal(&format!("<sheetData><row r=\"1\">{cells}</row></sheetData>"), &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap()
|
||||
};
|
||||
let (wb, rep) = two(r#"<c r="A1" t="s"><v>0</v></c>"#);
|
||||
assert_eq!(a1(&wb), Value::Text("short".into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
let (_, rep) = two(r#"<c r="A1" t="s"><v>1</v></c><c r="B1" t="s"><v>1</v></c>"#);
|
||||
assert!(rep.warnings.contains(&long_warning(2)), "{:?}", rep.warnings);
|
||||
// Inline strings (in `is`, or in `v`) in the sheet itself: the
|
||||
// same, exactly at the limit and one past it.
|
||||
let in_sheet = |n: usize| {
|
||||
let text = "a".repeat(n);
|
||||
[
|
||||
format!(r#"<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>{text}</t></is></c></row></sheetData>"#),
|
||||
format!(r#"<sheetData><row r="1"><c r="A1" t="inlineStr"><v>{text}</v></c></row></sheetData>"#),
|
||||
]
|
||||
};
|
||||
for body in in_sheet(most + 1) {
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most + 1).into()));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
}
|
||||
for body in in_sheet(most) {
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most).into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
}
|
||||
// A formula's cached result is read as it is, but opening a workbook calculates the formulas
|
||||
// that parse again, so the cached text isn't kept and isn't counted.
|
||||
let formula = format!(r#"<sheetData><row r="1"><c r="A1" t="str"><f>REPT("a",40000)</f><v>{}</v></c></row></sheetData>"#, "a".repeat(most + 1));
|
||||
let (wb, rep) = read_xlsx(&minimal(&formula, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most + 1).into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
// A formula GridCraft can't parse isn't calculated, so its cached text is kept, and it is
|
||||
// counted.
|
||||
let unparsed = format!(r#"<sheetData><row r="1"><c r="A1" t="str"><f>1+</f><v>{}</v></c></row></sheetData>"#, "a".repeat(most + 1));
|
||||
let (wb, rep) = read_xlsx(&minimal(&unparsed, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most + 1).into()));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
// The limit is counted as Excel counts, in UTF-16 units: 16,384 characters outside the Basic
|
||||
// Multilingual Plane are 32,768 units, one over, and 16,383 are within it.
|
||||
let astral =
|
||||
|n: usize| format!(r#"<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>{}</t></is></c></row></sheetData>"#, "\u{1F600}".repeat(n));
|
||||
let (wb, rep) = read_xlsx(&minimal(&astral(most / 2 + 1), &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("\u{1F600}".repeat(most / 2 + 1).into()));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
let (_, rep) = read_xlsx(&minimal(&astral(most / 2), &[], "", "")).unwrap();
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
// At the limit exactly, nothing is said.
|
||||
let body = format!(r#"<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>{}</t></is></c></row></sheetData>"#, "a".repeat(most));
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(most).into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
// A shared string longer than the limit in bytes but not in UTF-16 units: 20,000 `€` are
|
||||
// 60,000 bytes and 20,000 units, so the cell using it is not counted.
|
||||
let (wb, rep) =
|
||||
read_sst(format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>{}</t></si></sst>"#, "€".repeat(20_000)));
|
||||
assert_eq!(a1(&wb), Value::Text("€".repeat(20_000).into()));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_text_is_counted_when_read_even_where_a_later_cell_replaces_it() {
|
||||
// The long-text warning counts the long texts read, as each cell is read: a later cell at the
|
||||
// same address replaces the text but does not take it off the count.
|
||||
let long = "a".repeat(MAX_CELL_CHARS as usize + 1);
|
||||
let long_cell = format!(r#"<c r="A1" t="inlineStr"><is><t>{long}</t></is></c>"#);
|
||||
let plain_cell = r#"<c r="A1"><v>1</v></c>"#;
|
||||
let read = |cells: &str| read_xlsx(&minimal(&format!(r#"<sheetData><row r="1">{cells}</row></sheetData>"#), &[], "", "")).unwrap();
|
||||
// Long, then plain: one long text read, the plain value kept.
|
||||
let (wb, rep) = read(&format!("{long_cell}{plain_cell}"));
|
||||
assert_eq!(a1(&wb), Value::Number(1.0));
|
||||
assert!(rep.warnings.contains(&long_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
// Long, then long: two read. Plain, then long: one.
|
||||
for (cells, n) in [(format!("{long_cell}{long_cell}"), 2), (format!("{plain_cell}{long_cell}"), 1)] {
|
||||
let (wb, rep) = read(&cells);
|
||||
assert_eq!(a1(&wb), Value::Text(long.as_str().into()));
|
||||
assert!(rep.warnings.contains(&long_warning(n)), "{n}: {:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
}
|
||||
// The same through a long shared string, with another cell between the two A1s.
|
||||
let sst = format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>{long}</t></si></sst>"#);
|
||||
let body = r#"<sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1"><v>2</v></c><c r="A1"><v>1</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Number(1.0));
|
||||
assert!(rep.warnings.contains(&long_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twenty_thousand_copies_of_a_cell_using_a_long_shared_string_are_each_counted() {
|
||||
// Twenty thousand copies of A1, each using one shared string, of 32,000 characters (within
|
||||
// Excel's length) and then of one past it: each repeat is counted, and on the long string
|
||||
// each copy read is counted as a long text.
|
||||
let cells = format!(r#"<sheetData><row r="1">{}</row></sheetData>"#, r#"<c r="A1" t="s"><v>0</v></c>"#.repeat(20_000));
|
||||
for (len, long) in [(32_000, 0), (MAX_CELL_CHARS as usize + 1, 20_000)] {
|
||||
let sst = format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>{}</t></si></sst>"#, "a".repeat(len));
|
||||
let (wb, rep) = read_xlsx(&minimal(&cells, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Text("a".repeat(len).into()));
|
||||
assert!(rep.warnings.contains(&repeat_warning(19_999)), "{:?}", rep.warnings);
|
||||
assert_eq!(rep.warnings.contains(&long_warning(long)), long > 0, "{:?}", rep.warnings);
|
||||
assert!(long > 0 || !rep.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", rep.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
fn value(wb: &gridcraft_model::Workbook, at: &str) -> Value {
|
||||
wb.sheet(0).unwrap().value(CellRef::parse(at).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_in_the_same_columns_of_the_next_row_past_the_first_sixty_four_columns_are_not_repeats() {
|
||||
// The columns a row element held are cleared when a row of another number begins, all of
|
||||
// them: CV and XFD lie past the first 64 columns, so row 2's cells there are new, not repeats.
|
||||
let body = r#"<sheetData><row r="1"><c r="CV1"><v>1</v></c><c r="XFD1"><v>2</v></c></row><row r="2"><c r="CV2"><v>3</v></c><c r="XFD2"><v>4</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
for (at, n) in [("CV1", 1.0), ("XFD1", 2.0), ("CV2", 3.0), ("XFD2", 4.0)] {
|
||||
assert_eq!(value(&wb, at), Value::Number(n), "{at}");
|
||||
}
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read") || w.contains("column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrower_element_for_the_same_row_keeps_the_wider_ones_columns_cleared_for_the_next_row() {
|
||||
// A second element for row 1 reaches only column A, after one that reached XFD. The columns
|
||||
// cleared when row 2 begins must still include XFD's, so XFD2 is new, not a repeat.
|
||||
let body = r#"<sheetData><row r="1"><c r="XFD1"><v>1</v></c></row><row r="1"><c r="A1"><v>2</v></c></row><row r="2"><c r="XFD2"><v>3</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
for (at, n) in [("XFD1", 1.0), ("A1", 2.0), ("XFD2", 3.0)] {
|
||||
assert_eq!(value(&wb, at), Value::Number(n), "{at}");
|
||||
}
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read") || w.contains("column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_repeating_an_address_already_read_replaces_it_with_a_warning() {
|
||||
// Excel writes each cell once, in order, in its own row. A cell that repeats an address
|
||||
// is read over what was read there, as before, and is counted, and so are a repeated row's
|
||||
// properties where the first one had some. A cell out of column order, or in
|
||||
// another row's element, lands where its address says, and an unaddressed cell takes the
|
||||
// column after the one before it, in its own row.
|
||||
let body = r#"<sheetData><row r="1" ht="20" customHeight="1"><c r="A1"><v>1</v></c><c r="C1"><v>3</v></c><c r="B1"><v>2</v></c><c r="A1"><v>999</v></c><c r="D7"><v>7</v></c><c><v>8</v></c></row><row r="2"><c r="A2"><v>20</v></c><c r="A1"><v>998</v></c></row><row r="1" ht="30" customHeight="1"><c r="A1"><v>997</v></c><c r="G1"><v>9</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
for (at, n) in [("A1", 997.0), ("B1", 2.0), ("C1", 3.0), ("D7", 7.0), ("E1", 8.0), ("A2", 20.0), ("G1", 9.0)] {
|
||||
assert_eq!(value(&wb, at), Value::Number(n), "{at}");
|
||||
}
|
||||
// Three repeats of A1 and the repeated row 1's height.
|
||||
assert!(rep.warnings.contains(&repeat_warning(4)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(2)), "B1 out of order and D7 in row 1's element are named: {:?}", rep.warnings);
|
||||
let row_one = |body: &str| read_xlsx(&minimal(body, &[], "", "")).unwrap().0.sheet(0).unwrap().rows.get(&0).cloned();
|
||||
let second_height = row_one(r#"<sheetData><row r="1" ht="30" customHeight="1"/></sheetData>"#);
|
||||
assert!(second_height.is_some() && second_height != row_one(r#"<sheetData><row r="1" ht="20" customHeight="1"/></sheetData>"#));
|
||||
assert_eq!(wb.sheet(0).unwrap().rows.get(&0).cloned(), second_height, "the last row 1's height is kept");
|
||||
// Properties a repeated row brings where the first had none replace nothing: kept, silently.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><v>1</v></c></row><row r="1" ht="30" customHeight="1"><c r="B1"><v>2</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().rows.get(&0).cloned(), second_height);
|
||||
assert_eq!(value(&wb, "B1"), Value::Number(2.0));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read") || w.contains("column order")), "{:?}", rep.warnings);
|
||||
// An unaddressed cell after a repeat takes the column after the repeat: B1, left of C1, so
|
||||
// out of column order.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="C1"><v>3</v></c><c r="A1"><v>999</v></c><c><v>8</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), value(&wb, "B1"), value(&wb, "C1")), (Value::Number(999.0), Value::Number(8.0), Value::Number(3.0)));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(1)), "{:?}", rep.warnings);
|
||||
// A full row and then a cell in the next row's element naming A1.
|
||||
let body = row_of(MAX_COLS, 0).replace("</row></sheetData>", r#"</row><row r="2"><c r="A1"><v>999</v></c></row></sheetData>"#);
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Number(999.0));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
// A sparse sheet in order says nothing.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"/><c r="C1"><v>3</v></c></row><row r="3"><c r="B3"><v>1</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(value(&wb, "B3"), Value::Number(1.0));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read") || w.contains("out of column order")), "{:?}", rep.warnings);
|
||||
// A repeat of the furthest cell read, after a cell out of order: the shortcut past the furthest
|
||||
// cell must not miss it.
|
||||
let body =
|
||||
r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="C1"><v>3</v></c><c r="B1"><v>2</v></c><c r="C1"><v>999</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(value(&wb, "C1"), Value::Number(999.0));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(1)), "{:?}", rep.warnings);
|
||||
// A cell naming another row than the one it sits in, repeating nothing: placed where its
|
||||
// address says and named.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="B5"><v>5</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), value(&wb, "B5")), (Value::Number(1.0), Value::Number(5.0)));
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_cell_repeated_in_a_later_element_of_the_same_row_is_a_repeat() {
|
||||
// A blank cell without a style stores nothing; repeated in a second row element for row 1,
|
||||
// right after the first, it is a column that row's elements already held, and the furthest
|
||||
// cell read.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"/></row><row r="1"><c r="A1"/></row></sheetData>"#;
|
||||
let (_, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("out of column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_repeating_a_cell_the_reader_stores_nothing_for_in_the_elements_for_its_row_is_a_repeat() {
|
||||
// A blank cell without a style, and a value inside another formula's array, leave nothing
|
||||
// stored. Repeated in the same row element after a later cell, each is counted as a repeat,
|
||||
// not as a cell out of column order.
|
||||
for body in [
|
||||
r#"<sheetData><row r="1"><c r="A1"/><c r="B1"><v>2</v></c><c r="A1"/></row></sheetData>"#,
|
||||
r#"<sheetData><row r="1"><c r="A1"><f t="array" ref="A1:B1">1+1</f><v>2</v></c><c r="B1"><v>2</v></c><c r="C1"><v>3</v></c><c r="B1"><v>2</v></c></row></sheetData>"#,
|
||||
] {
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(value(&wb, "C1"), if body.contains("C1") { Value::Number(3.0) } else { Value::Empty });
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{body}: {:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{body}: {:?}", rep.warnings);
|
||||
}
|
||||
// In a later element for the same row, right after the first, in column order, it is a repeat
|
||||
// too: the elements for one row in a row share the columns they held.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"/><c r="B1"><v>2</v></c></row><row r="1"><c r="A1"/></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), value(&wb, "B1")), (Value::Empty, Value::Number(2.0)));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{:?}", rep.warnings);
|
||||
// The same for a value inside another formula's array.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><f t="array" ref="A1:B1">1+1</f><v>2</v></c><c r="B1"><v>2</v></c><c r="C1"><v>3</v></c></row><row r="1"><c r="B1"><v>5</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(value(&wb, "C1"), Value::Number(3.0));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{:?}", rep.warnings);
|
||||
// An element for another row between the two copies clears the columns held, so the copy in
|
||||
// the third element, in column order and not the furthest cell read, repeating a cell the
|
||||
// reader stored nothing for, replaces nothing and is not counted, in either warning.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"/><c r="B1"><v>2</v></c></row><row r="2"><c r="A2"><v>3</v></c></row><row r="1"><c r="A1"/></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), value(&wb, "B1"), value(&wb, "A2")), (Value::Empty, Value::Number(2.0), Value::Number(3.0)));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read") || w.contains("column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_cell_left_of_the_rightmost_one_read_in_its_row_element_is_out_of_column_order() {
|
||||
// Each cell is placed where its address says; every one not to the right of the rightmost
|
||||
// cell read before it in its row element is counted.
|
||||
for (body, n) in [
|
||||
(r#"<sheetData><row r="1"><c r="C1"><v>3</v></c><c r="A1"><v>1</v></c><c r="B1"><v>2</v></c></row></sheetData>"#, 2),
|
||||
(r#"<sheetData><row r="1"><c r="D1"><v>4</v></c><c r="B1"><v>2</v></c><c r="A1"><v>1</v></c><c r="C1"><v>3</v></c></row></sheetData>"#, 3),
|
||||
] {
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
for (at, v) in [("A1", 1.0), ("B1", 2.0), ("C1", 3.0)] {
|
||||
assert_eq!(value(&wb, at), Value::Number(v), "{at}");
|
||||
}
|
||||
assert!(rep.warnings.contains(&elsewhere_warning(n)), "{n}: {:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("already read")), "{:?}", rep.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
fn formula(wb: &gridcraft_model::Workbook, at: &str) -> Option<String> {
|
||||
wb.sheet(0).unwrap().cell(CellRef::parse(at).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_cell_keeps_the_last_ones_formula_value_and_style() {
|
||||
let shared = |first: &str, second: &str| {
|
||||
format!(r#"<sheetData><row r="1">{first}{second}</row><row r="2"><c r="A2"><f t="shared" si="0"/><v>1</v></c></row></sheetData>"#)
|
||||
};
|
||||
let plain = r#"<c r="A1"><v>5</v></c>"#;
|
||||
let master = r#"<c r="A1"><f t="shared" ref="A1:A2" si="0">B1+1</f><v>1</v></c>"#;
|
||||
// A plain A1, then a second A1 that is the master of a shared formula A2 uses: both formulas
|
||||
// are live.
|
||||
let (wb, rep) = read_xlsx(&minimal(&shared(plain, master), &[], "", "")).unwrap();
|
||||
assert_eq!((formula(&wb, "A1").as_deref(), formula(&wb, "A2").as_deref()), (Some("B1+1"), Some("B2+1")));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
// The master first, then a plain A1: A1 keeps the plain value, and A2 still gets its formula.
|
||||
let (wb, rep) = read_xlsx(&minimal(&shared(master, plain), &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), formula(&wb, "A1")), (Value::Number(5.0), None));
|
||||
assert_eq!(formula(&wb, "A2").as_deref(), Some("B2+1"));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
// An empty cell with a style is a stored cell; a value after it at its address replaces it,
|
||||
// with the warning, also when another cell came between them.
|
||||
let styles = r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="10" applyNumberFormat="1"/></cellXfs></styleSheet>"#;
|
||||
let style_rels =
|
||||
r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#;
|
||||
let styled = |cells: &str| {
|
||||
read_xlsx(&minimal(&format!(r#"<sheetData><row r="1">{cells}</row></sheetData>"#), &[("xl/styles.xml", styles)], style_rels, "")).unwrap()
|
||||
};
|
||||
let a1_format = |wb: &gridcraft_model::Workbook| {
|
||||
wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).map(|c| wb.styles.get(c.style).num_fmt.as_str().to_owned())
|
||||
};
|
||||
let (wb, _) = styled(r#"<c r="A1" s="1"/>"#);
|
||||
assert_eq!(a1_format(&wb).as_deref(), Some("0.00%"), "an empty styled cell is stored with its style");
|
||||
for cells in [r#"<c r="A1" s="1"/><c r="A1"><v>7</v></c>"#, r#"<c r="A1" s="1"/><c r="B1"><v>2</v></c><c r="A1"><v>7</v></c>"#] {
|
||||
let (wb, rep) = styled(cells);
|
||||
assert_eq!(a1(&wb), Value::Number(7.0), "{cells}");
|
||||
assert_eq!(a1_format(&wb).as_deref(), Some("General"), "{cells}: the last A1 has no style");
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{cells}: {:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{cells}: {:?}", rep.warnings);
|
||||
}
|
||||
// An empty cell without a style isn't stored; a value straight after it at its address is
|
||||
// kept, and counted as a repeat, not as out of order.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"/><c r="A1"><v>7</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(a1(&wb), Value::Number(7.0));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{:?}", rep.warnings);
|
||||
// As many copies of A1 as the grid has columns, then B1: the last A1 and B1 are kept.
|
||||
let body = format!(
|
||||
r#"<sheetData><row r="1">{}<c r="B1"><v>2</v></c></row></sheetData>"#,
|
||||
(0..MAX_COLS).map(|n| format!(r#"<c r="A1"><v>{n}</v></c>"#)).collect::<String>()
|
||||
);
|
||||
let (wb, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
assert_eq!((a1(&wb), value(&wb, "B1")), (Value::Number(f64::from(MAX_COLS - 1)), Value::Number(2.0)));
|
||||
assert!(rep.warnings.contains(&repeat_warning(u64::from(MAX_COLS) - 1)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_number_repeated_after_an_earlier_row_keeps_the_last_rows_cells_and_height() {
|
||||
// Rows 3, 1 and 3 again: row 1 comes after row 3, which is out of order but repeats nothing,
|
||||
// and the second row 3 repeats both a cell and the row's height. The last A3 and the last
|
||||
// height are kept, B3 from the repeat fills an empty address, and only the repeats are
|
||||
// counted. Nothing sits out of column order or in another row's element.
|
||||
let body = r#"<sheetData><row r="3" ht="20" customHeight="1"><c r="A3"><v>1</v></c><c r="C3"><v>3</v></c></row><row r="1"><c r="A1"><v>10</v></c></row><row r="3" ht="30" customHeight="1"><c r="A3"><v>999</v></c><c r="B3"><v>2</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
for (at, n) in [("A3", 999.0), ("B3", 2.0), ("C3", 3.0), ("A1", 10.0)] {
|
||||
assert_eq!(value(&wb, at), Value::Number(n), "{at}");
|
||||
}
|
||||
let third = |body: &str| read_xlsx(&minimal(body, &[], "", "")).unwrap().0.sheet(0).unwrap().rows.get(&2).cloned();
|
||||
let last_height = third(r#"<sheetData><row r="3" ht="30" customHeight="1"/></sheetData>"#);
|
||||
assert!(last_height.is_some() && last_height != third(r#"<sheetData><row r="3" ht="20" customHeight="1"/></sheetData>"#));
|
||||
assert_eq!(wb.sheet(0).unwrap().rows.get(&2).cloned(), last_height, "the last row 3's height is kept");
|
||||
assert!(rep.warnings.contains(&repeat_warning(2)), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("out of column order")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_was_repeated_before_a_part_turned_out_damaged_is_still_said() {
|
||||
// A repeated cell in the first row, then a part that ends inside a comment: the repeat was
|
||||
// read in a row before the damage, and the warning says so beside the "damaged" one.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="A1"><v>999</v></c></row><row r="2"><c r="A2"><v>2</v></c></row><!-- "#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.starts_with("sheet \"Data\" is damaged")), "{:?}", rep.warnings);
|
||||
assert_eq!(a1(&wb), Value::Number(999.0));
|
||||
assert!(rep.warnings.contains(&repeat_warning(1)), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_elements_nothing_reads_are_named() {
|
||||
// The unknown elements a string may hold are kept out of the table by the reader, which
|
||||
// doesn't read them: a warning says so, with the count.
|
||||
let (_, rep) = read_sst(sst_with(2, Some("hello"), 0, 0, 0));
|
||||
assert!(
|
||||
rep.warnings
|
||||
.contains(&"shared strings: 2 element(s) GridCraft does not read (unknown elements) were left out and will not be saved".to_string()),
|
||||
"{:?}",
|
||||
rep.warnings
|
||||
);
|
||||
// A plain string says nothing.
|
||||
let (_, rep) = read_sst(sst_with(0, Some("hello"), 0, 0, 0));
|
||||
assert!(!rep.warnings.iter().any(|w| w.starts_with("shared strings")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_was_dropped_before_a_string_table_turned_out_damaged_is_still_said() {
|
||||
let sst = r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>a</t><phoneticPr fontId="0"/><phoneticPr fontId="1"/></si><!-- "#;
|
||||
let (_, rep) = read_sst(sst.to_string());
|
||||
assert!(rep.warnings.iter().any(|w| w.starts_with("shared strings are damaged")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&string_warning(1)), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_cut_at_the_element_cap_is_said_to_be_cut_and_still_too_long() {
|
||||
// A string of more runs than a part may hold elements keeps what came before the cap; the
|
||||
// warning says it was cut, and the text A1 keeps, still longer than Excel allows, is named in
|
||||
// the long-text warning.
|
||||
let sst =
|
||||
format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si>{}</si></sst>"#, "<r><t>a</t></r>".repeat(600_000));
|
||||
let (wb, rep) = read_sst(sst);
|
||||
let Value::Text(text) = a1(&wb) else { panic!("A1 is text") };
|
||||
// 500,000 runs of two elements each fill the cap of 1,000,000; the run that crosses it is lost.
|
||||
assert_eq!(text.len(), 500_000);
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_cut_at_the_element_cap_keeps_the_text_after_the_part_that_crossed_it() {
|
||||
// The run between "head" and "tail" holds a million elements and crosses the cap: it is
|
||||
// dropped whole with what it holds, the count goes back to where it began, and the run after
|
||||
// it fits again, so the string keeps the text on both sides of it. The warning says so.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>head</t><r><t>middle</t>{}</r><r><t>tail</t></r></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("headtail".into()));
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_run_does_not_join_xstring_escapes_across_the_gap() {
|
||||
// The oversized run is dropped whole. The two retained fragments must not make a CR,
|
||||
// but a complete escape and an escape across adjacent retained runs still decode.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><r><t>_x0009__x00</t></r><r><t>mid<extra>{}</extra>dle</t></r><r><t>0D__x00</t></r><r><t>09_</t></r></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("\t_x000D_\t".into()));
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
let (saved, _) = read_xlsx(&crate::write_xlsx(&wb).unwrap()).unwrap();
|
||||
assert_eq!(a1(&saved), a1(&wb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_lost_part_of_its_text_at_the_element_cap_is_dropped_whole() {
|
||||
// The middle run's text holds a million and one elements: the one that crosses the cap is
|
||||
// dropped, so the `t` holding it, and the run holding that, go whole too ("middle" is not
|
||||
// kept as "midle" or "mid"), counted with what they held: the two past the cap, the 999,999
|
||||
// before them in `extra`, and `extra`, `t` and `r` themselves. The runs on both sides are kept.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>head</t><r><t>mid<extra>{}</extra>dle</t></r><r><t>tail</t></r></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("headtail".into()));
|
||||
assert!(rep.warnings.contains(&string_warning(1_000_004)), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_whose_refused_child_crosses_the_element_cap_is_not_said_to_be_cut() {
|
||||
// A second phoneticPr is one more than a string may hold, and it holds a million elements: it
|
||||
// is dropped whole for its allowance, and nothing the string keeps is lost, so the string is
|
||||
// whole (with its run after it) and its length is what the warning speaks of, not a cut.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>{}</t><phoneticPr fontId="0"/><phoneticPr fontId="1">{}</phoneticPr><r><t>tail</t></r></si></sst>"#,
|
||||
"a".repeat(40_000),
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
let Value::Text(text) = a1(&wb) else { panic!("A1 is text") };
|
||||
assert_eq!(text.len(), 40_004);
|
||||
assert!(text.ends_with("tail"));
|
||||
assert!(rep.warnings.contains(&LONG_TEXT.to_string()), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("reached its element limit")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_that_loses_only_an_unknown_element_at_the_element_cap_is_not_said_to_be_cut() {
|
||||
// The unknown element holds a million elements and crosses the cap: it is dropped whole and
|
||||
// counted, and since the reader reads nothing in it, the string keeps its text on both sides
|
||||
// and is not said to be cut.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>head</t><unknown>{}</unknown><r><t>tail</t></r></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("headtail".into()));
|
||||
assert!(rep.warnings.iter().any(|w| w.starts_with("shared strings: dropped ")), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("reached its element limit")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_that_lost_all_its_text_at_the_element_cap_counts_as_missing() {
|
||||
// The second string's only text holds a million elements and crosses the cap: it is dropped
|
||||
// whole, and the string lost text and kept none. Its cell reads as one naming a string the
|
||||
// table doesn't hold, as on main (empty, with that warning), not as an empty text; the strings
|
||||
// on both sides keep their text at their own indexes.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>alpha</t></si><si><t>beta{}</t></si><si><t>gamma</t></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_000)
|
||||
);
|
||||
let body = r#"<sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="C1" t="s"><v>2</v></c></row></sheetData>"#;
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap();
|
||||
assert_eq!((value(&wb, "A1"), value(&wb, "B1"), value(&wb, "C1")), (Value::Text("alpha".into()), Value::Empty, Value::Text("gamma".into())));
|
||||
assert!(wb.sheet(0).unwrap().cell(CellRef::parse("B1").unwrap()).is_none(), "B1 holds no cell");
|
||||
assert!(rep.warnings.contains(&"some cells refer to missing shared strings".to_string()), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&format!("{CUT}; 1 of them kept no text and count as missing strings")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// The phonetic runs kept for the string in A1, as (start, end, reading).
|
||||
fn a1_runs(wb: &gridcraft_model::Workbook) -> Vec<(u32, u32, String)> {
|
||||
wb.phonetics.iter().flat_map(|p| p.runs.iter().map(|r| (r.start, r.end, r.text.clone()))).collect()
|
||||
}
|
||||
|
||||
/// The cut warning's ending for `n` phonetic runs dropped from strings that lost text.
|
||||
fn unplaced_runs(n: u64) -> String {
|
||||
format!("; {n} phonetic run(s) in strings that lost text were dropped, since their offsets point into the text as it was")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_cut_at_the_element_cap_that_kept_no_text_counts_as_missing_also_with_an_empty_run() {
|
||||
// The middle string keeps an empty run, then loses its text at the cap: it kept no text, so it
|
||||
// counts as missing, as one that kept nothing does. The same string under the cap, an empty
|
||||
// run alone, reads as empty text, as on main.
|
||||
let body = r#"<sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="C1" t="s"><v>2</v></c></row></sheetData>"#;
|
||||
for (middle, cut) in [(format!("<si><r/><t>beta{}</t></si>", "<pad/>".repeat(1_000_000)), true), ("<si><r/></si>".to_string(), false)] {
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>alpha</t></si>{middle}<si><t>gamma</t></si></sst>"#
|
||||
);
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap();
|
||||
let expected = if cut { Value::Empty } else { Value::Text("".into()) };
|
||||
assert_eq!((value(&wb, "A1"), value(&wb, "B1"), value(&wb, "C1")), (Value::Text("alpha".into()), expected, Value::Text("gamma".into())));
|
||||
assert_eq!(wb.sheet(0).unwrap().cell(CellRef::parse("B1").unwrap()).is_none(), cut, "{:?}", rep.warnings);
|
||||
assert_eq!(rep.warnings.contains(&"some cells refer to missing shared strings".to_string()), cut, "{:?}", rep.warnings);
|
||||
let cut_warnings: Vec<&String> = rep.warnings.iter().filter(|w| w.contains("reached its element limit")).collect();
|
||||
let expected_cut = cut.then(|| format!("{CUT}; 1 of them kept no text and count as missing strings"));
|
||||
assert_eq!(cut_warnings, expected_cut.iter().collect::<Vec<_>>(), "{:?}", rep.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_with_empty_text_that_lost_only_a_phonetic_run_stays_empty_text() {
|
||||
// The string's text is empty in the file, and its only phonetic run crosses the cap: no text
|
||||
// was lost, so it reads as empty text, said to be cut, not as a missing string.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t/><rPh sb="0" eb="1"><t>reading</t>{}</rPh></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("".into()));
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("missing shared strings")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_that_lost_text_at_the_element_cap_drops_its_phonetic_runs() {
|
||||
// "middle" crosses the cap and is lost, so the string keeps "headtail". Its phonetic run over
|
||||
// offsets 4 to 8 annotated "midd" and would now land on "tail": it is dropped and counted under
|
||||
// the cut warning with the other run, whose offsets lie past the text, not as runs with bad
|
||||
// offsets, and a save writes no reading. The same run in a string that is not cut is kept.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>head</t><r><t>middle</t>{}</r><r><t>tail</t></r><rPh sb="4" eb="8"><t>ミドル</t></rPh><rPh sb="20" eb="30"><t>ソト</t></rPh></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_001)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("headtail".into()));
|
||||
assert!(a1_runs(&wb).is_empty(), "{:?}", wb.phonetics);
|
||||
assert!(rep.warnings.contains(&format!("{CUT}{}", unplaced_runs(2))), "{:?}", rep.warnings);
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("bad sb/eb")), "{:?}", rep.warnings);
|
||||
let (saved, _) = read_xlsx(&crate::write_xlsx(&wb).unwrap()).unwrap();
|
||||
assert!(a1_runs(&saved).is_empty(), "{:?}", saved.phonetics);
|
||||
let whole = r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>headtail</t><rPh sb="4" eb="8"><t>ミドル</t></rPh></si></sst>"#;
|
||||
let (wb, _) = read_sst(whole.to_string());
|
||||
assert_eq!(a1_runs(&wb), [(4, 8, "ミドル".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_that_lost_only_phonetic_parts_keeps_its_text_and_its_other_runs() {
|
||||
// One string loses its second phonetic run at the cap, another its phonetic properties: no
|
||||
// text was lost, so each keeps its text and its first run, and the cut warning says nothing of
|
||||
// dropped runs.
|
||||
let many = "<pad/>".repeat(1_000_001);
|
||||
let first = r#"<t>headtail</t><rPh sb="0" eb="4"><t>ヘッド</t></rPh>"#;
|
||||
for lost in [format!(r#"<rPh sb="4" eb="8"><t>テイル</t>{many}</rPh>"#), format!(r#"<phoneticPr fontId="1">{many}</phoneticPr>"#)] {
|
||||
let sst = format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si>{first}{lost}</si></sst>"#);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("headtail".into()));
|
||||
assert_eq!(a1_runs(&wb), [(0, 4, "ヘッド".to_string())]);
|
||||
assert!(wb.phonetics.iter().all(|p| p.props.is_none()), "{:?}", wb.phonetics);
|
||||
assert!(rep.warnings.contains(&CUT.to_string()), "{:?}", rep.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_that_lost_text_files_no_phonetic_data_under_its_shortened_text() {
|
||||
// The cut string keeps "head" after "middle" is lost at the cap; its phonetic properties go
|
||||
// with its runs, so nothing is filed under "head" for it, and the intact string with the same
|
||||
// text keeps its reading through a save, in either order, with no conflict between the two.
|
||||
let cut = format!(r#"<si><t>head</t><r><t>middle</t>{}</r><phoneticPr fontId="1"/></si>"#, "<pad/>".repeat(1_000_001));
|
||||
let intact = r#"<si><t>head</t><rPh sb="0" eb="4"><t>ヘッド</t></rPh></si>"#;
|
||||
let body = r#"<sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c></row></sheetData>"#;
|
||||
for (first, second) in [(cut.as_str(), intact), (intact, cut.as_str())] {
|
||||
let sst = format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">{first}{second}</sst>"#);
|
||||
let (wb, rep) = read_xlsx(&minimal(body, &[("xl/sharedStrings.xml", &sst)], SST_RELS, "")).unwrap();
|
||||
assert_eq!((value(&wb, "A1"), value(&wb, "B1")), (Value::Text("head".into()), Value::Text("head".into())));
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("same text")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.contains(&format!("{CUT}; 1 of them dropped their phonetic properties with the text they lost")), "{:?}", rep.warnings);
|
||||
assert_eq!(a1_runs(&wb), [(0, 4, "ヘッド".to_string())]);
|
||||
assert!(wb.phonetics.iter().all(|p| p.props.is_none()), "{:?}", wb.phonetics);
|
||||
let (saved, _) = read_xlsx(&crate::write_xlsx(&wb).unwrap()).unwrap();
|
||||
assert_eq!(a1_runs(&saved), [(0, 4, "ヘッド".to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_phonetic_runs_of_a_string_that_lost_all_its_text_are_counted() {
|
||||
// The string's phonetic runs come before its only text, which crosses the cap: it counts as
|
||||
// missing, and both runs, the damaged one too, are counted as dropped with the cut.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><rPh sb="0" eb="2"><t>ベ</t></rPh><rPh sb="1"/><t>beta{}</t></si></sst>"#,
|
||||
"<pad/>".repeat(1_000_000)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Empty);
|
||||
assert!(rep.warnings.contains(&format!("{CUT}; 1 of them kept no text and count as missing strings{}", unplaced_runs(2))), "{:?}", rep.warnings);
|
||||
assert!(wb.phonetics.is_empty(), "{:?}", wb.phonetics);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_string_at_the_element_cap_and_one_past_it() {
|
||||
// The string holds `head`, a run of `tail` stuffed with fill elements, and a phonetic run: 5
|
||||
// elements besides the fill. With the cap's worth in all, it is whole; with one more, the
|
||||
// phonetic run is the part that goes past the cap (the text is whole, so its other parts are
|
||||
// kept); with three more, the run of `tail` goes, and the phonetic run, kept after it, is
|
||||
// dropped with the text it pointed into.
|
||||
let reading = || vec![(0, 4, "ヘッド".to_string())];
|
||||
for (fill, text, runs, warning) in [
|
||||
(MAX_XML_NODES - 5, "headtail", reading(), None),
|
||||
(MAX_XML_NODES - 4, "headtail", vec![], Some(CUT.to_string())),
|
||||
(MAX_XML_NODES - 2, "head", vec![], Some(format!("{CUT}{}", unplaced_runs(1)))),
|
||||
] {
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>head</t><r><t>tail</t>{}</r><rPh sb="0" eb="4"><t>ヘッド</t></rPh></si></sst>"#,
|
||||
"<pad/>".repeat(fill)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text(text.into()), "{fill}");
|
||||
assert_eq!(a1_runs(&wb), runs, "{fill}");
|
||||
let cut: Vec<&String> = rep.warnings.iter().filter(|w| w.contains("reached its element limit")).collect();
|
||||
assert_eq!(cut, warning.iter().collect::<Vec<_>>(), "{fill}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_that_loses_an_empty_t_at_the_element_cap_is_taken_to_have_lost_text_by_the_by_name_rule() {
|
||||
// The string's text, a phonetic run and empty runs fill the cap exactly, so the empty `t`
|
||||
// after them (schema-valid, holding no character) is dropped at it. Which children a cut
|
||||
// string lost is known by name only, and a lost `t` counts as lost text whatever it held: the
|
||||
// phonetic run is dropped with the cut warning, although "abc" is whole and the run still
|
||||
// points at the right character.
|
||||
let sst = format!(
|
||||
r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>abc</t><rPh sb="0" eb="1"><t>ア</t></rPh>{}<t/></si></sst>"#,
|
||||
"<r/>".repeat(MAX_XML_NODES - 3)
|
||||
);
|
||||
let (wb, rep) = read_sst(sst);
|
||||
assert_eq!(a1(&wb), Value::Text("abc".into()));
|
||||
assert_eq!(a1_runs(&wb), []);
|
||||
assert!(rep.warnings.contains(&format!("{CUT}{}", unplaced_runs(1))), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_formatting_and_unknown_elements_inside_a_run_are_left_out_without_a_warning_as_on_main() {
|
||||
// Only the direct children of a string are counted by name: the run's formatting and an
|
||||
// unknown element inside a run are read with it and not kept, with no warning, as on main,
|
||||
// and a save writes the text alone.
|
||||
let sst = r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><r><rPr><b/></rPr><t>bold</t></r><r><t>x</t><unknown/></r></si></sst>"#;
|
||||
let (wb, rep) = read_sst(sst.to_string());
|
||||
assert_eq!(a1(&wb), Value::Text("boldx".into()));
|
||||
assert!(rep.warnings.iter().all(|w| !w.starts_with("shared strings")), "{:?}", rep.warnings);
|
||||
let saved = crate::write_xlsx(&wb).unwrap();
|
||||
let mut part = String::new();
|
||||
std::io::Read::read_to_string(
|
||||
&mut zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap().by_name("xl/sharedStrings.xml").unwrap(),
|
||||
&mut part,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(part.contains("<si><t>boldx</t></si>"), "{part}");
|
||||
assert!(!part.contains("rPr") && !part.contains("unknown"), "{part}");
|
||||
}
|
||||
|
||||
/// The count a warning made with `warning` reports, whatever it is, or 0 when there is none; the
|
||||
/// warning is found by its text around the count.
|
||||
fn warned_count(warnings: &[String], warning: fn(u64) -> String) -> u64 {
|
||||
const MARKER: u64 = 987_654_321;
|
||||
let template = warning(MARKER);
|
||||
let (before, after) = template.split_once(&MARKER.to_string()).expect("the warning shows its count");
|
||||
let mut found = warnings.iter().filter_map(|w| w.strip_prefix(before)?.strip_suffix(after));
|
||||
let count = found.next().map_or(0, |n| n.parse().unwrap_or_else(|_| panic!("a count in {n:?}")));
|
||||
assert!(found.next().is_none(), "one such warning: {warnings:?}");
|
||||
count
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warned_count_is_read_whatever_its_size() {
|
||||
assert_eq!(warned_count(&[repeat_warning(9)], repeat_warning), 9);
|
||||
assert_eq!(warned_count(&[repeat_warning(1), elsewhere_warning(12_345)], elsewhere_warning), 12_345);
|
||||
assert_eq!(warned_count(&[elsewhere_warning(3)], repeat_warning), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_short_sequence_of_cells_counts_repeats_and_misplaced_cells_as_the_plain_rule_says() {
|
||||
// Every sequence of up to three cells over columns A and B and rows 1 and 2, each a value or
|
||||
// a blank cell (which stores nothing, and removes a stored value), split across one, two or
|
||||
// three row elements, each for row 1 or 2. The counts must equal a plain reading of the rule:
|
||||
// a cell of its element's own row at a column held already by that element, or by the
|
||||
// elements for the same row right before it, repeats it; otherwise a cell not past the
|
||||
// furthest one read repeats it when it is that one or a cell is stored there; a cell that
|
||||
// doesn't repeat is misplaced when it names another row or isn't to the right of the rightmost
|
||||
// cell read in its element.
|
||||
type Cell = (u32, u32, bool);
|
||||
fn reference(elements: &[(u32, Vec<Cell>)]) -> (u64, u64) {
|
||||
let (mut repeated, mut elsewhere) = (0, 0);
|
||||
let mut furthest: Option<(u32, u32)> = None;
|
||||
let mut stored = std::collections::BTreeSet::new();
|
||||
let mut held_cols = std::collections::BTreeSet::new();
|
||||
let mut previous_row = None;
|
||||
for (r, cells) in elements {
|
||||
if previous_row != Some(*r) {
|
||||
held_cols.clear();
|
||||
previous_row = Some(*r);
|
||||
}
|
||||
let mut rightmost: Option<u32> = None;
|
||||
for &(row, col, value) in cells {
|
||||
let pos = (row, col);
|
||||
let past = furthest.is_none_or(|f| pos > f);
|
||||
let held = row == *r && !held_cols.insert(col);
|
||||
if held || !past && (furthest == Some(pos) || stored.contains(&pos)) {
|
||||
repeated += 1;
|
||||
} else if row != *r || rightmost.is_some_and(|m| col <= m) {
|
||||
elsewhere += 1;
|
||||
}
|
||||
if past {
|
||||
furthest = Some(pos);
|
||||
}
|
||||
rightmost = rightmost.max(Some(col));
|
||||
if value {
|
||||
stored.insert(pos);
|
||||
} else {
|
||||
stored.remove(&pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
(repeated, elsewhere)
|
||||
}
|
||||
let options: Vec<Cell> = (1..=2).flat_map(|row| (0..2).flat_map(move |col| [(row, col, true), (row, col, false)])).collect();
|
||||
let mut sequences: Vec<Vec<Cell>> = vec![Vec::new()];
|
||||
let (mut checked, mut repeats_seen, mut uncounted_after_other_row) = (0, 0, 0);
|
||||
for _ in 0..3 {
|
||||
sequences = sequences.iter().flat_map(|s| options.iter().map(move |o| [s.as_slice(), &[*o]].concat())).collect();
|
||||
for cells in &sequences {
|
||||
// Every way to cut the cells into one to three non-empty runs, each with a row number.
|
||||
let n = cells.len();
|
||||
let mut cuts: Vec<Vec<usize>> = vec![vec![]];
|
||||
cuts.extend((1..n).map(|cut| vec![cut]));
|
||||
cuts.extend((1..n).flat_map(|first| (first + 1..n).map(move |second| vec![first, second])));
|
||||
for cut in cuts {
|
||||
let bounds: Vec<usize> = [0].into_iter().chain(cut.iter().copied()).chain([n]).collect();
|
||||
let runs: Vec<&[Cell]> = bounds.windows(2).map(|w| &cells[w[0]..w[1]]).collect();
|
||||
for numbers in 0..(1u32 << runs.len()) {
|
||||
let elements: Vec<(u32, Vec<Cell>)> = runs.iter().enumerate().map(|(i, run)| (1 + ((numbers >> i) & 1), run.to_vec())).collect();
|
||||
let mut body = String::from("<sheetData>");
|
||||
for (r, cells) in &elements {
|
||||
body.push_str(&format!("<row r=\"{r}\">"));
|
||||
for &(row, col, value) in cells {
|
||||
let at = format!("{}{row}", col_to_letters(col));
|
||||
body.push_str(&if value { format!("<c r=\"{at}\"><v>1</v></c>") } else { format!("<c r=\"{at}\"/>") });
|
||||
}
|
||||
body.push_str("</row>");
|
||||
}
|
||||
body.push_str("</sheetData>");
|
||||
let (_, rep) = read_xlsx(&minimal(&body, &[], "", "")).unwrap();
|
||||
let counted = (warned_count(&rep.warnings, repeat_warning), warned_count(&rep.warnings, elsewhere_warning));
|
||||
let expected = reference(&elements);
|
||||
assert_eq!(counted, expected, "{body}: {:?}", rep.warnings);
|
||||
checked += 1;
|
||||
repeats_seen += u64::from(expected.0 > 0);
|
||||
// Row 1, row 2, row 1 with a blank cell of the outer row repeated across: the case
|
||||
// left uncounted.
|
||||
let blank_repeated_across = elements.len() == 3
|
||||
&& elements[0].0 == elements[2].0
|
||||
&& elements[1].0 != elements[0].0
|
||||
&& match (elements[0].1.as_slice(), elements[2].1.as_slice()) {
|
||||
([(row, col, false)], [(last_row, last_col, false)]) => (row, col) == (last_row, last_col) && *row == elements[0].0,
|
||||
_ => false,
|
||||
};
|
||||
if blank_repeated_across && expected == (0, 0) {
|
||||
uncounted_after_other_row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 8 * 2 + 64 * 6 + 512 * 18);
|
||||
assert!(repeats_seen > 1000 && uncounted_after_other_row > 0, "{repeats_seen} {uncounted_after_other_row}");
|
||||
}
|
||||
@@ -133,7 +133,9 @@ fn zip(parts: &[(String, Vec<u8>)]) -> Vec<u8> {
|
||||
|
||||
fn replace(parts: &mut [(String, Vec<u8>)], name: &str, from: &str, to: &str) {
|
||||
let (_, bytes) = parts.iter_mut().find(|(n, _)| n == name).unwrap();
|
||||
let text = std::str::from_utf8(bytes).unwrap().replace(from, to);
|
||||
let text = std::str::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains(from), "{name} holds no {from:?}");
|
||||
let text = text.replace(from, to);
|
||||
*bytes = text.into_bytes();
|
||||
}
|
||||
|
||||
@@ -219,6 +221,83 @@ fn pictures_roundtrip_across_sheets_with_and_without_dynamic_arrays() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_cells_long_fallback_text_is_not_counted() {
|
||||
// A picture in a cell is kept as the picture; its fallback text isn't kept, so a long one
|
||||
// isn't counted in the long-text warning.
|
||||
let mut parts = independent_parts(false);
|
||||
let long = "a".repeat(gridcraft_core::MAX_CELL_CHARS as usize + 1);
|
||||
replace(&mut parts, "sheets/data.xml", r#"t="e" vm="2"><v>#VALUE!</v>"#, &format!(r#"t="inlineStr" vm="2"><is><t>{long}</t></is>"#));
|
||||
let (wb, report) = read_xlsx(&zip(&parts)).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")));
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("longer than Excel's")), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_cell_repeating_a_picture_cell_leaves_the_picture_saved() {
|
||||
// A cell repeating the address of a picture cell replaces the cell's value, but the picture
|
||||
// stays and is what is saved there, as on main. A long text there was read, so it is counted.
|
||||
let long = "a".repeat(gridcraft_core::MAX_CELL_CHARS as usize + 1);
|
||||
for (later, counted) in [(r#"<c r="A1"><v>5</v></c>"#.to_string(), 0), (format!(r#"<c r="A1" t="inlineStr"><is><t>{long}</t></is></c>"#), 1)] {
|
||||
let mut parts = independent_parts(false);
|
||||
let picture_cell = r#"<c r="A1" t="e" vm="2"><v>#VALUE!</v></c>"#;
|
||||
replace(&mut parts, "sheets/data.xml", picture_cell, &format!("{picture_cell}{later}"));
|
||||
let (wb, report) = read_xlsx(&zip(&parts)).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")), "{later}");
|
||||
assert!(report.warnings.iter().any(|w| w.contains("already read")), "{:?}", report.warnings);
|
||||
let long: Vec<&String> = report.warnings.iter().filter(|w| w.contains("longer than Excel's")).collect();
|
||||
assert!(long.len() == counted && long.iter().all(|w| w.contains(": 1 cell text(s) ")), "{:?}", report.warnings);
|
||||
let saved = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap().0;
|
||||
assert!(saved.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")), "{later}");
|
||||
assert_eq!(saved.sheet(0).unwrap().value(at("A1")), Value::Error(CellError::Value), "{later}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_at_a_picture_cells_address_after_its_fallback_was_cleared_is_a_repeat() {
|
||||
// The picture cell A1, then an empty A1 (which clears the cell but leaves the picture), B1,
|
||||
// and A1 again: the picture is still stored at A1, so the last A1 repeats an address already
|
||||
// read, and isn't out of column order. The picture stays and is what is saved.
|
||||
let mut parts = independent_parts(false);
|
||||
let picture_cell = r#"<c r="A1" t="e" vm="2"><v>#VALUE!</v></c>"#;
|
||||
replace(&mut parts, "sheets/data.xml", picture_cell, &format!(r#"{picture_cell}<c r="A1"/>"#));
|
||||
replace(&mut parts, "sheets/data.xml", "</row><row r=\"2\">", r#"<c r="A1"><v>5</v></c></row><row r="2">"#);
|
||||
let (wb, report) = read_xlsx(&zip(&parts)).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")));
|
||||
assert!(
|
||||
report
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|w| w.starts_with("sheet \"Pictures\": 2 cell(s), or a row's properties, repeated an address or row already read")),
|
||||
"{:?}",
|
||||
report.warnings
|
||||
);
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("out of column order")), "{:?}", report.warnings);
|
||||
let saved = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap().0;
|
||||
assert!(saved.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_at_a_picture_cells_address_in_a_later_element_of_the_same_row_is_a_repeat() {
|
||||
// As above, but the last A1 sits in a second row element for row 1, after row 2's, which
|
||||
// cleared the column bitmap, and A1 is not the furthest cell: only the picture stored at A1
|
||||
// finds it.
|
||||
let mut parts = independent_parts(false);
|
||||
let picture_cell = r#"<c r="A1" t="e" vm="2"><v>#VALUE!</v></c>"#;
|
||||
replace(&mut parts, "sheets/data.xml", picture_cell, &format!(r#"{picture_cell}<c r="A1"/>"#));
|
||||
replace(&mut parts, "sheets/data.xml", "</sheetData>", r#"<row r="1"><c r="A1"><v>5</v></c></row></sheetData>"#);
|
||||
let (wb, report) = read_xlsx(&zip(&parts)).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cell_pictures.contains_key(&at("A1")));
|
||||
assert!(
|
||||
report
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|w| w.starts_with("sheet \"Pictures\": 2 cell(s), or a row's properties, repeated an address or row already read")),
|
||||
"{:?}",
|
||||
report.warnings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_picture_references_keep_the_scalar_fallback_with_warnings() {
|
||||
for (part, from, to) in [
|
||||
|
||||
@@ -480,6 +480,7 @@ fn sample() -> Workbook {
|
||||
});
|
||||
s.charts.push(combo);
|
||||
s.charts.push(Chart { kind: ChartKind::Waterfall, legend: LegendPos::None, title: None, ..base_chart.clone() });
|
||||
s.charts.push(Chart { kind: ChartKind::Pareto, ..base_chart.clone() });
|
||||
let mut doughnut = Chart { kind: ChartKind::Doughnut, hole_size: 25, first_slice_angle: 180, legend: LegendPos::Right, ..base_chart.clone() };
|
||||
doughnut.series.push(base_chart.series[0].clone());
|
||||
s.charts.push(doughnut);
|
||||
|
||||
+645
-41
@@ -1,8 +1,9 @@
|
||||
//! A small XML tree built on `quick-xml`, with streaming of repeated elements (worksheet rows,
|
||||
//! shared strings) so large parts never need a full tree, plus escaping helpers for writing.
|
||||
//! A small XML tree built on `quick-xml`, with streaming of repeated elements (shared strings,
|
||||
//! Python scripts) so large parts never need a full tree, plus escaping helpers for writing.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use gridcraft_core::MAX_CELL_CHARS;
|
||||
use gridcraft_model::{PhoneticProps, PhoneticRun, PhoneticString};
|
||||
use quick_xml::Reader;
|
||||
use quick_xml::XmlVersion;
|
||||
@@ -16,7 +17,7 @@ pub const MAX_DEPTH: usize = 256;
|
||||
/// Most elements kept in one part's parsed XML tree: an emptied `El` costs well over a hundred
|
||||
/// bytes, so a highly-compressible part of endless empty elements could fit the package byte
|
||||
/// limit and still take gigabytes of tree before any semantic check ran. Parts whose big runs
|
||||
/// matter (worksheet rows, shared strings) are streamed instead and never hold this tree.
|
||||
/// matter (shared strings, Python scripts) are streamed instead and never hold this tree.
|
||||
pub const MAX_XML_NODES: usize = 1_000_000;
|
||||
|
||||
/// An element: local name (namespace prefix dropped), attributes by local name, children and
|
||||
@@ -27,9 +28,30 @@ pub struct El {
|
||||
pub attrs: Vec<(String, String)>,
|
||||
pub children: Vec<El>,
|
||||
pub text: String,
|
||||
/// Non-zero on a streamed element when the parser dropped something inside it at the element
|
||||
/// cap, other than a direct child of a name the caller doesn't list (nothing the caller reads):
|
||||
/// what it hands over is then not all the part held. An element inside it that lost part of
|
||||
/// what it held is dropped whole, so each child handed over is complete, and the streamed
|
||||
/// element has the bit of that child's name set ([`El::lost`]): bit `i` for the caller's
|
||||
/// listed name at place `i`, counted from 0 (the names at place 31 and on share the last bit).
|
||||
pub cut: u32,
|
||||
/// A shared string lost text immediately before this child.
|
||||
pub text_gap_before: bool,
|
||||
/// A shared string lost text after its last retained child.
|
||||
pub(crate) pending_text_gap: bool,
|
||||
}
|
||||
|
||||
/// The bit in [`El::cut`] of the caller's listed child name at place `i`.
|
||||
fn listed_bit(i: usize) -> u32 {
|
||||
1 << i.min(31)
|
||||
}
|
||||
|
||||
impl El {
|
||||
/// Whether this streamed element lost, at the element cap, a child named `name`, one of the
|
||||
/// `children` it was streamed with ([`Streaming::children`]).
|
||||
pub fn lost(&self, children: &[(&str, usize)], name: &str) -> bool {
|
||||
self.cut != 0 && children.iter().position(|(n, _)| *n == name).is_some_and(|i| self.cut & listed_bit(i) != 0)
|
||||
}
|
||||
pub fn attr(&self, k: &str) -> Option<&str> {
|
||||
self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
|
||||
}
|
||||
@@ -78,7 +100,12 @@ impl El {
|
||||
/// not part of the text). Decodes `_xHHHH_` escapes.
|
||||
pub fn rich_text(e: &El) -> String {
|
||||
let mut s = String::new();
|
||||
let mut decoded: Option<String> = None;
|
||||
for c in &e.children {
|
||||
if c.text_gap_before {
|
||||
decoded.get_or_insert_with(String::new).push_str(&decode_xstring(&s));
|
||||
s.clear();
|
||||
}
|
||||
match c.name.as_str() {
|
||||
"t" => s.push_str(&c.text),
|
||||
"r" => {
|
||||
@@ -89,7 +116,13 @@ pub fn rich_text(e: &El) -> String {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
decode_xstring(&s)
|
||||
match decoded {
|
||||
Some(mut result) => {
|
||||
result.push_str(&decode_xstring(&s));
|
||||
result
|
||||
}
|
||||
None => decode_xstring(&s),
|
||||
}
|
||||
}
|
||||
|
||||
/// The phonetic (furigana) data of a string item: its `<rPh>` runs in document order, and its
|
||||
@@ -206,7 +239,7 @@ fn named_entity(name: &str) -> Option<char> {
|
||||
|
||||
/// Parses a whole part into a tree.
|
||||
pub fn parse(xml: &[u8]) -> Result<El, IoError> {
|
||||
parse_streaming(xml, &[], &mut |_| Ok(()))
|
||||
parse_streaming(xml, Streaming { split: &[], children: &[] }, &mut |_| Ok(())).map(|s| s.root).map_err(|f| f.error)
|
||||
}
|
||||
|
||||
/// The first element named `local_name` (namespace prefix dropped) in `xml`, read from its start tag
|
||||
@@ -232,11 +265,157 @@ pub fn first_start(xml: &[u8], local_name: &str) -> Option<El> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a part; complete elements named in `split` that are children or grandchildren of the
|
||||
/// root (`sst/si`, `worksheet/sheetData/row`) are handed to `cb` and not kept in the returned
|
||||
/// tree. Deeper elements of the same name (the `xdr:row` of a form control's anchor) stay in the
|
||||
/// tree.
|
||||
pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Result<(), IoError>) -> Result<El, IoError> {
|
||||
/// How a part is streamed: complete elements named in `split` that are children or grandchildren of
|
||||
/// the root (`sst/si`, `python/pythonScripts/pythonScript`; see [`is_streamed`]) are handed to the
|
||||
/// callback instead of being kept in the tree, and each of them holds no more direct children of a
|
||||
/// name than `children` allows for it. The caller lists every child the schema allows the element, each with
|
||||
/// its own allowance (`("phoneticPr", 1)`: the one phonetic properties element a shared string may
|
||||
/// carry; `("code", 1)`: the one code a Python script holds), so a name that is not listed is one
|
||||
/// the schema does not know: such a name is admitted once, and no more than
|
||||
/// [`MAX_UNLISTED_CHILD_NAMES`] of them at all. So a crafted part cannot grow one streamed element
|
||||
/// without bound through any name, nor make the counting itself slow, nor use up a listed name's
|
||||
/// allowance with another name (an unknown child whose own descendants fill the element cap can
|
||||
/// still leave no room for what follows it): a child past its allowance is kept out of the tree
|
||||
/// once parsed, with its subtree
|
||||
/// (which holds nothing streamed: streamed elements sit at depth 1 or 2), and counted in
|
||||
/// [`Streamed::dropped`]. What a streamed element holds at any depth is bounded by
|
||||
/// [`MAX_XML_NODES`]: an element that would go past it is dropped and counted the same way, and
|
||||
/// so is each element holding it up to the streamed element's own child, which is lost whole.
|
||||
/// Dropping an element gives what it held back to the count, so the streamed element's later
|
||||
/// children are kept while they fit under the cap, and the rest of the part is still read.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Streaming<'a> {
|
||||
pub split: &'a [&'a str],
|
||||
pub children: &'a [(&'a str, usize)],
|
||||
}
|
||||
|
||||
/// Most distinct child names not listed in [`Streaming::children`] one streamed element may hold.
|
||||
/// Every child the schema allows is listed by its caller, so an unlisted name is one the schema does
|
||||
/// not know (an extension a future schema might add, or an invention); a few are tolerated once
|
||||
/// each, and refusing the rest keeps the per-name count a scan of a handful of entries instead of
|
||||
/// one that grows with every invented name. A listed name is never refused for the names an
|
||||
/// element already holds, only for its own allowance or the element cap.
|
||||
pub const MAX_UNLISTED_CHILD_NAMES: usize = 4;
|
||||
|
||||
/// Whether cell text is longer than Excel's limit of characters per cell ([`MAX_CELL_CHARS`]),
|
||||
/// counted in UTF-16 units (a character outside the Basic Multilingual Plane counts as two). A
|
||||
/// file Excel wrote never is; one that is gets kept whole, since cutting it would lose the user's
|
||||
/// data at the next save, and the caller warns about it.
|
||||
pub fn exceeds_cell_text(text: &str) -> bool {
|
||||
let limit = MAX_CELL_CHARS as usize;
|
||||
// A character takes at least as many UTF-8 bytes as UTF-16 units and at most three bytes per
|
||||
// unit (three bytes are one unit, four bytes two), so only a text between those lengths in
|
||||
// bytes needs counting.
|
||||
if text.len() <= limit {
|
||||
return false;
|
||||
}
|
||||
if text.len() > limit.saturating_mul(3) {
|
||||
return true;
|
||||
}
|
||||
utf16_units(text) > limit
|
||||
}
|
||||
|
||||
/// The number of UTF-16 units in `text`, counted from its bytes: each byte is one unit, except a
|
||||
/// continuation byte (`10xxxxxx`), which adds none, and the first byte of a four-byte character
|
||||
/// (`11110xxx`), the only one taking two units, which adds two. Counting in blocks into
|
||||
/// byte-sized counters (a block is shorter than 256 bytes, so they cannot overflow) lets the
|
||||
/// compiler count many bytes per instruction.
|
||||
#[inline(never)]
|
||||
fn utf16_units(text: &str) -> usize {
|
||||
let (mut continuations, mut four_byte) = (0usize, 0usize);
|
||||
for block in text.as_bytes().chunks(192) {
|
||||
let (mut block_continuations, mut block_four_byte) = (0u8, 0u8);
|
||||
for &byte in block {
|
||||
block_continuations += u8::from(byte & 0xC0 == 0x80);
|
||||
block_four_byte += u8::from(byte >= 0xF0);
|
||||
}
|
||||
continuations = continuations.saturating_add(usize::from(block_continuations));
|
||||
four_byte = four_byte.saturating_add(usize::from(block_four_byte));
|
||||
}
|
||||
text.len().saturating_sub(continuations).saturating_add(four_byte)
|
||||
}
|
||||
|
||||
/// What a streamed parse leaves behind: the tree without the streamed elements, how many
|
||||
/// elements inside streamed elements were dropped, for exceeding [`Streaming::children`] or
|
||||
/// [`MAX_XML_NODES`], and how many children of a name not listed there the streamed elements
|
||||
/// handed out held. The caller turns non-zero counts into import warnings.
|
||||
pub struct Streamed {
|
||||
pub root: El,
|
||||
pub dropped: u64,
|
||||
pub unlisted: u64,
|
||||
}
|
||||
|
||||
/// A streamed parse that failed part-way, with what it had dropped until then, so the caller can
|
||||
/// still say so.
|
||||
#[derive(Debug)]
|
||||
pub struct StreamFailure {
|
||||
pub error: IoError,
|
||||
pub dropped: u64,
|
||||
pub unlisted: u64,
|
||||
}
|
||||
|
||||
/// The parser's counts while it streams a part.
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
// Elements kept in the tree so far, so a pathological part that passes the byte limits can
|
||||
// still be refused before the tree itself outgrows memory. Elements inside a `split` element
|
||||
// are handed out with it and do not stay in the tree, so a shared-string table or Python part
|
||||
// of any size passes: `kept_at_start` remembers, for each open element, the count when it
|
||||
// began and, for a streamed one ([`is_streamed`], tested once, at its start tag), whether its
|
||||
// name counts are open (`Some(true)`) in `child_counts`.
|
||||
kept: usize,
|
||||
kept_at_start: Vec<(usize, Option<bool>)>,
|
||||
// Elements inside streamed elements dropped (for exceeding their name's allowance, or the
|
||||
// element cap), and the counts by name of the open streamed elements that have met a name that
|
||||
// needs one (innermost last): a string of text and runs alone never opens a count list.
|
||||
dropped: u64,
|
||||
child_counts: Vec<Vec<(Slot, usize)>>,
|
||||
// Children of unlisted names the closed streamed elements held, from their counts.
|
||||
unlisted: u64,
|
||||
/// Emptied count lists, reused for the next streamed element instead of allocated per element.
|
||||
spare: Vec<Vec<(Slot, usize)>>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
/// Puts away the name counts of the streamed element that has just closed, for the next one.
|
||||
/// Its unlisted children are added up first: an unlisted name is admitted once, and its entry
|
||||
/// is removed when the child is then dropped at the element cap, so the counts add up to the
|
||||
/// unlisted children the element holds.
|
||||
fn close_streamed(&mut self) {
|
||||
if let Some(mut counts) = self.child_counts.pop() {
|
||||
let held = counts.iter().filter(|(slot, _)| matches!(slot, Slot::Unlisted(_))).map(|(_, n)| *n as u64).sum::<u64>();
|
||||
self.unlisted = self.unlisted.saturating_add(held);
|
||||
counts.clear();
|
||||
self.spare.push(counts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A child name a streamed element has met: one listed in [`Streaming::children`], by its place
|
||||
/// in the list, or one not listed, by name.
|
||||
enum Slot {
|
||||
Listed(usize),
|
||||
Unlisted(String),
|
||||
}
|
||||
|
||||
/// Parses a part, streaming the elements `how` names to `cb`.
|
||||
pub fn parse_streaming(xml: &[u8], how: Streaming<'_>, cb: &mut dyn FnMut(El) -> Result<(), IoError>) -> Result<Streamed, StreamFailure> {
|
||||
let mut tally = Tally::default();
|
||||
match stream(xml, how, cb, &mut tally) {
|
||||
Ok(root) => Ok(Streamed { root, dropped: tally.dropped, unlisted: tally.unlisted }),
|
||||
Err(error) => Err(StreamFailure { error, dropped: tally.dropped, unlisted: tally.unlisted }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an element named `name` with `ancestors` elements above it is one `how` streams: a child or
|
||||
/// grandchild of the root (`sst/si`, `python/pythonScripts/pythonScript`) named in `split`. A deeper
|
||||
/// element of the same name is an ordinary element of the tree.
|
||||
fn is_streamed(how: Streaming<'_>, ancestors: usize, name: &str) -> bool {
|
||||
// Names are compared byte by byte: they are a few bytes long, and this runs for every element.
|
||||
(1..=2).contains(&ancestors) && how.split.iter().any(|s| s.bytes().eq(name.bytes()))
|
||||
}
|
||||
|
||||
fn stream(xml: &[u8], how: Streaming<'_>, cb: &mut dyn FnMut(El) -> Result<(), IoError>, tally: &mut Tally) -> Result<El, IoError> {
|
||||
let data = to_utf8(xml);
|
||||
let mut reader = Reader::from_reader(data.as_ref());
|
||||
{
|
||||
@@ -250,36 +429,96 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
let mut stack: Vec<El> = Vec::new();
|
||||
let mut root: Option<El> = None;
|
||||
let mut buf = Vec::new();
|
||||
// Elements kept in the tree so far, so a pathological part that passes the byte limits can
|
||||
// still be refused before the tree itself outgrows memory. Elements inside a `split` element
|
||||
// are handed out with it and do not stay in the tree, so a streamed worksheet or shared-string
|
||||
// table of any size passes: `kept_at_start` remembers the count when each open element began.
|
||||
let mut kept = 0usize;
|
||||
let mut kept_at_start: Vec<usize> = Vec::new();
|
||||
// Attach a finished element to its parent (or emit it / make it the root).
|
||||
fn finish(
|
||||
stack: &mut [El],
|
||||
root: &mut Option<El>,
|
||||
el: El,
|
||||
split: &[&str],
|
||||
mut el: El,
|
||||
how: Streaming<'_>,
|
||||
cb: &mut dyn FnMut(El) -> Result<(), IoError>,
|
||||
kept: &mut usize,
|
||||
kept_at_start: Option<usize>,
|
||||
tally: &mut Tally,
|
||||
opened: Option<(usize, Option<bool>)>,
|
||||
) -> Result<(), IoError> {
|
||||
let shallow = stack.len() <= 2;
|
||||
let children = how.children;
|
||||
// An element that had a start tag carries what was noted then; an empty one is tested here.
|
||||
let (kept_at_start, streamed) = match opened {
|
||||
Some((k, streamed)) => (Some(k), streamed.is_some()),
|
||||
None => (None, is_streamed(how, stack.len(), &el.name)),
|
||||
};
|
||||
// Dropping an element releases what it held: the count goes back to where it began.
|
||||
let release = |tally: &mut Tally| {
|
||||
if let Some(k) = kept_at_start {
|
||||
tally.kept = k;
|
||||
}
|
||||
};
|
||||
// A dropped element is counted with everything it held, and releases it.
|
||||
let drop_whole = |tally: &mut Tally| {
|
||||
let held = kept_at_start.map_or(0, |k| tally.kept.saturating_sub(k));
|
||||
tally.dropped = tally.dropped.saturating_add(1).saturating_add(held as u64);
|
||||
release(tally);
|
||||
};
|
||||
match stack.last_mut() {
|
||||
Some(parent) => {
|
||||
if shallow && split.contains(&el.name.as_str()) {
|
||||
// A direct child of the streamed element, counted against its name's allowance, and
|
||||
// its name's place in the caller's list, looked up once (byte by byte, as in
|
||||
// `is_streamed`).
|
||||
let direct = tally.kept_at_start.last().is_some_and(|&(_, counted)| counted.is_some());
|
||||
let listed = if direct && !streamed { children.iter().position(|(n, _)| n.bytes().eq(el.name.bytes())) } else { None };
|
||||
if streamed {
|
||||
cb(el)?;
|
||||
// The element and everything parsed inside it have left the tree.
|
||||
if let Some(k) = kept_at_start {
|
||||
*kept = k;
|
||||
}
|
||||
} else {
|
||||
*kept = kept.saturating_add(1);
|
||||
if *kept > MAX_XML_NODES {
|
||||
release(tally);
|
||||
} else if direct && !admit(tally, children, listed, &el.name) {
|
||||
// The streamed element already holds all a legitimate one can of this name:
|
||||
// the child is dropped with its subtree (which holds nothing streamed), all of
|
||||
// it counted.
|
||||
drop_whole(tally);
|
||||
} else if (tally.kept >= MAX_XML_NODES || el.cut != 0)
|
||||
&& let Some(&(began, _)) = tally.kept_at_start.iter().take(3).rev().find(|(_, streamed)| streamed.is_some())
|
||||
{
|
||||
// Inside a streamed element (they sit at depth 1 or 2). If the cap was already
|
||||
// reached before the innermost open one (the one this element sits in) began,
|
||||
// nothing in it can be kept, so the part is refused, as one that streams nothing is.
|
||||
if began >= MAX_XML_NODES {
|
||||
return Err(IoError::Xml(format!("the part holds more than {MAX_XML_NODES} elements")));
|
||||
}
|
||||
// Inside a streamed element that has filled the element cap, or an element that
|
||||
// lost part of what it held to the cap: this element is dropped with what it
|
||||
// holds, all of it counted, and the rest of the part is still read. Its parent
|
||||
// is marked, so whatever held it goes whole too, up to the streamed element,
|
||||
// which is handed out marked as cut, with the bit of its own child's name set.
|
||||
drop_whole(tally);
|
||||
// Read again: admitting this child may have just opened the parent's counts.
|
||||
if tally.kept_at_start.last().is_some_and(|&(_, counted)| counted == Some(true))
|
||||
&& let Some(counts) = tally.child_counts.last_mut()
|
||||
&& let Some(count) = slot_count(counts, listed, &el.name)
|
||||
{
|
||||
// Dropped at the cap, not for its allowance: the slot it took is free again,
|
||||
// and an unlisted name left holding no child gives back its place among the
|
||||
// names the element may hold.
|
||||
*count = count.saturating_sub(1);
|
||||
if listed.is_none() {
|
||||
counts.retain(|(slot, n)| *n > 0 || matches!(slot, Slot::Listed(_)));
|
||||
}
|
||||
}
|
||||
// Preserve a boundary when a shared string loses text at the cap.
|
||||
// The next retained child carries it; consecutive losses need one boundary.
|
||||
if direct && parent.name == "si" && listed.is_some() && matches!(el.name.as_str(), "t" | "r") {
|
||||
parent.pending_text_gap = true;
|
||||
}
|
||||
// A direct child of a name the caller doesn't list is nothing it reads: losing
|
||||
// it doesn't cut the streamed element. A listed one marks its name's bit there.
|
||||
parent.cut |= match (direct, listed) {
|
||||
(false, _) => 1,
|
||||
(true, Some(i)) => listed_bit(i),
|
||||
(true, None) => 0,
|
||||
};
|
||||
} else {
|
||||
tally.kept = tally.kept.saturating_add(1);
|
||||
if tally.kept > MAX_XML_NODES {
|
||||
return Err(IoError::Xml(format!("the part holds more than {MAX_XML_NODES} elements")));
|
||||
}
|
||||
el.text_gap_before = std::mem::take(&mut parent.pending_text_gap);
|
||||
parent.children.push(el);
|
||||
}
|
||||
}
|
||||
@@ -291,6 +530,53 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// Counts one more child of `name` (`listed`: its place in the caller's list) for its parent,
|
||||
// the innermost open streamed element; `false` when the element already holds all the
|
||||
// allowance for that name (one, for a name not listed), or already holds as many unlisted
|
||||
// names as a legitimate element can.
|
||||
fn admit(tally: &mut Tally, children: &[(&str, usize)], listed: Option<usize>, name: &str) -> bool {
|
||||
let allowance = listed.and_then(|i| children.get(i)).map_or(1, |(_, a)| *a);
|
||||
// A name without a limit is never refused, so it needs no count.
|
||||
if allowance == usize::MAX {
|
||||
return true;
|
||||
}
|
||||
// The first child that needs a count opens the element's count list.
|
||||
let Some((_, Some(counted))) = tally.kept_at_start.last_mut() else { return true };
|
||||
if !*counted {
|
||||
*counted = true;
|
||||
let counts = tally.spare.pop().unwrap_or_default();
|
||||
tally.child_counts.push(counts);
|
||||
}
|
||||
let Some(counts) = tally.child_counts.last_mut() else { return true };
|
||||
if let Some(count) = slot_count(counts, listed, name) {
|
||||
if *count >= allowance {
|
||||
return false;
|
||||
}
|
||||
*count += 1;
|
||||
return true;
|
||||
}
|
||||
// A name this element has not seen yet: a listed one gets its entry (unless its allowance
|
||||
// is zero); an unlisted one only while the element has room for another unknown name.
|
||||
let unlisted_names = counts.iter().filter(|(slot, _)| matches!(slot, Slot::Unlisted(_))).count();
|
||||
if allowance == 0 || (listed.is_none() && unlisted_names >= MAX_UNLISTED_CHILD_NAMES) {
|
||||
return false;
|
||||
}
|
||||
let slot = match listed {
|
||||
Some(i) => Slot::Listed(i),
|
||||
None => Slot::Unlisted(name.to_string()),
|
||||
};
|
||||
counts.push((slot, 1));
|
||||
true
|
||||
}
|
||||
// The count of the slot `name` takes (`listed`: its place in the caller's list), if it has one.
|
||||
fn slot_count<'a>(counts: &'a mut [(Slot, usize)], listed: Option<usize>, name: &str) -> Option<&'a mut usize> {
|
||||
let (_, count) = counts.iter_mut().find(|(slot, _)| match (slot, listed) {
|
||||
(Slot::Listed(i), Some(j)) => *i == j,
|
||||
(Slot::Unlisted(n), None) => n == name,
|
||||
_ => false,
|
||||
})?;
|
||||
Some(count)
|
||||
}
|
||||
loop {
|
||||
let ev = reader.read_event_into(&mut buf).map_err(|e| IoError::Xml(format!("{e} at byte {}", reader.buffer_position())))?;
|
||||
match ev {
|
||||
@@ -298,17 +584,22 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
if stack.len() >= MAX_DEPTH {
|
||||
return Err(IoError::Xml("XML nested too deeply".into()));
|
||||
}
|
||||
stack.push(start_el(&e));
|
||||
kept_at_start.push(kept);
|
||||
let el = start_el(&e);
|
||||
let streamed = is_streamed(how, stack.len(), &el.name).then_some(false);
|
||||
stack.push(el);
|
||||
tally.kept_at_start.push((tally.kept, streamed));
|
||||
}
|
||||
Event::Empty(e) => {
|
||||
let el = start_el(&e);
|
||||
finish(&mut stack, &mut root, el, split, cb, &mut kept, None)?;
|
||||
finish(&mut stack, &mut root, el, how, cb, tally, None)?;
|
||||
}
|
||||
Event::End(_) => {
|
||||
if let Some(el) = stack.pop() {
|
||||
let at_start = kept_at_start.pop();
|
||||
finish(&mut stack, &mut root, el, split, cb, &mut kept, at_start)?;
|
||||
let opened = tally.kept_at_start.pop();
|
||||
if let Some((_, Some(true))) = opened {
|
||||
tally.close_streamed();
|
||||
}
|
||||
finish(&mut stack, &mut root, el, how, cb, tally, opened)?;
|
||||
}
|
||||
}
|
||||
Event::Text(t) => {
|
||||
@@ -347,8 +638,11 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
}
|
||||
// Unclosed elements (truncated part): close them so we keep what we have.
|
||||
while let Some(el) = stack.pop() {
|
||||
let at_start = kept_at_start.pop();
|
||||
finish(&mut stack, &mut root, el, split, cb, &mut kept, at_start)?;
|
||||
let opened = tally.kept_at_start.pop();
|
||||
if let Some((_, Some(true))) = opened {
|
||||
tally.close_streamed();
|
||||
}
|
||||
finish(&mut stack, &mut root, el, how, cb, tally, opened)?;
|
||||
}
|
||||
root.ok_or_else(|| IoError::Xml("no root element".into()))
|
||||
}
|
||||
@@ -480,6 +774,64 @@ pub fn push_num(o: &mut String, n: f64) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cell_text_limit_counts_utf16_units_not_bytes() {
|
||||
let limit = MAX_CELL_CHARS as usize;
|
||||
// Three bytes and one UTF-16 unit each: past the limit in bytes, well within it in units.
|
||||
let euros = "€".repeat(20_000);
|
||||
assert!(!exceeds_cell_text(&euros), "20,000 euro signs are 20,000 units");
|
||||
let accents = "é".repeat(limit + 1);
|
||||
assert!(exceeds_cell_text(&accents), "32,768 two-byte characters exceed");
|
||||
let more_euros = "€".repeat(limit + 1);
|
||||
assert!(exceeds_cell_text(&more_euros), "32,768 three-byte characters exceed");
|
||||
// Four bytes and two UTF-16 units each.
|
||||
let emoji = "😀".repeat(16_384);
|
||||
assert!(exceeds_cell_text(&emoji), "16,384 emoji are 32,768 units");
|
||||
let emoji_and_letter = format!("{}x", "😀".repeat(16_383));
|
||||
assert!(!exceeds_cell_text(&emoji_and_letter), "16,383 emoji and a letter are 32,767 units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_text_limit_matches_utf16_count_at_the_boundaries() {
|
||||
let limit = MAX_CELL_CHARS as usize;
|
||||
let chars = ["a", "é", "€", "😀"];
|
||||
let mut checked = 0;
|
||||
for body in chars {
|
||||
for tail in chars {
|
||||
let (body_units, tail_units) = (body.encode_utf16().count(), tail.encode_utf16().count());
|
||||
// Texts of `body` characters then up to three `tail` ones, whose units land on
|
||||
// the limit, one either side of it and near the byte bounds.
|
||||
for tails in 0..4 {
|
||||
let tail_total = tails * tail_units;
|
||||
for target in [limit - 1, limit, limit + 1, limit + 2] {
|
||||
let Some(rest) = target.checked_sub(tail_total) else { continue };
|
||||
let count = rest / body_units;
|
||||
for n in [count.saturating_sub(1), count, count + 1] {
|
||||
let text = format!("{}{}", body.repeat(n), tail.repeat(tails));
|
||||
let expected = text.encode_utf16().count() > limit;
|
||||
assert_eq!(exceeds_cell_text(&text), expected, "{n} of {body:?} then {tails} of {tail:?}");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The byte bounds themselves: exactly at the limit in bytes, and three bytes per unit.
|
||||
for text in [
|
||||
"a".repeat(limit),
|
||||
"a".repeat(limit + 1),
|
||||
"€".repeat(limit),
|
||||
format!("{}a", "€".repeat(limit)),
|
||||
format!("{}é", "€".repeat(limit - 1)),
|
||||
format!("{}😀", "€".repeat(limit - 1)),
|
||||
String::new(),
|
||||
] {
|
||||
assert_eq!(exceeds_cell_text(&text), text.encode_utf16().count() > limit);
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked > 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn si_without_phonetics_is_written_exactly_as_before() {
|
||||
for s in ["plain", " leading ", "a & <b>", "line\nbreak", "日本語", "x_x0041_"] {
|
||||
@@ -489,24 +841,164 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_streamed_part_may_hold_more_elements_than_the_cap() {
|
||||
// A worksheet of ordinary size: 5001 rows of 100 cells is 1,000,200 `c` and `v` elements,
|
||||
// more than the cap, but the rows are streamed out one by one and never pile up in the
|
||||
// 5001 streamed elements of 100 children each is 1,000,200 `c` and `v` elements, more than
|
||||
// the cap, but the streamed elements are handed out one by one and never pile up in the
|
||||
// tree, so the part is read whole. Kept in a tree (no split), the same part is refused.
|
||||
let row = format!("<row>{}</row>", "<c><v>1</v></c>".repeat(100));
|
||||
let xml = format!("<sheetData>{}</sheetData>", row.repeat(5001));
|
||||
let mut rows = 0usize;
|
||||
let root = parse_streaming(xml.as_bytes(), &["row"], &mut |r| {
|
||||
let streamed = parse_streaming(xml.as_bytes(), Streaming { split: &["row"], children: &[("c", usize::MAX)] }, &mut |r| {
|
||||
assert_eq!(r.children.len(), 100);
|
||||
rows += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(rows, 5001);
|
||||
assert!(root.children.is_empty());
|
||||
assert!(streamed.root.children.is_empty());
|
||||
assert_eq!(streamed.dropped, 0);
|
||||
let err = parse(xml.as_bytes()).unwrap_err();
|
||||
assert!(err.to_string().contains("elements"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_streamed_element_keeps_exactly_its_limit_of_children_and_drops_the_rest() {
|
||||
// Exactly the limit: nothing dropped, every child kept. One more: the extra child is
|
||||
// dropped and counted, the element keeps exactly the limit, and the parse goes on with the
|
||||
// next streamed element untouched.
|
||||
let how = Streaming { split: &["row"], children: &[("c", 3)] };
|
||||
let full = b"<sheetData><row><c>1</c><c>2</c><c>3</c></row><row><c>4</c></row></sheetData>";
|
||||
let mut seen = Vec::new();
|
||||
let s = parse_streaming(full, how, &mut |r| {
|
||||
seen.push(r.children.iter().map(|c| c.text.clone()).collect::<Vec<_>>());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(seen, [vec!["1", "2", "3"], vec!["4"]]);
|
||||
assert_eq!(s.dropped, 0);
|
||||
let over = b"<sheetData><row><c>1</c><c>2</c><c>3</c><c>4</c></row><row><c>5</c><c>6</c><c>7</c><c>8</c><c>9</c></row></sheetData>";
|
||||
let mut seen = Vec::new();
|
||||
let s = parse_streaming(over, how, &mut |r| {
|
||||
seen.push(r.children.iter().map(|c| c.text.clone()).collect::<Vec<_>>());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(seen, [vec!["1", "2", "3"], vec!["5", "6", "7"]]);
|
||||
assert_eq!(s.dropped, 3);
|
||||
// The limit is on the streamed element's own children, by name: deeper nesting is not
|
||||
// counted, elements outside the streamed ones are not limited at all, and a name not
|
||||
// listed is allowed once (the second `extLst` is dropped).
|
||||
let deep = b"<sheetData><cols><col/><col/><col/><col/><col/></cols><row><c><f/><v/><is/><other/></c><extLst/><extLst/></row></sheetData>";
|
||||
let mut names = Vec::new();
|
||||
let s = parse_streaming(deep, how, &mut |r| {
|
||||
names = r.children.iter().map(|c| c.name.clone()).collect();
|
||||
assert_eq!(r.children[0].children.len(), 4);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(names, ["c", "extLst"]);
|
||||
assert_eq!(s.dropped, 1);
|
||||
assert_eq!(s.root.child("cols").map(|c| c.children.len()), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_streamed_element_holds_only_a_handful_of_unlisted_child_names() {
|
||||
// Four invented names are admitted once each; the fifth and every later one is dropped
|
||||
// and counted. The listed name is still admitted up to its own allowance after a
|
||||
// thousand invented ones.
|
||||
let mut row = String::from("<row>");
|
||||
for i in 0..1000 {
|
||||
row.push_str(&format!("<unknown{i}/>"));
|
||||
}
|
||||
row.push_str("<c/><c/><c/><c/></row>");
|
||||
let xml = format!("<sheetData>{row}{row}</sheetData>");
|
||||
let mut kept = Vec::new();
|
||||
let s = parse_streaming(xml.as_bytes(), Streaming { split: &["row"], children: &[("c", 3)] }, &mut |r| {
|
||||
kept.push(r.children.iter().map(|c| c.name.clone()).collect::<Vec<String>>());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut expected: Vec<String> = (0..MAX_UNLISTED_CHILD_NAMES).map(|i| format!("unknown{i}")).collect();
|
||||
expected.extend(["c", "c", "c"].map(String::from));
|
||||
assert_eq!(kept, [expected.clone(), expected]);
|
||||
assert_eq!(s.dropped, 2 * ((1000 - MAX_UNLISTED_CHILD_NAMES as u64) + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unlisted_name_dropped_at_the_element_cap_frees_its_place_among_the_names() {
|
||||
// Four invented names each hold the element cap's worth of elements and are dropped at it,
|
||||
// whole: the first row holds none of them, so a fifth invented name after them is admitted
|
||||
// and counted as an unlisted child. A row that keeps four invented names still refuses a
|
||||
// fifth.
|
||||
let many = "<pad/>".repeat(MAX_XML_NODES);
|
||||
let crossing: String = (0..MAX_UNLISTED_CHILD_NAMES).map(|i| format!("<crossing{i}>{many}</crossing{i}>")).collect();
|
||||
let four: String = (0..MAX_UNLISTED_CHILD_NAMES).map(|i| format!("<kept{i}/>")).collect();
|
||||
let xml = format!("<sheetData><row><c/>{crossing}<fifth/></row><row>{four}<fifth/></row></sheetData>");
|
||||
let mut kept = Vec::new();
|
||||
let s = parse_streaming(xml.as_bytes(), Streaming { split: &["row"], children: &[("c", 1)] }, &mut |r| {
|
||||
kept.push(r.children.iter().map(|c| c.name.clone()).collect::<Vec<String>>());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let second: Vec<String> = (0..MAX_UNLISTED_CHILD_NAMES).map(|i| format!("kept{i}")).collect();
|
||||
assert_eq!(kept, [vec!["c".to_string(), "fifth".to_string()], second]);
|
||||
assert_eq!(s.unlisted, 1 + MAX_UNLISTED_CHILD_NAMES as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_children_do_not_count_against_the_element_cap() {
|
||||
// One streamed element stuffed with more `c` children than the element cap, each with a `v`
|
||||
// inside: the excess is dropped as it is parsed, counted with what it holds, and the elements
|
||||
// counted while each dropped child was open are counted back out, so the element keeps the
|
||||
// ten its allowance lets through, and the `tail` after them, instead of reaching the cap and
|
||||
// dropping it.
|
||||
let xml = format!("<sheetData><row>{}<tail/></row></sheetData>", "<c><v>1</v></c>".repeat(MAX_XML_NODES + 1));
|
||||
let mut rows = 0;
|
||||
let s = parse_streaming(xml.as_bytes(), Streaming { split: &["row"], children: &[("c", 10), ("tail", 1)] }, &mut |r| {
|
||||
assert_eq!(r.children.len(), 11);
|
||||
assert_eq!(r.cut, 0);
|
||||
rows += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
assert_eq!(s.dropped, 2 * (MAX_XML_NODES as u64 + 1 - 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_limited_child_lost_at_the_cap_frees_its_place_for_a_later_one() {
|
||||
// The first `code` is the first child that needs a count, and it crosses the cap: it is
|
||||
// dropped and gives its place back, so the second `code` is kept.
|
||||
let xml = format!("<scripts><script><code>{}</code><code>kept</code></script></scripts>", "<pad/>".repeat(MAX_XML_NODES));
|
||||
let mut kept = Vec::new();
|
||||
parse_streaming(xml.as_bytes(), Streaming { split: &["script"], children: &[("code", 1)] }, &mut |s| {
|
||||
kept = s.children.iter().map(|c| c.text.clone()).collect();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(kept, ["kept"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_streamed_element_says_which_listed_children_it_lost_at_the_element_cap() {
|
||||
// Each string loses one part at the cap: a run whose `t` holds the crossing element (lost
|
||||
// through what it held), a phonetic run that crosses it directly, an unlisted child (which
|
||||
// cuts nothing), and nothing at all. The names it lost are the ones `lost` reports.
|
||||
let many = "<pad/>".repeat(MAX_XML_NODES);
|
||||
let how = Streaming { split: &["si"], children: &[("t", usize::MAX), ("phoneticPr", 1), ("r", usize::MAX), ("rPh", usize::MAX)] };
|
||||
let xml = format!(
|
||||
"<sst><si><t>a</t><r><t>{many}</t></r></si><si><t>a</t><rPh>{many}</rPh></si><si><t>a</t><extra>{many}</extra></si><si><t>a</t></si></sst>"
|
||||
);
|
||||
let mut seen = Vec::new();
|
||||
parse_streaming(xml.as_bytes(), how, &mut |si| {
|
||||
let lost: Vec<&str> = how.children.iter().map(|(name, _)| *name).filter(|name| si.lost(how.children, name)).collect();
|
||||
seen.push((si.cut != 0, lost.join(",")));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let expected = [(true, "r"), (true, "rPh"), (false, ""), (false, "")];
|
||||
assert_eq!(seen, expected.map(|(cut, lost)| (cut, lost.to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_of_endless_empty_elements_is_refused() {
|
||||
assert!(parse(b"<r><x/><y t=\"1\"/><x/></r>").is_ok());
|
||||
@@ -515,6 +1007,83 @@ mod tests {
|
||||
assert!(err.to_string().contains("elements"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elements_past_the_cap_after_a_streamed_element_are_refused() {
|
||||
// A streamed element's count list closes at its end tag, so elements past the cap outside
|
||||
// any streamed element are refused, as in a part that streams nothing, not dropped.
|
||||
let xml = format!("<sst><si><t>a</t></si>{}</sst>", "<pad/>".repeat(MAX_XML_NODES + 1));
|
||||
let mut strings = 0;
|
||||
let parsed = parse_streaming(xml.as_bytes(), Streaming { split: &["si"], children: &[("t", 1)] }, &mut |_| {
|
||||
strings += 1;
|
||||
Ok(())
|
||||
});
|
||||
let Err(failure) = parsed else { panic!("a part past the element cap is refused") };
|
||||
assert!(failure.error.to_string().contains("elements"), "{}", failure.error);
|
||||
assert_eq!(strings, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_whose_cap_is_filled_before_its_streamed_elements_is_refused() {
|
||||
// The tree outside the strings already holds the cap when the first string begins: its
|
||||
// text can't be kept, so the part is refused, as one that streams nothing is, instead of
|
||||
// handing out strings that each lost their text. An empty string loses nothing and passes,
|
||||
// as on main: the cap bounds the elements the parser holds, and an empty streamed element
|
||||
// holds none.
|
||||
let filler = "<pad/>".repeat(MAX_XML_NODES);
|
||||
let how = Streaming { split: &["si"], children: &[("t", usize::MAX)] };
|
||||
let mut strings = 0;
|
||||
let xml = format!("<sst>{filler}<si/><si><t>alpha</t></si><si><t>beta</t></si></sst>");
|
||||
let parsed = parse_streaming(xml.as_bytes(), how, &mut |_| {
|
||||
strings += 1;
|
||||
Ok(())
|
||||
});
|
||||
let Err(failure) = parsed else { panic!("a part whose cap is filled outside its strings is refused") };
|
||||
assert!(failure.error.to_string().contains("elements"), "{}", failure.error);
|
||||
assert_eq!(strings, 1, "only the empty string is handed out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_that_hold_no_element_are_handed_out_with_the_cap_full_as_on_main() {
|
||||
// With the tree outside the strings at the cap, or one under it, a string holding no
|
||||
// element (self-closing, open and closed, or whitespace only) is handed out with nothing
|
||||
// in it, and so is each of three in a row: the cap bounds the elements the parser holds,
|
||||
// and such a string holds none. One under the cap, a string's text still fits.
|
||||
let how = Streaming { split: &["si"], children: &[("t", usize::MAX)] };
|
||||
for (fill, strings, expected) in [
|
||||
(MAX_XML_NODES, "<si></si>", vec![""]),
|
||||
(MAX_XML_NODES, "<si> </si>", vec![""]),
|
||||
(MAX_XML_NODES - 1, "<si/><si><t>alpha</t></si>", vec!["", "alpha"]),
|
||||
(MAX_XML_NODES, "<si/><si></si><si/>", vec!["", "", ""]),
|
||||
] {
|
||||
let xml = format!("<sst>{}{strings}</sst>", "<pad/>".repeat(fill));
|
||||
let mut seen = Vec::new();
|
||||
parse_streaming(xml.as_bytes(), how, &mut |si| {
|
||||
assert_eq!(si.cut, 0, "{strings}");
|
||||
seen.push(rich_text(&si));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|f| panic!("{strings} at {fill}: {}", f.error));
|
||||
assert_eq!(seen, expected, "{strings} at {fill}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_streamed_element_that_begins_inside_another_with_the_cap_full_is_refused() {
|
||||
// The outer string's runs fill the cap, and the string inside it begins with the cap
|
||||
// already full: its text can't be kept, so the part is refused, as on main, instead of
|
||||
// handing out an inner string that lost its text.
|
||||
let xml = format!("<sst><si>{}<si><t>inner</t></si></si></sst>", "<r/>".repeat(MAX_XML_NODES));
|
||||
let how = Streaming { split: &["si"], children: &[("t", usize::MAX), ("r", usize::MAX)] };
|
||||
let mut strings = 0;
|
||||
let parsed = parse_streaming(xml.as_bytes(), how, &mut |_| {
|
||||
strings += 1;
|
||||
Ok(())
|
||||
});
|
||||
let Err(failure) = parsed else { panic!("a part whose cap is filled before an inner string begins is refused") };
|
||||
assert!(failure.error.to_string().contains("elements"), "{}", failure.error);
|
||||
assert_eq!(strings, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phonetic_data_validates_offsets() {
|
||||
let x = r#"<si><t>課きく</t><rPh sb="0" eb="1"><t>カ</t></rPh><rPh sb="2" eb="9"><t>ク</t></rPh><rPh sb="2" eb="2"><t>x</t></rPh><rPh sb="1"/></si>"#;
|
||||
@@ -574,16 +1143,42 @@ mod tests {
|
||||
fn streaming_split() {
|
||||
let x = b"<r><row n='1'/><row n='2'><c/></row><other/></r>";
|
||||
let mut n = 0;
|
||||
let root = parse_streaming(x, &["row"], &mut |e| {
|
||||
let root = parse_streaming(x, Streaming { split: &["row"], children: &[("c", usize::MAX)] }, &mut |e| {
|
||||
assert_eq!(e.name, "row");
|
||||
n += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
.root;
|
||||
assert_eq!(n, 2);
|
||||
assert_eq!(root.children.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_element_deeper_than_the_streamed_level_sharing_a_split_name_is_neither_streamed_nor_held_to_the_allowances() {
|
||||
// An element named in `split` (with a namespace prefix, dropped from its name) six levels
|
||||
// below the root is not a child or grandchild of it, so it is an ordinary element of the
|
||||
// tree: not streamed, kept with everything it holds, and nothing in it counted as dropped.
|
||||
// Given children past the allowance on purpose, so counting them would show.
|
||||
let xml = "<root><list><item><c/><c/></item><item><c/></item></list>\
|
||||
<outer><middle><inner><deeper><deepest><ns:item><c/><c/><c/></ns:item></deepest></deeper></inner></middle></outer>\
|
||||
</root>";
|
||||
let mut streamed = Vec::new();
|
||||
let s = parse_streaming(xml.as_bytes(), Streaming { split: &["item"], children: &[("c", 1)] }, &mut |r| {
|
||||
streamed.push(r.children.len());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// The two streamed elements, the first cut to its one allowed child.
|
||||
assert_eq!(streamed, [1, 1]);
|
||||
assert_eq!(s.dropped, 1);
|
||||
let deep_item = ["outer", "middle", "inner", "deeper", "deepest", "item"]
|
||||
.iter()
|
||||
.try_fold(&s.root, |el, name| el.child(name))
|
||||
.expect("the deeper element stays in the tree");
|
||||
assert_eq!(deep_item.children.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_is_an_error() {
|
||||
let mut s = String::new();
|
||||
@@ -624,6 +1219,15 @@ mod tests {
|
||||
assert_eq!(decode_xstring("_xD83D__x005F_xDE00_"), "_xD83D__xDE00_");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_text_decodes_surrogates_only_within_the_same_stretch() {
|
||||
let run = |text: &str| El { name: "r".into(), children: vec![El { name: "t".into(), text: text.into(), ..El::default() }], ..El::default() };
|
||||
let mut si = El { children: vec![run("_xD83D_"), run("_xDE00_")], ..El::default() };
|
||||
assert_eq!(rich_text(&si), "😀");
|
||||
si.children[1].text_gap_before = true;
|
||||
assert_eq!(rich_text(&si), "_xD83D__xDE00_");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_escaping_preserves_carriage_returns() {
|
||||
assert_eq!(esc("a\rb"), "a b");
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Chart parity
|
||||
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (an unedited embedded chart keeps its original XML on save (#1668); chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (Pareto charts: sorted columns and a cumulative percentage line on a fixed 0–100% axis; earlier: an unedited embedded chart keeps its original XML on save (#1668); chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Excel's chart types and chart elements against GridCraft. Part of
|
||||
[target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated).
|
||||
|
||||
Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crates/chart/src`
|
||||
(layout and rendering), `crates/xlsx/src/chart.rs` (DrawingML chart parts), merged PRs #62, #116,
|
||||
#158 and #161, and issue #190. Behaviour checked against Microsoft's
|
||||
#158 and #161, and issues #1819 and #190. Behaviour checked against Microsoft's
|
||||
[Pareto](https://support.microsoft.com/en-us/excel/create-a-pareto-chart) and
|
||||
[pie/doughnut](https://support.microsoft.com/en-us/excel/add-a-pie-chart) support pages.
|
||||
|
||||
@@ -26,12 +26,12 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate
|
||||
| Surface | 3-D surface, wireframe, contour, wireframe contour | 0 of 4 | |
|
||||
| Radar | radar, with markers, filled | 1 of 3 | |
|
||||
| Treemap, Sunburst | 1 each | 2 of 2 | |
|
||||
| Histogram, Pareto | 2 | 1 of 2 | no Pareto |
|
||||
| Histogram, Pareto | 2 | 2 of 2 | Pareto groups equal categories and sums them, sorts descending, and bins numeric-only data like a histogram |
|
||||
| Box & Whisker | 1 | 1 of 1 | exclusive (default) and inclusive quartiles per series; XLSX round-trip; `chart.set {quartiles}` changes all series |
|
||||
| Waterfall, Funnel | 2 | 2 of 2 | kinds survive XLSX round-trip (PR #161) |
|
||||
| Filled map | 1 | 0 | needs geographic boundary data (licensing decision) |
|
||||
| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, 100% stacked line with or without markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | |
|
||||
| **Total** | ~60 subtypes | **28 (~47%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate |
|
||||
| **Total** | ~60 subtypes | **29 (~48%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate |
|
||||
|
||||
## Chart elements and formatting
|
||||
|
||||
@@ -137,7 +137,7 @@ column chart draws and saves its forecast series as columns, not lines.
|
||||
2. Axis options, label options, gridlines per axis, legend formatting: 10–15 h.
|
||||
3. Error bars; Format Trendline pane (trendlines landed): 4–6 h.
|
||||
4. Per-element Format pane parity, smoothed lines, exploded pie, pie/bar of pie, 100% variants: 8–12 h.
|
||||
5. 3-D column/bar/pie/area, surface and contour, Pareto: 8–12 h.
|
||||
5. 3-D column/bar/pie/area, surface and contour: 8–12 h.
|
||||
6. Chart sheets, templates and PivotChart field buttons: 5–8 h. Filled map: owner decision on boundary data.
|
||||
|
||||
## Revision history
|
||||
@@ -154,6 +154,7 @@ column chart draws and saves its forecast series as columns, not lines.
|
||||
| 2026-10-24 | minor | 100% Stacked Area: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` |
|
||||
| 2026-10-24 | minor | An unedited embedded chart keeps its original chart part, with its style, colour and user-shape parts, on save (#1668) |
|
||||
| 2026-10-18 | trivial | Stale notes: stock/combo, treemap/sunburst, box and waterfall kinds survive XLSX round-trip (PRs #158, #161) |
|
||||
| 2026-10-17 | minor | Pareto charts: sorted columns, cumulative percentage line on a fixed 0–100% axis, chartex read/write (#1819) |
|
||||
| 2026-10-18 | minor | Doughnut charts: every series is a ring (first series innermost), hole size and first slice angle modelled, editable and round-tripped; rotated slices split at 12 o'clock without overlap; legend names categories like Excel's default (#1823) |
|
||||
| 2026-10-16 | trivial | Series that refer to defined names (`[0]!Name`, `Sheet!Name`) resolve instead of showing `#NAME?`, and are saved qualified, as Excel needs (#1686) |
|
||||
| 2026-10-16 | minor | Box & whisker quartiles default to exclusive, honor each series on draw and XLSX round-trip; `chart.set {quartiles}` changes the method (#1453) |
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -28,7 +28,7 @@ workflow, would make GridCraft pre-alpha.
|
||||
| Open a colleague's XLSX, edit, save, hand it back | partial, not blocking | Typical workbooks open and save with cells, styles, CF, validation, tables, names and pivots; unmodelled parts are dropped with a warning (gap #3); Excel-side repair prompts unverified (gap #1); ~100 MB files fail (#175) | 0 for alpha (gaps #1–#3 are beta gates) |
|
||||
| Format and present: number formats, styles, conditional formatting, print or PDF | yes | Full number-format language, 47 cell styles, all CF kinds, Page Break Preview, PDF export and printing. PDF can't carry non-Latin text (gap #5) | 0 |
|
||||
| Analyze: sort, filter, tables, PivotTable | yes | Multi-level sort, AutoFilter, tables with totals, PivotTables with field list, layouts, grouping, refresh and XLSX round-trip. Calculated fields done; slicers missing (gap #8) | 0 |
|
||||
| Chart the data | partial, not blocking | Column, bar, line, pie, area, scatter, combo, histogram, box, waterfall, funnel, treemap, sunburst and stock charts are created, edited and survive save and reopen; doughnut charts draw every series as a ring (first series innermost) with editable hole size and first slice angle; trendlines are drawn; no axis options (gap #4) | 0 for alpha |
|
||||
| Chart the data | partial, not blocking | Column, bar, line, pie, area, scatter, combo, histogram, Pareto, box, waterfall, funnel, treemap, sunburst and stock charts are created, edited and survive save and reopen; doughnut charts draw every series as a ring (first series innermost) with editable hole size and first slice angle; trendlines are drawn; no axis options (gap #4) | 0 for alpha |
|
||||
| Import and export CSV | yes | Encoding and delimiter detection on read, CSV/TSV write; exports raw rather than displayed values (gap #19) | 0 |
|
||||
|
||||
**Passes:** every core workflow works end to end on macOS with save and reopen; the two partial
|
||||
|
||||
@@ -86,7 +86,7 @@ performance 8, stability 8, localization 4, hardware 2, platforms 2, ecosystem 2
|
||||
| Cell formatting, styles, conditional formatting | 10 | ~95% | ~80% | 8–14 | Full number-format language, borders, 47 cell styles, 60 table styles, all CF rule kinds including data bars, colour scales and icon sets. Gaps: font weights beyond regular/bold (#168), system fonts list (#4), themes |
|
||||
| Sort, filter, tables, validation, outline | 8 | ~82% | ~70% | 10–16 | Multi-level sort, AutoFilter, Advanced Filter, tables with totals rows; a table grows when data is typed in the row below it (not below a totals row) or the column to its right, validation, outline, subtotals, consolidate. Advanced Filter copy-to preserves cells outside its result and rejects worksheet overflow (#1031). Bugs: subtotal header (#131), validation edits (#129), table style panic caught (#130); no slicers on tables |
|
||||
| PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, GETPIVOTDATA, sort by a value field, custom captions and item names, XLSX round-trip of the layout settings refreshed file pivots need. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, Generate GetPivotData, data-model pivots. Round-trip never checked in Excel |
|
||||
| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. Doughnut charts draw every series as a concentric ring (first series innermost), with editable hole size and first slice angle. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Kinds survive XLSX round trip (#158, #161), except stock charts: only 3–4 series are a stock chart, and any other count is written and reimported as a line chart. [chart-parity.md](chart-parity.md) |
|
||||
| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 26 chart kinds, all 2-D. Doughnut charts draw every series as a concentric ring (first series innermost), with editable hole size and first slice angle. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart-sheet editing or creation, 3-D, surface or map. Trendlines are modelled and round-trip; chart sheets are kept unchanged on XLSX save. Kinds survive XLSX round trip (#158, #161), except stock charts: only 3–4 series are a stock chart, and any other count is written and reimported as a line chart. [chart-parity.md](chart-parity.md) |
|
||||
| Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, page order, Page Break Preview, headers/footers, PDF export and printing. Paper sizes match Japanese Excel: B4/B5/B6 are the JIS sizes, ISO B4/B5/B6 stay reachable by name, and Japanese Postcard (はがき), Japanese Double Postcard (往復はがき), the chou/kaku envelopes and A6 are available. No true Page Layout view; the PDF writer uses only the 14 standard fonts without embedding (no CJK or other non-Latin text in PDF); web print only exports (#141, #143) |
|
||||
| What-if and analysis | 4 | ~50% | ~40% | 22–35 | Goal Seek, Scenario Manager, data tables, Analysis ToolPak (all 19 tools, no charts), Solver (Simplex LP, a local nonlinear method and Evolutionary; Answer, Sensitivity and Limits reports; Load/Save Model, Reset All and Solver Options; no Population report), Forecast Sheet. Missing: Analyze Data |
|
||||
| Get & Transform, external data, data model | 5 | ~15% | ~10% | 60–100 | Import of CSV/TSV, JSON, HTML. No Power Query editor, no From Web, database or folder sources, no connections or refresh, no relationships or data model, no external workbook links (dropped with a warning) |
|
||||
@@ -321,8 +321,8 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
|
||||
- Draw: pen, highlighter, eraser, ink strokes and Ink to Shape. Task panes: Comments (threaded
|
||||
replies, resolve), Watch Window, Selection, Format Chart.
|
||||
- Charts: column, bar, line, area, pie, doughnut (one concentric ring per series), scatter,
|
||||
bubble, radar, histogram, waterfall, funnel, treemap, sunburst, box & whisker, stock and combo
|
||||
charts; sparklines.
|
||||
bubble, radar, histogram, Pareto, waterfall, funnel, treemap, sunburst, box & whisker, stock and
|
||||
combo charts; sparklines.
|
||||
- UI (egui): Excel-style title bar with Quick Access Toolbar and AutoSave, the full ribbon with
|
||||
galleries (cell styles, table styles, colour palettes, conditional formatting menus),
|
||||
contextual Table/Chart Design tabs, formula bar with Name Box, virtualised grid (smooth
|
||||
|
||||
Reference in New Issue
Block a user